Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Form Fields won't show in my template
The form field won't show up in the browser. There is only the submit button showing up. views.py code: def vote(request, pk): # check if request is post if request.method == 'POST': # create a form and populate it with data from request form = forms.Vote(request.POST) if form.is_valid(): fact = Fact.objects.get(pk=pk) fact.votes += int(form.cleaned_data['vote']) fact.save() return HttpResponseRedirect(reverse( 'facts:detail', args=(pk,) )) else: form = forms.Vote() return render(request, 'facts/fact_detail.html', {'form': form}) template(fact_detail.html) code: <form method='POST'> {% csrf_token %} {{ form }} <input type="submit" value="vote" /> </form> Form class(forms.py) code: VOTE_CHOICES = [ (1, 'upvote'), (0, 'downvote') ] class Vote(forms.Form): vote = forms.ChoiceField(choices=VOTE_CHOICES, widget=forms.RadioSelect()) -
Django test deleteview for model with overwritten 'delete' method.
I am writting tests for a django application that contains multiple deleteviews. I test all deleteviews with variations of the following code: #Object exists to begin with response = self.client.get(reverse('roldelete', kwargs={'pk': self.role.pk})) self.assertEqual(response.status_code, 200) #Object Can be deleted can be posted response = self.client.post(reverse('roldelete', kwargs={'pk': self.role.pk})) self.assertEqual(response.status_code, 302) #Object is actually deleted response = self.client.get(reverse('roldelete', kwargs={'pk': self.role.pk})) self.assertEqual(response.status_code, 404) #Query returns an empty result self.assertFalse( Role.objects.filter(pk=self.role.pk).exists()) All of this is working fine, however, in on of my models I've overwritten the default 'delete' method. Basically everytime I delete a 'TenantPurchase' object I want to check for the existence of a linked 'PurchaseRequest' object and delete it as well. I wrote the following code to do so: def delete(self, *args, **kwargs): try: purchase_user = self.user purchase_arrangement_period = self.item #Import here to avoid circular import from arrangement.models import ArrangementBuyRequest linked_buy_request = ArrangementBuyRequest.objects.filter( user=purchase_user, arrangement_period=purchase_arrangement_period) \ .order_by('request_date').last() linked_buy_request.delete() except (ArrangementBuyRequest.DoesNotExist, AttributeError) as e: pass super(TenantPurchase, self).delete(*args, **kwargs) When I test manually on our development server, I behaves as it should. Linked buy Requests are deleted and no errors are thrown. However, all my Unittests for this model fail. It passes the first three tests (assert 200, assert 302, assert 404) But a direct … -
Django loop through list
How do you loop trough a list in django templates with a for loop? my problem is with trying to fetch list.0 list.1 list.2 But when running the code i don't get anything {% for i in range %} {% for key, value in list.i.items %} {{ key }} {{ value }} {% endfor %} {% endfor %} where i should be list.0-2 but it doesn't show anything on screen -
In form view, how to put the template_name on the current page
Everything is in the title, I have a problem with the form error and I think to solve it I have to put the template name on the current page. Thanks =) -
Not able to link the template page of Django
I am trying to make an application using django-allauth; My Django version is 1.11.5. I am trying to display the result on another template: facebook_personality_traits.html Here is the code: settings.py SITE_ID = 1 LOGIN_REDIRECT_URL = 'facebook_personality_traits/' 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 views.py def fb_personality_traits(request): # logger.debug('FB Page Loaded') return render(request, 'home/facebook_personality_traits.html') urls.py url(r'^facebook_personality-traits/&', views.fb_personality_traits, name="fb_personality_traits"), facebook_personality_traits.html <html> <body> Welcome back {{ user.first_name }} {{ user.last_name}} <a href="/">Home</a> </body> </html> But I could able to make it run effectively. I guess there is some issue where I have declared the url for the site. Here is the snapshot of the error: Kindly suggest me the missed part. -
Can I override Django password form layout?
I have overridden the Django login and registration forms by creating the templates registration/login.html, registration/logout.html, registration/registration_closed.html and registration/registration_form.html. However, the password change forms are in the original style. Unlike the existing forms, it doesn't look like django-registration.registration.auth_urls specifies HTML templates for these password forms. So how can I override them to look like my custom templates? -
How to detect related models get saved in django model and save the instance model
I am working on django, and I am in a situation, that I need to run some function, after all the related models of django model get saved in database. Let say I have a model models.py from . import signals class Video(models.Model): """Video model""" title = models.CharField( max_length=255, ) keywords = models.ManyToManyField( KeyWord, verbose_name=_("Keywords") ) When the new instance of video model is created. I need to 1. All the related models get saved first. a. If the related models are empty return empty or None 2. and then Save this video instance. I tried to do it using post_save signals, but couldn't succeded as there is no gurantee that related models get saved first that this video model. from django.db.models.signals import post_save, pre_delete, m2m_changed from django.dispatch import receiver from .models import Video @receiver(m2m_changed, sender=Video) @receiver(post_save, sender=Video) def index_or_update_video(sender, instance, **kwargs): """Update or create an instance to search server.""" # TODO: use logging system # Grab the id print("Id is", instance.id) # Keywords is empty as keyword instance is saved later than this instace. keywords = [keyword.keyword for keyword in instance.keywords.all()] print(keywords) # [] empty no keywords instance.index() @receiver(pre_delete, sender=Video) def delete_video(sender, instance, **kwargs): print("Delete index object") instance.delete() -
Using `subprocess` in a web service
I'm trying to leverage wkhtmltopdf to make a render-on-the-fly endpoint in a Django web app. The only way I'm aware of if to execute the external tool in a subprocess, for e.g.: from subprocess import Popen, PIPE from rendering.service.settings.local import WKHTMLTOPDF_PATH class HtmlToPdfView(APIView): def post(self, request): process = Popen([ WKHTMLTOPDF_PATH, '--disable-smart-shrinking', '-', '-' ], stdout=PIPE, stdin=PIPE, stderr=PIPE) stdout, stderr = process.communicate(input=bytes(request.data['html'])) return Response({'pdf': stdout}) But I have a general bad feeling about this. Should I worry about things like SIGFAULT? Am I even doing it right? Should I join() or poll() the process to make sure wkhtmltopdf is done with it's execution? Should I use close_fds=True? -
Is it ok to use app config variable as CharField choices?
Is it correct to use a AppConfig variable in model? myapp/apps.py class MyAppConfig(AppConfig): name = 'my_app' my_list = None def ready(self): self.my_list = ( ('a', 'A'), ('b', 'B'), ('c', 'C'), ) anotherapp/models.py AnotherModel(models.Model): options = models.CharField( max_length=1, choices=apps.get_app_config('my_app').my_list) -
Django redirect having a ValueError
I am having a valueerror on my redirect function below. I checked previous updates which specified that this would occur when the name argument is not specified. I already did but its still not working for some strange reason. The traceback is below ValueError at / dictionary update sequence element #0 has length 0; 2 is required views.py class HomeView(TemplateView): template_name = "home.html" title = 'Your Dashboard' def get_context_data(self, *args, **kwargs): if self.request.user.is_authenticated(): fav_polls = PollFav.objects.filter(fav_user=self.request.user) poll_types = [] for poll in fav_polls: poll_types.append(poll.poll.polltype_id) poll_types = Ptype.objects.filter(pk__in=list(set(poll_types))) context = super(HomeView, self).get_context_data(*args, **kwargs) context["submit_btn_value"] = "Send" context["title"] = self.title context["poll_types"] = poll_types todate = datetime.datetime.now().date() user = self.request.user context["pollsCreated"] = Ptype.objects.filter(c_user=user).count() context["pollsECreated"] = PollItem.objects.filter(user_submit=user).count() try: context["user"] = PUser.objects.get(user_id=self.request.user.id) except: #where the issue is return redirect("PUserCreate") return context urls.py url(r'^puser/add/$', PUserCreate.as_view(), name='PUserCreate'), -
form instance inside loop django
I'm looking to save my form instance and I found Create objects in for loop. How can I achieve similar effect if I have: pk = self.kwargs['pk'] C = {'dog':'Nash', 'cat':'Luffy'} for animal,owner in ngipon.items(): form.instance.owner = owner form.instance.animal = animal form.instance.patient = Clinic.objects.get(pk=pk) -
Running celery task on Ubuntu with supervisor
I have a test Django site using a mod_wsgi daemon process, and have set up a simple Celery task to email a contact form, and have installed supervisor. I know that the Django code is correct. The problem I'm having is that when I submit the form, I am only getting one message - the first one. Subsequent completions of the contact form do not send any message at all. On my server, I have another test site with a configured supervisor task running which uses the Django server (ie it's not using mod_wsgi). Both of my tasks are running fine if I do sudo supervisorctl status Here is my conf file for the task I've described above which is saved at /etc/supervisor/conf.d the user in this instance is called myuser [program:test_project] command=/home/myuser/virtualenvs/test_project_env/bin/celery -A test_project worker --loglevel=INFO --concurrency=10 -n worker2@%%h directory=/home/myuser/djangoprojects/test_project user=myuser numprocs=1 stdout_logfile=/var/log/celery/test_project.out.log stderr_logfile=/var/log/celery/test_project.err.log autostart=true autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase this if you have very long running tasks. stopwaitsecs = 600 stopasgroup=true ; Set Celery priority higher than default (999) ; so, if rabbitmq is supervised, it will start first. priority=1000 My other test site has this set … -
Random Option In Django Drop Down Form
I've been picking my brain trying to figure this out and so now I turn to the community for help. I'm using models to create a form in Django and I want to add a Random option to a few of the drop-down choices. Here is a general idea of what I'm working with: models.py Character(models.Model): name = models.CharField(max_length=255,unique=True) age = models.PositiveIntegerField(default=0) gender = models.CharField(max_length=20,choices=creation_choices.GENDERS) race = models.CharField(max_length=500,choices=creation_choices.RACE) creation_choices.py GENDERS = ( ('male',"Male"), ("female","Female"), ("unknown","Unknown"), ) RACE = ( ('human','Human'), ('elf','Elf'), ('dwarf','Dwarf'), ) What I am trying to do is add a way for users to select Random and it returns one of the other values. I tried a lot of different methods but most returned an error. When I created a function with random.choice() and pushed that through it seemed to work, but for some reason always returned the same value. Any help would be greatly appreciated! -
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