Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Making script content 'safe' for HTTPS display (Bokeh)
I was searching for a solution and came across a removed question from maria saz. Fortunately, I was able to see it cached by google. Since I have the exact same question, I borrowed the original text: """ I'm building a website with Bokeh plots, using inline embedding. However, using an https connection to the site blocks the plots from being rendered, as the source is deemed 'unauthenticated'. Is there a way to solve this? In the 'Security Overview', it says: Blocked mixed content Your page requested insecure resources that were blocked. Where the two blocked requests were: bokeh-0.12.1.min.css bokeh-0.12.1.min.js ... """ In my case, I can add a bit of further information. The site is being built using django and google app engine, and if I allow the unsafe content, the bokeh plots work as expected. How can I serve my content so the scripts will load without the warning? -
Django, eclipse, localhost: How to allow caching of static files
I am using Django's static_serve to serve static files in our development environment (localhost, Windows). How do I add a response header such that the files will be cached on my browser? I am using Eclipse debug mode. This is not an issue in production where I'm using a CDN to serve static files. The browser used to cache these files, but at some point stopped. I don't know if it's an Eclipse thing or...? urlpatterns = [ url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}), ... From this post Turn off caching of static files in Django development server it seems that the default is to allow caching, but that's not what I'm seeing. -
Using save method to extend M2M relationship
I have a model like this class Authority(models.Model): name=models.CharField(max_length=100) country=models.ForeignKey(Country) category=models.ForeignKey(Category) competitors=models.ManyToManyField("self",related_name="competitors") I want authorities having the same country and category and itself to be automatically give an M2M relationship,so i did this def save(self,*args,**kwargs): z=Authority.objects.filter(country=self.country).filter(category=self.category) this_authority=Authority.objects.get(id=self.id) for a in z: this_authority.competitors.add(a) super(Authority,self).save(*args,**kwargs) It wasn't working and not bringing any error,I also tries this below def save(self,*args,**kwargs): z=Authority.objects.filter(country=self.country).filter(category=self.category) this_authority=Authority.objects.get(id=self.id) self.competitors=z super(Authority,self).save(*args,**kwargs) What might be wrong with my code?Thanks in advance. -
python-social-auth: request does not include session and meta fields
def register_by_access_token(request, backend): # This view expects an access_token GET parameter, if it's needed, # request.backend and request.strategy will be loaded with the current # backend and strategy. token = request.GET.get('access_token') user = backend.do_auth(request.GET.get('access_token')) if user: login(request, user) return 'OK' else: return 'ERROR' This example from different resources. I use django 1.9, but this code fails with 'GET' doesn't exists and i rewrite this function like this: def UserLogin(request, backend, details, response, *args, **kwargs): # This view expects an access_token GET parameter, if it's needed, # request.backend and request.strategy will be loaded with the current # backend and strategy. token = response['access_token'] user = backend.do_auth(token) arg = {} arg['user'] = user if user: login(request, user) return HttpResponseRedirect('/', arg) As a result i have loop of redirect and server return http error with too many redirects. After all i tries write my own backend: class AuthBackend(object): def authenticate(self, access_token, id, add_info, **kwargs): print 'authenticate backend' user = None print 'access_token='+access_token try: prof = qProfile.objects.get(facebook_uid=id) user = User.objects.get(pk=prof.muser_id) print "i've found this user and return pk" except Exception as Error: try: print 'kwargs:'+str(kwargs) print "can't get user and have this error:"+str(Error) user = User.objects.create(email = add_info['email']) user.first_name = add_info['first_name'] user.last_name = add_info['last_name'] … -
How to set equal fields in formset?
I have a formset with maximum number of forms 2. It's a reservation form. When user choose "round trip", the second form is shown and activated to choose date and time of the second ride. The problem is that both forms contain fields like first_name, last_name which is required. In fact, user have to fill first_name, last_name once - in the first form and after submit, two Reservation objects would be created - with the same first_name, last_name... . In the template, I render only date,time,last_name,first_name for first form and if round trip is checked, date and time for the second form. Problem is that when I click to submit, it returns error - is_valid() is False because first_name,last_name and telephone are required for second form too. My idea was simple: def view(request): if request.method == 'POST': if formset.is_valid(): first_name = formset[0].cleaned_data['first_name'] last_name = formset[0].cleaned_data['last_name'] telephone = formset[0].cleaned_data['telephone'] date_1 = formset[0].cleaned_data['date'] time_1 = formset[0].cleaned_data['time'] date_2 = formset[1].cleaned_data['date'] time_2 = formset[1].cleaned_data['time'] Reservation.objects.create(first_name=first_name, last_name=last_name, date=date_1, time=time_1...) Reservation.objects.create(first_name=first_name, last_name=last_name, date=date_2, time=time_2...) What would you do? -
Django - How to restrict foreign key choices in dropdown menu depending on datatime field
I have form for adding data in database and I want to restrict foreign key choices in my dropdown menu. It have to be restricted on my finishDate field. If finishDate is date before today (eg. today is 21-08-2016 and finishDate is 30-06-2013), then I don't want to show foreign key value of that finishDate. What is the easiest way to do this? I am relative new at this, so I need help. models.py class Account(models.Model): startDate = models.DateField(verbose_name="Start") finishDate = models.DateField(verbose_name="Finish") def __str__(self): return 'A{}'.format(self.id) class Net(models.Model): date = models.DateTimeField(default=datetime.now()) MB = models.IntegerField(validators=[MinValueValidator(1)],default=randint(100,2000)) idAccount = models.ForeignKey(Account, on_delete=models.CASCADE, verbose_name="Account") def __str__(self): return 'Record {}'.format(self.datum) forms.py class NetForm(ModelForm): class Meta: model = Net fields = ['idAccount'] views.py @login_required(login_url="/accounts/login/") def net(request): if request.method == 'POST': form = NetForm(request.POST) if form.is_valid(): internet = form.save() return HttpResponseRedirect('/') else: form = NetForm() return render(request, 'project/Net.html', {'form': form}) Thanks a lot! -
Saving django model with DateTime fields
Model: class Meal(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) collection_from = models.DateTimeField(blank=False, null=False) discount_price = models.DecimalField(blank=False, null=False, decimal_places=2, max_digits=4) normal_price = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=4) available_count = models.IntegerField(blank=False, null=False) name = models.CharField(blank=False, null=False, max_length=255) active = models.BooleanField(blank=False, null=False, default=True) Now, when I'm saving it's instances the created_at and updated_at values are set properly, eg: 2016-08-21 13:13:57.585472+02. collection_from value should be nearly the same as those two previous ones, but it's getting set to point to the next day, eg: 2016-08-22 01:00:00+02 which I don't get at all :). The collection_from value looks like that when sent by the browser: 2016-08-21 23:00. I believe I have proper settings set up int the settings.py file: TIME_ZONE = 'UTC' USE_TZ = True So what's the problem here? How do I make django save collection_from value the same way as created_at or updated_at? -
RelatedObjectDoesNotExist at /review/add/1/
I have a review app where user gets to review a restaurant.I have created a form for review and views but i am getting an error submiting the form to review a restaurant. I get RelatedObjectDoesNotExist at /review/add/1/ with an exception of review has no restaurant Following is my model for review class Review(models.Model): user = models.ForeignKey(User) restaurant = models.ForeignKey(Restaurant) review = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) forms.py class ReviewForm(ModelForm): class Meta: model = Review fields = ['review'] widget = { 'review':Textarea(attrs={'cols':40, 'rows':10}) } views.py def add_review(request, review_id): restaurant = get_object_or_404(Restaurant, pk=review_id) print('restaurant from review form',restaurant) if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): review = form.cleaned_data['review'] review = form.save(commit=False) Review.objects.create(user=request.user,restaurant=restaurant,review=review) return redirect('/restaurants/') else: form = ReviewForm() return render(request, 'review/review_form.html', {'form':form}) -
django custom property to return filtered field
In a django app, with an existing databse, I've used inspectdb to build a model: class Sensorparser(models.Model): """ a read-only implemenation to access the MeshliumDB """ id_wasp = models.TextField(blank=True, null=True) id_secret = models.TextField(blank=True, null=True) frame_type = models.IntegerField(blank=True, null=True) frame_number = models.IntegerField(blank=True, null=True) sensor = models.TextField(blank=True, null=True) value = models.TextField(blank=True, null=True) timestamp = models.DateTimeField() raw = models.TextField(blank=True, null=True) parser_type = models.IntegerField() def save(self, *args, **kwargs): return def delete(self, *args, **kwargs): return class Meta: managed = False db_table = 'sensorParser' I added the save and delete methods, because this should be a read-only model. One of the fields is sensor, which defines strings for different, well, "sensors" (e.g. BAT, ANE, etc.). I would like to have a property: @property def battery() return self.sensor.objects.filter(sensor='BAT') How should I accomplish this? -
Filtering Paginated Results Django
I extended ListView in Django to paginatedListView as following class paginatedListView(ListView): per_page = 20 def get_queryset(self): qs = super(paginatedListView,self).get_queryset().order_by('-creation_datetime') paginator = Paginator(qs,self.per_page) try: page_num = int(self.request.GET.get('p', '0')) except ValueError: page_num = 0 try: page = paginator.page(page_num + 1) except (EmptyPage, InvalidPage): page = paginator.page(paginator.num_pages) self.cl = InlineChangeList(self.request, page_num, paginator) self.paginator = paginator if self.cl.show_all: return qs else: return page.object_list def get_context_data(self,**kwargs): context = super(paginatedListView,self).get_context_data(**kwargs) context['cl'] = self.cl return context Now I have another view which extends paginatedListView, the queryset of this view should contain Order instances that follow a condition so i try to apply filter in its get_queryset() class orderList(paginatedListView): template_name = "dashboard/reports.html" model = Order def get_queryset(self): qs = super(orderList,self).get_queryset().filter(Order_status=Order.ORDER_PLACED) return qs But this returns a error which says Cannot filter a query once a slice has been taken. I know why Django is throwing this error, one way I know how to make this work is just rewrite the whole code of paginatedListView in orderList and apply filter before pagination. But is there any other elegant way of doing it? -
How to filter model_set in django
Here is my part of template: {% for sitting in c.sittings %} {% if sittings.sit_date == sittings.shiftdate_set.all %} <p>Firstly it was scheduled on {{sitting.sit_date}}</p> {% endif %} {% endfor %} But this code return all the sitting dates not particularly equal to sit_date of Shiftdate model. I can't filter sit_date from shiftdate_set. I also tried to using following method in Sitting model: def get_shiftdate(self): return self.shiftdate_set.filter(shift_date=self.sit_date) and Using it in the above template as: {% for sitting in c.sittings %} {% if sittings.sit_date == sittings.get_shiftdate %} <p>Firstly it was scheduled on {{sitting.sit_date}}</p> {% endif %} {% endfor %} But still I am getting all the sitting dates not only related sitting dates. Could anybody help to figure out what I am doing wrong. -
How to copy queryset Django
I am trying to access queryset of ManyToManyField before and after saving in def save_related(self, request, form, *args, **kwargs) method. I want to compare them and get new objects, that were added to ManyToManyField. So, I am getting old queryset with: def save_related(self, request, form, * args, * * kwargs): obj = form.instance queryset_before = obj.translations.all() print(queryset_before) super(WordAdmin, self).save_related(request, form, * args, * * kwargs) print(queryset_before) But print(translations_before) outputs the new, updated queryset after calling super().save_related. So: How to copy queryset, so that saving will not affect it? Or is there a way to compare old and new values of ManyToManyField more properly? -
django: return Fields as different types than defined in database
In a django app, with an existing databse, I've used inspectdb to build a model: class Sensorparser(models.Model): """ a read-only implemenation to access the MeshliumDB """ id_wasp = models.TextField(blank=True, null=True) id_secret = models.TextField(blank=True, null=True) frame_type = models.IntegerField(blank=True, null=True) frame_number = models.IntegerField(blank=True, null=True) sensor = models.TextField(blank=True, null=True) value = models.TextField(blank=True, null=True) timestamp = models.DateTimeField() raw = models.TextField(blank=True, null=True) parser_type = models.IntegerField() def save(self, *args, **kwargs): return def delete(self, *args, **kwargs): return class Meta: managed = False db_table = 'sensorParser' I added the save and delete methods, because this should be a read-only model. This works great, but the thing is the database has defined (or at least inspectdb suggested) that id_wasp and id_secret and value are type TextField. This is correct, as they are in the database, but in my app I would like to treat them as type IntegerField. Is it okay to simply use those types of fields instead? E.G.: class Sensorparser(models.Model): ... id_wasp = models.IntegerField(blank=True, null=True) id_secret = models.InteferField(blank=True, null=True) ... id_value = models.FloatField(blank=True, null=True) I'm asking because I've done this, and it works, but I want to know if it is valid, or may cause me problems down the road. Thanks! -
django - update details using forms
For my django application, I have created signup and login pages. signup handles the signing up of a user with: full_name,user_email and password fields. Similarly, login logs the user in after authentication and the login.html has a logout button and associated view that handles logout with session variables. Now, after signing in I want to have another form that asks for more details like: postal_address, date_of_birth etc. (say 5 more fields) with a CREATE button that adds all these details to a separate table. When the user next logs in, he should see all his details printed out with an UPDATE button that will take him/her to the same form where he can change his details if he needs to. This means the previously created details should still appear in the textboxes and the user must be able to modify them. How would I go about achieving the above? I'm assuming the UPDATE button only shows up once the user's session starts? Any guidance, ideas or references to go about this would be much appreciated. -
changing s3 storages with django-storages
I have a Django application where I use django-storages and amazon s3 to store images. I need to move those images to a different account: different user different bucket. I wanted to know how do I migrate those pictures? my main concern is the links in my database to all those images, how do I update it? -
Django select_related join model attributes with a single query
I'm trying to find a optimal solution with a single query to retrieve attributes on a join model. I have the following models relationships: class Player(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) season_team = models.ForeignKey(SeasonTeam, related_name='players', blank=True, null=True) leagues = models.ManyToManyField(League, related_name='players', through='PlayerLeague') class League(models.Model): name = models.CharField() class PlayerLeague(models.Model): player = models.ForeignKey(Player) league = models.ForeignKey(League) stamina = models.PositiveSmallIntegerField(_('Stamina'), default=100) class Team(models.Model): name = models.CharField(max_length=30, validators=[ RegexValidator(regex='^[a-zA-Z0-9\s]+$', message=_('name must contain only chars and numbers'), ), ]) players = models.ManyToManyField(Player, blank=True, related_name='teams') league = models.ForeignKey(League, related_name='teams') This is the view where I want all players loaded in get_context_data to preload stamina attribute class FormationUpdateView(AjaxResponseMixin, FormationRequirementsMixin, UpdateView): model = Formation template_desktop = 'hockey/formation/form.html' template_mobile = 'hockey/formation/mobile/form.html' form_class = FormationForm def get_initial(self): self.initial = {'active': True} return self.initial.copy() def get_context_data(self, **kwargs): context = super(FormationUpdateView, self).get_context_data(**kwargs) team = Team.objects.select_related('league').get(formations=self.kwargs['pk']) context['players'] = Player.objects.filter(teams=team).all() context['league'] = team.league return context def get_queryset(self): return Formation.objects.select_related() def get_template_names(self): if 'Mobile' in self.request.META['HTTP_USER_AGENT']: return self.template_mobile return self.template_desktop My first solution was by adding a stamina method to Player class: def stamina(self, league): p_l = self.leagues.through.objects.filter(league=league)[0] return p_l.stamina I don't like this solution because is going to query for each player its stamina value. Thank you for any help -
Django: how to send argument in HtpResponseRedirect
Views.py from django.shortcuts import render from django.template.context_processors import csrf from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from .models import studentDetails from .forms import loginForm # Create your views here. def login(request): c = {} c.update(csrf(request)) return render(request, "login.html", c) def auth_view(request): username = request.POST.get("username", "") password = request.POST.get("password", "") q = studentDetails.objects.get(name=username) if q.password==password: return HttpResponseRedirect("/student/accounts/loggedin") return HttpResponseRedirect("/studemt/accounts/invalid") def loggedin(request): username = request.GET.get("username") return render(request, "loggedin.html", {"full_name": username}) def invalid(request): return render(request, "invalid_login.html") def logout(request): return render(request, "logout.html") Urls.py from django.conf.urls import url from django.contrib import admin from .views import ( login, auth_view, loggedin, logout ) urlpatterns = [ url(r"^accounts/login/$", login , name="login"), url(r"^accounts/auth/$", auth_view ,name="auth_view"), url(r"^accounts/loggedin/$", loggedin , name="loggedin"), url(r"^accounts/logout/$", logout, name="logout"), ] i want to send username from auth_view to loggedin view but i don'y know how to do that. i have used username = request.GET.get("username") but it is not working. i want to show username in url also such that it looks like /student/username/ where username will change as different user login. -
Cannot select an option in jquery autocomplete plugin if input does not match from the data in data source ajax response
I am using jquery autocomplete plugin https://jqueryui.com/autocomplete/. i want auto complete to show menu and on selection of name it should be able to display price in the price text box,i am using min length of 1. But the problem is i am only able to select option if my first input character matches to the data in ajax response and if i enter a character which is not present in ajax response and then when i hit backspace key to remove the characters and enter new character which matches the data source : ajax response ...the autocomplete menu opens but it stucks and not able to select the option. for example:- I have 6 fruits in my database. Name :Apple Price :50 Name :Mango Price :40 Name :banana Price :30 Name :cherry Price :60 Name :sweetlime Price :40 Name :fig Price :20 so the problem is if i enter a in the first place then i can select apple mango banana and its price is also reflecting in respective textbox but if i enter x in the first place or any value which is not in my database then if i use backspace and again put a then suggestion … -
Trying to do some asynchronous processing in django on heroku using Redis Queue
I am trying to upload bigger files to s3 asynchronously.I have followed documentaion from http://python-rq.org/ . Worker is running but it is not doing doing the job. views.py def youmaterial(request): if request.method == 'POST': newdoc = Youmaterial(docfile = request.FILES['file'],user=request.user) newdoc.save() msg='dee' # Redirect to the document list after POST return HttpResponse(json.dumps({'message': msg})) else: form1 = DocumentForm() return render(request,'mat_upload.html',{'form':form1}) def create_job(): redis_conn = Redis() q = Queue(connection=redis_conn) # no args implies the default queue # Delay execution of count_words_at_url('http://nvie.com') job = q.enqueue(youmaterial, 'http://heroku.com') worker.py import os import urlparse from redis import Redis from rq import Worker, Queue, Connection listen = ['high', 'default', 'low'] redis_url = os.getenv('REDISTOGO_URL') if not redis_url: raise RuntimeError('Set up Redis To Go first.') urlparse.uses_netloc.append('redis') url = urlparse.urlparse(redis_url) conn = Redis(host=url.hostname, port=url.port, db=0, password=url.password) if __name__ == '__main__': with Connection(conn): worker = Worker(map(Queue, listen)) worker.work() Procfie: web: gunicorn gettingstarted.wsgi --log-file - worker: python -u worker.py Settings.py(This gives me error.) DJANGO_SETTINGS_MODULE=config.settings rqworker high default low -
Django Model Form - Not Valid without any errors
I am writing a test for a Django Form. I am populating it with initial data. But when i save the form i get the error that it does not have cleaned_data attribute. This may happen because the form does not validate but it does not show any errors either. here is the code. def test_keyw(self): class BlogPostKeywordCheck(forms.ModelForm): class Meta: model = BlogPost exclude = () data = {'keywords': 'awwww,aaa,lol'} initial_data = { "title":"Test Keywords", "content":"<p>Testing Keywords</p>", "status":CONTENT_STATUS_PUBLISHED, "keywords":"call,me,abc", "user":self._user, "allow_comments":"on", "gen_description":"on", "in_sitemap":"on", "_save":"Save" } print (self._user) submitted_form = BlogPostKeywordCheck(initial=initial_data) print (submitted_form.fields) submitted_form.instance.user = self._user print("Instance Title",submitted_form.instance.title) print("Valid: ",submitted_form.is_valid()) print ("Errors: ",submitted_form.errors) submitted_form.save() print (Keyword.objects.all()) self.assertTrue(submitted_form.is_valid()) print (submitted_form.errors) Currently the O/P is Creating test database for alias 'default'... test OrderedDict([('title', <django.forms.fields.CharField object at 0x05185CF0>), ('slug', <django.forms.fields.CharField object at 0x05185BD0>), ('_meta_title', <django.forms.fields.CharField object at 0x05185ED0>), ('description', <django.forms.fields.CharField object at 0x05185E10>), ('gen_description', <django.forms.fields.BooleanField object at 0x05185C10>), ('keywords', <django.forms.fields.CharField object at 0x05185CD0>), ('status', <django.forms.fields.TypedChoiceField object at 0x05185C50>), ('publish_date', <django.forms.fields.DateTimeField object at 0x05185B10>), ('expiry_date', <django.forms.fields.DateTimeField object at 0x05185D90>), ('short_url', <django.forms.fields.URLField object at 0x05185AD0>), ('in_sitemap', <django.forms.fields.BooleanField object at 0x05185FD0>), ('content', <django.forms.fields.CharField object at 0x05182E50>), ('user', <django.forms.models.ModelChoiceField object at 0x05182350>), ('categories', <django.forms.models.ModelMultipleChoiceField object at 0x051820D0>), ('allow_comments', <django.forms.fields.BooleanField object at 0x051821F0>), ('featured_image', <filebrowser_safe.fields.FileBrowseFormField object at 0x05182310>), ('related_posts', … -
Upload images in Django trough Ajax without submitting entire form
I have 4 ModelForms and 1 form in the same template, I'm using the same <form> tag to all of them, so they are all part of the same form and when I submit it all the data will be sent. I can separate it in three <form> if that will help, but the file input must be with other data that I don't want to submit, I saw solutions that uses this var data = new FormData($('form').get(0)); but it sends all the form and I don't konw how to get the data in that way. This is how my template looks: When I press the button, (is a button type, not a submit) the image will be uploaded to the server and it's route will be saved to the database and then it's primary key will be sent trough Ajax in a json array. All the other data will be sent to a html table for a posterior submit. This is my model: class Fotografia(models.Model): idfotografia = models.AutoField(db_column='idFotografia', primary_key=True) # Field name made lowercase. nombre_fotografia = models.CharField(max_length=45, blank=True, null=True,default='s/n') ruta_fotografia = models.ImageField(upload_to = '') #settings.MEDIA_ROOT estado_fotografia = models.BooleanField(default=True) principal_fotografia = models.BooleanField(default=False) This is what I have tried in ajax … -
Function call on individual field save in django
Say I have a model: class Workplace(models.Model): name = models.CharField(max_length=255) ... office_mail_id = models.EmailField(null=True, blank=True) What I want is whenever the value of email is changed and the object is saved, a function should be run which would save the value of that field to other models (say Emails) Now, this can be done in many ways like creating a custom save function which would call the email saving function or otherwise making a custom function and save emails through it: def set_email(self, email): self.office_mail_id = email self.save() # do whatever i want return What i want to know is that is there a simpler way to do this so that whenever i run company.office_mail_id = request.POST.get('email') company.save() in a view, the function may be run saving it to other models as i want The problem here is that I am not saving all fields individually but making a dictionary and saving all fields based on key and values like this as there are so many fields: for key in dictionary: setattr(workplace, key, dictionary[key]) workplace.save() What can be the best way to do it? -
Show if restaurant is open or closed based on weekday, opening and closing time
I have a model of restaurant and operating time which has foreign key relation. for example a restaurant ocean view cafe whose operating time in each week day is Friday - 10am - 6:30pm Thursday - 10 am - 9:45 pm Wednesday - 10 am - 9:45 pm Tuesday - 10 am - 9:45 pm Monday - 10 am - 9:45 pm Sunday - 10 am - 8 pm I could only check based on opening and closing time like this @property def open_or_closed(self): operating_time = OperatingTime.objects.all() opening_time = operating_time.opening_time closing_time = operating_time.closing_time current_time = datetime.now().time() weekday = operating_time.day_of_week if opening_time < current_time < closing_time: open_or_closed = True else: open_or_closed = False return self.open_or_closed How can i find if restaurant is open or closed on each day for all the restaurant? -
Two dates are equal from date field of two model in django
My template where I am checking two dates from two model are equal: sittings.sit_date = '{{ sittings.sit_date }}'<br> shiftdates.shift_date = '{{ shiftdates.shift_date }}'<br> {% if sittings.sit_date == shiftdates.sit_date %} <p>Equal on {{shiftdates.sit_date}} {% else %} Not Equal {% endif %} Here Sitting model are linked with Shiftdate model as a foreign key. This gave output: Logo sittings.sit_date = '' shiftdates.shift_date = '' Equal on Here you see no dates was shown. How to show which dates are equal of two fields? Any help will be much appreciated. -
Not able to pass logical answer received from Form to NullBoolean model
My model is like class mymodel(models.Model): param1=models.NullBooleanField(blank=False) My form is class MyForm01(forms.Form): LCHOICES=[(True, 'Yes'),(False,'No')] answer=forms.ChoiceField( label='Question', choices=LCHOICES, widget=forms.RadioSelect(), help_text='Help text') I am trying to pass the user choice to a model for saving as below, where id_number is a new number for new object creation. myobj=mymodel.objects.create( id=mymodel.objects.get(id=id_number), param1=form.cleaned_data['answer'] ) Everything happens, including new object creation but the data passed is always True even when the original answer is negative. If I take a print of answer its coming as False. Also if I change form.cleaned_data.['answer'] to False, it is well accepted. Where am I making a mistake?