I have two templatetags in my app which contain forms which show entries in db. When I alter data or add new entry to db, the forms show the old data. While in admin panel everything is correct (updated). When I restart the server (I mean manage.py runserver) forms show updated db entries. How to make the forms show updated data?
regards
chriss
EDIT:
file: templatetags/oceny_tags.py:
from django import template
from oceny.formularze import StudentFormularz, PrzeniesStudentaFormularz
def dodajStudenta(req):
formularz = StudentFormularz(req)
return {'formularz': formularz}
def przeniesStudenta(req):
formularz = PrzeniesStudentaFormularz(req)
return {'formularz': formularz}
register = template.Library()
register.inclusion_tag('oceny/formularz_studenta.html', takes_context = False)(dodajStudenta)
register.inclusion_tag('oceny/formularz_przenies_studenta.html', takes_context = False)(przeniesStudenta)
file: views.py view responsible for handling forms:
def zarzadzajStudentami(request):
formularze = ['dodaj_studenta', 'przenies_studenta']
req = {}
for e in formularze:
req[e] = None
if request.POST:
req[request.POST['formularz']] = request.POST
if request.POST['formularz'] == 'dodaj_studenta':
formularz = StudentFormularz(request.POST)
if formularz.is_valid():
formularz.save()
return HttpResponseRedirect(reverse('zarzadzaj_studentami'))
elif request.POST['formularz'] == 'przenies_studenta':
formularz = PrzeniesStudentaFormularz(request.POST)
if formularz.is_valid():
student = Student.objects.get(id = request.POST['student'])
grupa = Grupa.objects.get(id = request.POST['grupa'])
student.grupa = grupa
student.save()
return HttpResponseRedirect(reverse('zarzadzaj_studentami'))
return render_to_response('oceny/zarzadzaj_studentami.html', {'req': req}, context_instance = RequestContext(request))
I realize that the code may be lame in some cases. I would appreciate any other hints how to write things better.
I have too low rep to comment, but takes_context defaults to False, making your assignment redundant. Also, but now I am guessing, but it might be related to your problem.
Look for "CACHE_BACKEND= ????" in your settings.py file. The value will change as a function of which caching mechanism you are using. Comment this out and restart the server. If your values are now showing correctly, then it was a caching problem.
Are you using some kind of cache system? It could be that.
Related
Whenever I run this,
Exception Value:
name 'current_user' is not defined;
error is raised.
I am not getting where i am doing the mistake as I m new in django programming. Please help me fetch the data
# To add a new product in the database
def AddNewProduct(request):
if request.method == "POST":
current_user = request.user
product_title =request.POST['product_title']
uid = request.POST['uid']
specification =request.POST['specification']
sale_price = request.POST['sale_price']
discount = request.POST['discount']
img1 = request.FILES['img1']
img2 = request.FILES['img2']
promote_method = request.POST['promote_method']
terms_conditions = request.POST['terms_conditions']
newproduct = AffProduct(user_id=current_user.id, product_title=product_title, uid=uid, specification=specification, sale_price=sale_price,
discount=discount, img1=request.FILES.get('img1'), img2=request.FILES.get('img2'),
promote_method=promote_method, terms_conditions=terms_conditions)
newproduct.save()
# Status message
messages.success(request, 'Product added successfully')
return render(request, 'blink_network.html')
else:
return render(request, 'blink_network.html')
#Here i m trying to fetch my data.
def showproduct(request):
if request.user.is_authenticated:
result = AffProduct.objects.filter(user_id=current_user.id)
else:
result = AffProduct.objects.all()
return render(request, 'blink_viewproduct.html', {'result': result})
It looks like you will be getting that problem from showproduct(request) because you don't define current_user in that method before calling it.
to call this
result = AffProduct.objects.filter(user_id=current_user.id)
you need to define current_user = request.user beforehand
Could you share the relevant models.py file as well? You probably linked the user model with the ForeignKey with the Product model. If you did this, you need to give current_user, not current_user.id, django handles the matching itself.
Also, I guess you are using django form. If you are using it, I recommend you to use it because you can increase the readability of your code by writing less code.
Now heads up! I am fresh noob off the NOOB-BUS from NOOBSVILLE!
So i am workin on a form to load up information and edit that form information and im in a headache. so i am using:
Django: 1.8
Pyhton: 3.5.1
backend is sqlite
I am using a form.ModelForm to load information into but when it comes to saving this is where i am stuck. the documentation is very confusing should i use all or just one clean.
this is the forms.py
class EditContact(forms.ModelForm):
class Meta:
model = Contact
#the list of all fields
exclude = ['date_modified']
def clean(self):
if self.date_of_entry is None:
print("looking to see what works")
self.date_of_entry = datetime.date.today()
return
def clean_ContactID(self):
#see this line below this comment i dunno what it does
ContactID= self.cleaned_data.get('ContactID')
print ("cleaning it")
# i also dont know what validation code suppose to look like
# i cant find any working examples of how to clean data
return ContactID
now there are mainly more def clean_methods but i think what i want to use is clean which should use all but in my view.
this is in view.py
def saveContactInfo (request):
#this part i get
if request.user.is_authenticated():
ContactID= request.POST['ContactID']
a = ListofContacts.objects.get(ContactID=ContactID)
f = EditContact(request.POST,instance=a)
print("plz work!")
if f.is_valid():
f.save()
return render (request,"Contactmanager/editContact.html", {'contactID': contactID})
else:
return HttpResponse("something isnt savin")
else:
return HttpResponse("Hello, you shouldnt ")
and this is model.py
def clean(self):
if self.ConactID is None:
raise ValidationError(_('ContactID cant be NULL!'))
if self.date_of_entry is None:
print("think it might call here first?")
self.date_of_entry = datetime.date.today()
print ( self.date_of_entry )
if self.modified_by is not None:
self.modified_by="darnellefornow"
print(self.modified_by )
if self.entered_by is not None:
self.entered_by = "darnellefornow"
print(self.entered_by )
ContactID = self.cleaned_data.get('ContactID')
return
now above the model has the fields and the types which all have blank = true and null = true except for the excluded field date_of_entry
and ive gotten to find out that when calling is_valid() in views it calls the models.clean() but it fails to save!!! and i dont know why! i dont know how to do the validation. i would like to know the process and what is required and even an example of form validation a field.
I think you're wanting info/answers on a couple of things here, looking at your code comments. Hopefully this helps:
1) You only need to use the clean_FIELDNAME functions if you need to handle something custom specifically for that field. The Django docs show this as an example:
def clean_recipients(self):
data = self.cleaned_data['recipients']
if "fred#example.com" not in data:
raise forms.ValidationError("You have forgotten about Fred!")
# Always return the cleaned data, whether you have changed it or
# not.
return data
So in that block, they are checking to see if the email list provided contains a particular email.
2) That also shows another question you asked in your comments about how to handle the validation. You'll see in that snippet above, you could raise a forms.ValidationError. This is discussed more here: https://docs.djangoproject.com/en/1.10/ref/forms/validation/
So, if an error is raised in any of those clean_ methods or in the main clean method, the form.is_valid() will be false.
Does that help?
In my settings.py there are some custom settings, a few data structures that I use. These are rarely changed.
I've noticed that changing them from a view wont work.
How can I force django to reload the settings file at runtime ?
So far the only way that works is to restart the apache web server. But I want to avoid that.
In my code. I needed to kindof reinvent the #login_required decorator for a protected (admin only restricted) page. This is what I did.
In the project/settings.py I created a variable called ACCESS_CP = False
In the app/views.py I imported
from django.conf import settings
In the def login_form
# (if the user is authenticated and the user is an Active Directory Domain Admin)
settings.ACCESS_CP = True
In the def ControlPanel:
if request.method == "GET" and settings.ACCESS_CP == False:
return redirect('login')
elif request.method == "GET" and settings.ACCESS_CP == True:
settings.ACCESS_CP = False
return render(request, 'controlpanel.html')
For your application you can store configuration parameters in redis or django model.
Here is the helpful reusable app for that https://github.com/jezdez/django-constance
Also you can check other existing solutions for django configuration management:
https://www.djangopackages.com/grids/g/configuration/
Import in view.py
import django.conf as conf
def home(request):
conf.settings.SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']
conf.settings.DATABASES['default']['NAME'] = 'testdb'
Very simple question need a very simple solution. I need to add extra context to a profile view called profile_detail while still including the original context. Here is the userena view.
def profile_detail(request, username,
template_name=userena_settings.USERENA_PROFILE_DETAIL_TEMPLATE,
extra_context=None, **kwargs):
.........................
.........................
user = get_object_or_404(User,
username__iexact=username)
profile_model = get_profile_model()
try:
profile = user.get_profile()
except profile_model.DoesNotExist:
profile = profile_model.objects.create(user=user)
if not profile.can_view_profile(request.user):
return HttpResponseForbidden(_("You don't have permission to view this profile."))
if not extra_context: extra_context = dict()
extra_context['profile'] = user.get_profile()
extra_context['hide_email'] = userena_settings.USERENA_HIDE_EMAIL
return ExtraContextTemplateView.as_view(template_name=template_name,
extra_context=extra_context)(request)
I was told this would work. First I imported the userena view as userena_views. Then I tried to create my context, then send the request using the userena view and also change my urls to point to this view.
def profileview(request,username):
user=User.objects.get(username=username)
usergigs=Gig.objects.filter(user.id)
extra_context['usergig']=usergigs
return userena_views.profile_detail(request)
This didn't work, is this the right way? Is there an elegant way to do it? Or is my only option to copy the view into my views and edit from there?
Can you edit your code like this ?
def profileview(request,username):
user=User.objects.get(username=username)
usergigs=Gig.objects.filter(user.id)
extra_context['usergig']=usergigs
return userena_views.profile_detail(request, extra_context=extra_context)
I have written a simple feedback application in django. It's not particulairly complex, basically it allows authenticated users to write a shot message with a subject line and submit that message via a form. I then allows who are in a selected group to view user submitted feedback. In the future I may add more functionality but for now it does what I want.
Here comes my question, the site I'm building has multiple places where I would like to use the feedback app, for example I have a "what do you think of the site?" kind of page at /dev/feedback/ I also have one for customer support feedback at "/support/feedback/" Currently I have just copied the code from my mysite.apps.dev.feedback over to mysite.apps.support.feedback.
The problem is that this has now created two separate copies of the same code. Despite having just written the app the two versions are already starting to diverge which is annoying. My question is simply how do I create multiple instances of the same app in a django site with distinct database models?
Some resources I've found related but not helpful are https://docs.djangoproject.com/en/dev/topics/http/urls/ and Reversing namespaced URLs in Django: multiple instances of the same app The first page does not offer much on the issue and the second page provides somewhat cludgey and impractical solutions that seem to be both unrelated and more work than their worth. Is there a proper way to implement multiple instances of the same django app?
Single model approach
I'd personally try to keep this as one app and have a view that can handle being posted from multiple locations / tag them appropriately.
As S.Lott says, this is the way to go. I am providing alternatives if you're curious about methods to keep your code in one place in other situations.
For example, you could add a category field to your model, set up a single url conf which accepts an argument in the URL such as /(?P<category>\w+/feedback/$ and have the view simply tag the feedback with the appropriate category.
class MyForm(forms.ModelForm):
class Meta:
model = Feedback
def my_view(request, category):
form = MyForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
feedback = form.save(commit=False)
feedback.category = category
feedback.save()
return http.HttpResponse("Thanks for posting!")
return render(request, "mytemplate.html", {'form': form})
# urls.py
(r'^(?P<category>\w+)/feedback/$', 'my_view')
# user can visit dev/feedback or support/feedback and the feedback will be tagged appropriately
Abstract base class
Another solution is to build an abstract base class, then create subclasses for your distinct tables. That should solve the issue with your code getting out of sync.
You'd have a single abstract model (which has no tables) from which your "real" models in your separate apps would be based on.
Dynamically generated views
If you must have separate models, you could potentially write a dynamically constructed view.
def view_generator(model_class):
class MyForm(forms.ModelForm):
class Meta:
model = model_class
def my_view(request):
form = MyForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
form.save()
return http.HttpResponse("Thanks for posting!")
return render(request, "mytemplate.html", {'form': form})
return my_view
# urls.py
from foo import view_generator
(r'^my_first_feedback_form', view_generator(Model1))
(r'^my_second_feedback_form', view_generator(Model2l))
how do I create multiple instances of the same app in a django site with distinct database models?
You shouldn't.
You simply use the feedback app model in the other two apps with a simple from feedback.models import Feedback.
Then your support app can create, retrieve, update and delete Feedback objects.
Your dev app, similarly, can create, retrieve, update and delete Feedback objects because it imported the model.
That's all that's required: import.
Thanks Yuji Tomita for a very thorough answer, my final solution is derived very closely from his suggestion, but is different enough that I thought I would post it as another option if someone else runs into the same situation that I am in.
Firstly in my mysite.apps.feedback.models file I put
class Feedback( models.Model ):
subject = models.TextField( max_length=100 )
body = models.TextField( max_length=100 )
# Some other stuff here...
# Finally I used the suggestion above and created a field which I
# use to label each entry as belonging to a specific instance of the app.
instance_name = models.TextField( max_length=20 )
In my mysite.apps.feedback.views file I put
def save_message( request, instance_name ):
if request.method == 'POST':
form = FeedbackFrom( request.POST )
if form.is_valid():
form.instance.instance_name = instance_name
form.save()
return render("feedback/thanks.html")
else:
return render("feedback/submit.html", {'form':form })
else:
return render("feedback/submit.html",{'form':FeedbackForm()})
#user_passes_test( is_staff )
def all_messages( request, instance_name ):
messages = Feedback.objects.filter( instance_name = instance_name )
return render("feedback/view_all.html",{'feedback':messages} )
In my mysite.apps.dev.urls file I put
url(r'^feedback/', include('mysite.apps.feedback.urls'),
{'instance_name':'dev'}),
In my mysite.apps.support.urls file I put
url(r'^feedback/', include('mysite.apps.feedback.urls'),
{'instance_name':'support'}),
This will separate feedback messages by app instance. Note that my actual code is more complex but this should be good enough for anyone with a similar problem to get a solution up and running pretty quickly. Hope this is useful to anyone in a similar situation. Thanks again to Yuji Tomita for the suggestions upon which this solution is based.