Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Duplicate resuts after annotation on django queryset
I'm working with Django 1.10 with Django REST framework and need to create a filter on a relationship like this class Player(models.Model): name = models.CharField(max_length=20, null=True, blank=True) class Score(models.Model): player = models.OneToOneField('companies.Company') class ScorePeriod(models.Model): score = models.ForeignKey('Score', on_delete=models.CASCADE) period = models.DateField() period_score = models.PositiveIntegerField() The Player filter should filter by last period_score but only if the last period is before a given year. If the year is 2015 and there are ScorePeriod for 2016 and 2015 it should filter by the 2015 period_score. In case there are 2014 and 2013 ScorePeriod and the given year is 2015 should filter by 2014. In the views I'm using annotations so I can just filter by last_score in the filter file. This is the view. queryset = super().get_queryset() max_year = get_starting_year() queryset = queryset.annotate( last_score_year_available=Max(Case( When(score__scoreperiod__period__year__lte=max_year, then=F('score__scoreperiod__period')), output_field=DateField() )), ) queryset = queryset.annotate( last_score=Case( When(score__scoreperiod__period__year=F('last_score_year_available'), then=F('score__scoreperiod__period_score')), default=None, output_field=IntegerField(), ), ) return queryset This works as filter correctly but returns one duplicate for each ScorePeriod in the database. Also when getting something like "players/1" will fail because there are multiple objects in a get(). -
Display JSON as table in Django
I have the following JSON file [{ "ID": 1, "Name": "John Smith", "IDNumber": "7606015012088" }, { "ID": 2, "Name": "Molly Malone", "IDNumber": "8606125033087" }] Which I want to display it in table format.I have parsed the json file using json.load(filename) I have tried something like: Views.py import json from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.template.loader import render_to_string # Create your views here. with open('/home/kunal.jamdade/Desktop/PyCharmProjects/demo.json') as d: data = json.load(d) def load_json_table_format(request): print(data) html = render_to_string() return HttpResponse({'d':data}, 'demoApp/demo.html', content_type="application/html") #return JsonResponse(data, safe=False,content_type="application/html") #return render(request, 'demoApp/demo.html', {'d': data}, content_type="application/html") demo.html <body> {% if data %} <table> {% for k in d %} {% for item_1, item_2 in k.items %} <tr> <td>{{ item_1 }}</td> <td>{{ item_2 }}</td> </tr> {% endfor %} {% endfor %} </table> {% endif %} </body> But it is not printing the anything? -
form not updating itself using multiple steps URLS
I am editing a questionnaire app using a diplay_by_question template where each question is displayed on a single page using a different URL in the form of survey/22; suvey/22-1; survey/22-2 .... When saving the answers the form should take the actual step we are in and save it in the database. For example if I am at URL survey/22-2 is referencing to survey ID: 22 and step : 1 In my code it shoud extract from my form the data using the current step: form = ResponseForm(request.POST, survey=survey, user=request.user, step=kwargs.get('step', 0)) However I do not understand why if the URL is step 1 the step does not update and stay at step 0 Could you please help ? viexs.py: class SurveyDetail(View): def get(self, request, *args, **kwargs): survey = get_object_or_404(Survey, is_published=True, id=kwargs['id']) if survey.template is not None and len(survey.template) > 4: template_name = survey.template else: if survey.display_by_question: template_name = 'survey/survey.html' else: template_name = 'survey/one_page_survey.html' if survey.need_logged_user and not request.user.is_authenticated(): return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) categories = Category.objects.filter(survey=survey).order_by('order') form = ResponseForm(survey=survey, user=request.user, step=kwargs.get('step', 0)) context = { 'response_form': form, 'survey': survey, 'categories': categories, } return render(request, template_name, context) def post(self, request, *args, **kwargs): import pdb; pdb.set_trace() survey = get_object_or_404(Survey, is_published=True, id=kwargs['id']) if … -
Missing table name in IntegrityError (Django ORM)
I am missing the table name in IntegrityError of Django: Traceback (most recent call last): ... return self.cursor.execute(sql, params) File ".../django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File ".../django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) IntegrityError: null value in column "manager_slug" violates not-null constraint DETAIL: Failing row contains (17485, null, 2017-10-10 09:32:19, , 306). Is there a way to see which table the INSERT/UPDATE is accessing? We use PostgreSQL 9.6. -
How to query to fetch last 5 months records?
I have a model named 'DemoModel' it has a field called demo_date. I want to fetch the last 5 months i.e;(from current month records to past 5 months records) records by querying on the demo_date field. My models look like class DemoModel(models.Model): demo_date = models.DateTimeField() -
unresolved reference 'path' - django
I have installed python 3.6.2 and then django 1.11.6 I have added the 'pip' and 'django' path inside "PATH" variable in environmental variables in both sections User Variables : C:\Users\Moh3n\AppData\Local\Programs\Python\Python36\Scripts C:\Users\Moh3n\AppData\Local\Programs\Python\Python36\Lib\site-packages\django C:\Users\Moh3n\AppData\Local\Programs\Python\Python36\Lib\site-packages System Variables : c:\Users\Moh3n\AppData\Local\Programs\Python\Python36\Scripts C:\Users\Moh3n\AppData\Local\Programs\Python\Python36\Lib\site-packages C:\Users\Moh3n\AppData\Local\Programs\Python\Python36\Lib\site-packages\django Then I created a project with django and created a simple app named"polls" in polls/urls.py i typed [("from django.urls import path")] [enter image description here]1 then pycharm poped a box saying (unresolved reference 'path') I didn't pay attention at first and then in mysite/urls.py typed enter image description here the same thing happend for "include,path" at the end when i ran server in cmdier with the code (py manage.py runserver) , in saw this (because I neet at least 10 reputation to post mor than 2 links I placed my image url here:) i.stack.imgur.com/BYK3S.png if you could help me to find where the problem is I'd really appreciate. -
Jquery Logic for showing div of that instance after submitting form
I need to show div after i have submitted the reply form, It is working but it is showing the another parent's comment replies too which i do not need as per my requirement. I want to show the div for only that instance where i am replying or submitting the form. Please help with the code comment_section.html {% for comment in comments %} <blockquote> <p>{{ comment.content }}</p> <footer><i>by</i> {{ comment.user|capfirst }}</footer> <button type="button" class="reply-btn pull-right btn btn-default">Reply</button> <div class="replied-comments" style="display:None;"> <blockquote> {% for reply in comment.replies.all %} <p>{{ reply.content }}</p> <footer>{{ reply.user }}</footer> {% endfor %} </blockquote> <form method="POST" id="reply-form"> {% csrf_token %} <input type="hidden" name="parent_id" value="{{ comment.id }}"> {{ comment_form.as_p }} <input type="submit" name="" value="Reply" class='btn btn-default'> </form> </div> </blockquote> {% endfor %} jquery script with ajax to show div for one instance $(document).on('submit', '#reply-form', function(event){ event.preventDefault(); $.ajax({ data: $(this).serialize(), type: "POST", url: $(this).attr('action'), success: function(data){ $('#div1').html(data['form']); $('textarea').val(''); $('.reply-btn').click(function(){ $(this).next('.replied-comments').fadeToggle(); }); #problem occuring here $('.reply-btn').next('.replied-comments').show(); }, error: function(e){ console.log(e) } }); }); -
Rooting log files with daemon mode
I'm using mod_wsgi (v.4.5.20), installed with pip, in daemon mode, using a "main" apache instance as front (reverse proxy). I'm serving a django application, the "main" server hosts some other applications. I'ld like to record the log files to a "known" directory. For now, the log files are recorded into the directory generated by the daemon-mode, aka. --server-root directory. The process is launched through a systemd service. On the "main" apache settings, I've set the ErrorLog and CustomLog directives to my "wanted" log directory, but no files are recorded. The "main" apache settings: (Note the X-Forwarded-For switch for company reverse proxy) https://gist.github.com/frague59/0c9717bd5668140de392019874373f0a Thanks for your help ! -
Clarification about Django-Oscar
I have already finished setting up my home,about,contact us page using bootstrap in one project. I wanted to use the django-oscar for the e-commerce configuration and use it in my products page. Do I need to add another project or just create another app for django-oscar? Thank you so much for the clarification. By the way I created another project and currently stuck on how to connect it the first project I have made -
How to make api call from react hotreload server to django server?
I am trying to develop a website with react and django. I have react hotreload running in localhost:8080 and django on localhost:8000. Now when I try to make a api call to django server for data than chrome throws the following error: There has been a problem with your fetch operation: Failed to execute 'fetch' on 'Window': The origin of 'http://localhost:8000/' should be same as 'http://localhost:8080' I am using ubuntu 16.04 as my dev machine. Please help. -
How to properly paginate comments table by time
This question isn't so much about Django as it is about general pagination. Consider the following table of comments. | auto_inc_id | comment | timestamp | |-------------|-------------------------|-----------| | 1 | I sure love pie | 1000 | | 2 | I hate mondays | 2000 | | 3 | I want to watch a movie | 3000 | | 4 | hello world | 2500 | This is a simple table of user comments. When a user clicks "submit", the server pushes the event onto a processing queue. Due to the nature of the processing queue (this might take 1-2 hours). So in order to get the "real time of submission" the client interface also generates a timestamp that it bundles up with the request (I know this is spoofable) When the event gets finally dequeued. They are inserted into the table. There is also an app that queries this table, and displays a scrolling list of comments (most recent first - at the top). The user can scroll to the bottom and click "more" - which will load even older comments onto the app screen - and so on and so forth. I was planning to use a simple … -
Django-allauth not asking for permission while using facebook
While trying to login the application I have seen the Django-Allauth do not ask for the permissions for accessing the profile data. It just simply ask for the password for reauthentication purpose (even after using the oauth2 or js_sdk). See the following image which shows the current login screen: I expect the login should be like the following: Please let me know how I can achieve this in Django-allauth -
Setting up Mimetype when to show a mp4/webm in all browsers in Django
I'm trying to understand how I can have my website properly display - specifically a banner video. I think the issue relates to Mimetype - It works from my computer but not when server from a server. This is the website https://consultingpage.herokuapp.com/ . I assume that the issue is within my settings.py or urls.py - I'll put them below. Urls.py """ The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf import settings from django.conf.urls import url from django.contrib import admin from django.conf.urls.static import static from profiles import views as profiles_views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', profiles_views.base, name='base'), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and Settings.py """ Django settings for alex1 project. Generated by 'django-admin startproject' using Django 1.11.4. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For … -
AllAUTH Django not redirecting to Home Page
I am trying to make a Django 1.11.5 Application including the Facebook Login using AllAuth. Settings.py SITE_ID = 1 LOGIN_REDIRECT_URL = '/' SOCIALACCOUNT_QUERY_EMAIL = True SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'SCOPE': ['email', 'user_posts'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'METHOD': 'js_sdk', 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', ], 'EXCHANGE_TOKEN': True, 'VERIFIED_EMAIL': True } } ACCOUNT_LOGOUT_ON_GET = True The problem is: When I click on the login through link a box appear for password. If I cancel the box then the error or cancel template appears on the browser like the below: I want that this page should not appear. Instead, the URL must redirect to HomePage. Hence I tried the following in my URLS.py url(r'^accounts/social/login/cancelled/$', RedirectView.as_view(pattern_name='homeIndex', permanent=False)) But has no effect on the browser. Please let me know what I am missing in the implementation to improve my functionality. -
Remove item with empty value in django dictionary
I want to remove dictionary item on my list. Animals = ['dog', 'cat', 'fish', 'goat'] Owner = ['Nash', 'Luffy', '', ''] C = dict(zip(Animals, Owner)) C = {'dog':'Nash', 'cat':'Luffy', 'fish':'', 'goat':''} What should I do to achieve the result below: C = {'dog':'Nash', 'cat':'Luffy'} -
django class based view shared code between post and get
I'm making a Django app and I was wondering if there was a way I can call a method dosomecheckups in both post and get method without having to type it twice. Keep in mind, I need the request object for my checkup method. NB: I don't want to use decorators for now. class Welcome(View): def get(self, request): #I wanna avoid having the method below both in post and get self.dosomecheckups(request) ... def post(self, request): #I wanna avoid having the method below both in post and get self.dosomecheckups(request) ... def dosomecheckups(self, request): # request is required for this checkup so __init__ isn't an option pass -
How to save the django model after its many to many field and foreign key saved
I am working on a Django project, which has a number of fields including many ForeignKey and ManyToMany Fields. and I am trying to create a flat json file by serializing this model so that I can index it into an elastic search server by using elasticsearch-DSL. models.py class Video(models.Model): """Video model""" title = models.CharField( max_length=255, ) education_levels = models.ManyToManyField( EducationLevel, verbose_name=_("Education Level") ) languages = models.ManyToManyField( Language, verbose_name=_("Languages") ) def save(self, *args, **kwargs): # Save the model instance super(Video, self).save() # After saving model instance, serialize all the fields # And save to elastic search self.serialize() def serialize(self): """Method that serialize all the dependencies and call elastic search to post data""" # The problem I am facing is # This method only able to serialize only its fields not able # to serialize Foreignkey and ManytoMany field. # The problem is serialized_data = dict( self.title, # got serialized # Not able to serialized as the instace is not saved before this model get saved. education_levels=[education_level.level for education_level in self.education_levels.all()], # # Not able to serialized as the instace is not saved before this model get saved. languages=[language.language for language in self.languages.all()], ) # Save data to Elastic search save_to_elastic_server(index="videoindex", … -
How to deploy website changes in Django
Recently, the web developer that created our website has gone a-wall. Our company is in the process of sourcing a new developer that knows Django and Python. I am a Microsoft developer with little to no Django experience. However, I do know a little unix and have worked with linux and apache before. We need to make a minor update to our contact details page as we have moved office. The developer originally hard coded this page so we can not update this page via the CMS. I have located the file on the server and made the address updates but I do not know how to deploy it so it reflects on the live site. Can anyone assist me in doing this? I'm ssh into the box and doing everything via the terminal. Cheers, Ben -
django-taggit issue with url for blog/tag page & display all tags
I am having issues getting django-taggit to work in a test blog to a test django website. I have been able to display the individual tags next to the blog description, when I list the blogs. However I have the following two issues: I cannot display all of the tags used for all the blog entries in the blog template; I cannot get the url link working to display the selected links to the blog/tag/<tag name>/ page. Here is my models.py code: class BlogDetails(models.Model): blog_title = models.CharField(null=False, blank=False, max_length=150, unique=True) blog_description = models.TextField(null=False, blank=False, max_length=1500) blog_script = models.TextField(null=True, blank=True, max_length=15000) blog_date_published = models.DateField(null=False, blank=False, default=datetime.now) blog_video_url = models.URLField(null=False, blank=False, max_length=250) blog_video_image_url = models.URLField(null=True, blank=True, max_length=250) blog_timestamp_added = models.DateTimeField(auto_now_add=True, auto_now=False) blog_timestamp_updated = models.DateTimeField(auto_now=True, auto_now_add=False) blog_tags = TaggableManager() class Meta: ordering = ['-blog_date_published', '-blog_timestamp_added', '-id'] Here is my views.py code: def blog_details(request): date_now = timezone.now() all_blog_tags = BlogDetails.objects.all() blog_details_values = BlogDetails.objects.filter(blog_date_published__lte=date_now) ... paginator = Paginator(blog_details_values, 10) # Show 10 blogs per page page = request.GET.get('page') try: blog_details_values = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. blog_details_values = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. blog_details_values = … -
Set dynamic scheduling celerybeat
I have send_time field in my Notification model. I want to send notification to all mobile clients at that time. What i am doing right now is, I have created a task and scheduled it for every minute tasks.py @app.task(name='send_notification') def send_notification(): # here is logic to filter notification that fall inside that 1 minute time span cron.push_notification() settings.py CELERYBEAT_SCHEDULE = { 'send-notification-every-1-minute': { 'task': 'send_notification', 'schedule': crontab(minute="*/1"), }, } All things are working as expected. Question: is there any way to schedule task as per send_time field, so i don't have to schedule task for every minute. -
Tag an existing model and save it as a new model object in Django
I'm working on a django (1.10.5) project in which I need to build a logic as: We have a model as "Article" and upload articles by admin already. Now we need to allow a user to open an article and when he opens an article it comes with a form to tag it with some fields and then user have to submit this form and it will save again. When user load articles again he should be able to get only those articles not tagged by that user. Currently where I am: I have created a model for Articles to upload all articles : It's as articles/models.py Categories = ( ('Acute Threat ("Fear")', 'Acute Threat ("Fear")'), ('Potential Threat ("Anxiety")', 'Potential Threat ("Anxiety")'), ('Sustained Threat', 'Sustained Threat'), ('Loss', 'Loss'), ('Frustrative Nonreward', 'Frustrative Nonreward'), ('Approach Motivation: Reward Valuation', 'Approach Motivation: Reward Valuation'), ('Approach Motivation: Effort Valuation / Willingness to Work', 'Approach Motivation: Effort Valuation / Willingness to Work'), ('Approach Motivation: Expectancy / Reward Prediction Error', 'Approach Motivation: Expectancy / Reward Prediction Error'), ('Approach Motivation: Action Selection / Preference-Based Decision Making', 'Approach Motivation: Action Selection / Preference-Based Decision Making'), ('Initial Responsiveness to Reward Attainment', 'Initial Responsiveness to Reward Attainment'), ('Sustained/Longer-Term Responsiveness to Reward … -
Django Orm Query - Reverse list lookup
Its easy to check if item is in a list via Django ORM like User.objects.filter(name__in = ['x', 'y']) how about reverse way. if User has a field say list of suburbs which he vists (A comma separated list) and we have to check if he has not visited a particular suburb . class User(models.Model): suburb = models.TextField(_('suburbs'),validators=[validate_comma_separated_integer_list], blank=True) Data when retrieved from shell_plus will be of this sort for {'suburb': '965,967,969,972' } Want to get all users who have not visited suburb 100 ? -
Django to anguler4 site converstion
Well I have one web app in Django 1.9 and I want to convert it fully in Anguler4 but the thing is I want to use all the API of old Django and yes, site is in Django not in Django-REST First thing, is it possible? and if yes then the site is big enough to take 3.5 to 4 months so I want to be sure about how should I start with it? -
I wanna send localhost:8000/accounts/detail ,but it cannot be done
I wanna send localhost:8000/accounts/detail ,but it cannot be done. I wrote in views.py def login(request): login_form = LoginForm(request.POST) regist_form = RegisterForm(request.POST) if regist_form.is_valid(): user = regist_form.save(commit=False) context = { 'user': request.user, 'login_form': login_form, 'regist_form': regist_form, } return HttpResponseRedirect('detail') if login_form.is_valid(): user = login_form.save(commit=False) login(request, user) context = { 'user': request.user, 'login_form': login_form, 'regist_form': regist_form, } return HttpResponseRedirect('detail') context = { 'login_form': login_form, 'regist_form': regist_form, } return render(request, 'registration/accounts/login.html', context) Now in the part of HttpResponseRedirect,it sends localhost:8000/accounts/login/detail so error happens.This page read login method is localhost:8000/accounts/login.I wanna send the url to localhost:8000/accounts/detail.So,how should I fix this? In urls.py,I wrote urlpatterns = [ url(r'^detail$', views.detail,name='detail'), url(r'^login/$', views.login,name='login'), ] -
How can I use django template filter to delete the last character?
I have a string such as 100M, I want to delete the M, how can I do that? I tried use slice filter, but the number length is variable(maybe 1000 or others), so, how can I do that?