Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django get distinct results from queryset based on value
Here, I have my query result <QuerySet [{'user__first_name': 'aakash', 'user__id': 1, 'games_played': 1}, {'user__first_name': 'prakash', 'user__id': 2, 'games_played': 2}, {'user__first_name': 'prakash', 'user__id': 2, 'games_played': 2}]> and my query is, Games.objects.filter(Match__player__id=1).values('user__first_name', 'user__id', 'accounts__id').annotate(games_played=Count(Case(When(Q(status=Games.COMPLETE), then='id')))) So here I want user prakash or user__id=2 to come once. -
Installed pytest but running `pytest` in bash returns `not found`
I am following the python-django tutorial in Vagrant (Ubuntu 18.04 / Python3.6.6). After running pip3 install pytest-django and configuring pytest.ini file, running pytest returns Command 'pytest' not found, but can be installed with: apt install python-pytest Please ask your administrator. pip3 freeze output: pytest==3.10.0 pytest-django==3.4.3 Is there something else to the installation? -
Generate schema for Django rest framework viewset actions
As per the DRF documentation I started using ViewSet and have implemented list, retrieve, create, update and destroyactions. I have another APIView for which I was able to write schema (ManualSchema) and when I navigate to /docs/ I am able to the documentation as well as live endpoint for interaction. I wish to create separate schema for each of the viewset action. I tried writing one but it doesn't show up so I think I am missing something. Here is the code: class Clients(viewsets.ViewSet): ''' Clients is DRF viewset which implements `create`, `update`, `read` actions by implementing create, update, list and retrieve functions respectively. ''' list_schema = schemas.ManualSchema(fields=[ coreapi.Field( 'status', required=False, location='query', description='Accepted values are `active`, `inactive`' ), ], description='Clients list', encoding='application/x-www-form-urlencoded') @action(detail=True, schema=list_schema) def list(self, request): '''Logic for listing''' def retrieve(self, request, oid=None): '''Logic for retrieval''' create_schema = schemas.ManualSchema(fields=[ coreapi.Field( 'name', required=False, location='body', ), coreapi.Field( 'location', required=False, location='body', ), ], description='Clients list', encoding='application/x-www-form-urlencoded') @action(detail=True, schema=create_schema) def create(self, request): '''Logic for creation''' -
How to pass wizard variable with contextprocessor django?
I am using two global two forms with contextprocessor. forms.py from django import forms class ContactForm1(forms.Form): subject = forms.CharField(max_length=100) sender = forms.EmailField() class ContactForm2(forms.Form): message = forms.CharField(widget=forms.Textarea) views.py from django.http import HttpResponseRedirect from formtools.wizard.views import SessionWizardView class ContactWizard(SessionWizardView): def done(self, form_list, **kwargs): new = MyModel() for form in form_list: new = construct_instance(form, new, form._meta.fields, form._meta.exclude) new.save() HttpResponseRedirect('/page-to-redirect-to-when-done/') contexprocessors.py from .forms import ContactForm1, ContactForm2 def contact_form1(request): return { 'contact_form1': ContactForm1() } def contact_form2(request): return { 'contact_form2': ContactForm2(), } How to pass wizard variable with contextprocessors? -
Pre populate image field in django form not working
I'm trying to pre populate an image field in a django form, however, I can't seem to get it working. Here's what I've done: Views.py class EditUnpublished(TemplateView): template_name = 'adminpage/editUnpublished.html' def get(self, request, id): if not is_authenticated(request.user): return render(request, template_name_not_authenticated) post = Unpublished.objects.get(id=id) form = PublishForm( { 'title': post.title, 'text': post.text, 'user': post.user, 'image': post.image.url, 'users': post.users, 'tags': post.tags, 'copyeditor': post.copyeditor, 'comments': post.comments, } ) if not(request.user == post.copyeditor): form.fields['comments'].widget.attrs['readonly'] = True context = { 'post': post, 'form': form } return render(request, self.template_name, context) Forms.py class PublishForm(forms.ModelForm): title = forms.CharField(required=False) text = forms.TextInput() image = forms.ImageField(required=False) users = forms.ModelChoiceField(queryset=User.objects.all(), widget=forms.Select(), required=False) tags = forms.ModelChoiceField(queryset=Tags.objects.all(), widget=forms.Select(), required=False) copyeditor = forms.ModelChoiceField(queryset=User.objects.filter(groups__name__in=['Editor']), required=False, to_field_name="id") comments = forms.CharField(widget=forms.Textarea(), required=False) class Meta: model = PostsTwo fields = ('title', 'text', 'image', 'users', 'copyeditor', 'tags', 'comments') Models.py class Unpublished(models.Model): title = models.CharField(max_length=500) user = models.ForeignKey(User, related_name="owner", default=None, on_delete=models.CASCADE, blank=True, null=True) text = models.TextField() image = models.FileField(upload_to='img', default='img/None/no- img.jpg', blank=True, null=True) created_at = models.DateTimeField(default=datetime.now, blank=True) users = models.ForeignKey(User, related_name='contributors', on_delete=models.CASCADE, blank=True, null=True) tags = models.ForeignKey(Tags, on_delete=models.CASCADE, blank=True, null=True, unique=False) copyeditor = models.ForeignKey(User, unique=False, limit_choices_to={'groups__name': "Editor"}, on_delete=models.CASCADE, blank=True, null=True) comments = models.CharField(max_length=500000, blank=True, null=True) def __str__(self): return self.title class Meta: verbose_name_plural = "Unpublished" What I want is that when … -
Python - Field name and value in template
I would like to display something like this in my template: Name: John Age: 18 City: New York Using, for example, this code: views.py def person_details(request,pk): person = get_object_or_404(Person, id=pk) return render(request, 'template.html', {'person': person, 'person_fields': person._meta.get_fields()}) template.html {% for field in person_fields %} <div class="col-4 form-group"> <p><strong>{{ field.verbose_name }}:</strong> {{ person[ field.name ] }}</p> </div> {% endfor %} Is this possible in python? -
Not able to start supervisor with Django
I have a Django application and I use Celery to run background task. I am using supervisor to run celery as a service, but when I run: sudo supervisorctl reread , it gives me following error: Traceback (most recent call last): File "/home/wscube/.local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 578, in _build_master ws.require(__requires__) File "/home/wscube/.local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 895, in require needed = self.resolve(parse_requirements(requirements)) File "/home/wscube/.local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 786, in resolve raise VersionConflict(dist, req).with_context(dependent_req) pkg_resources.VersionConflict: (supervisor 4.0.0.dev0 (/home/wscube/.local/lib/python3.6/site-packages), Requirement.parse('supervisor==3.3.1')) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/bin/supervisorctl", line 6, in <module> from pkg_resources import load_entry_point File "/home/wscube/.local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 3112, in <module> @_call_aside File "/home/wscube/.local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 3096, in _call_aside f(*args, **kwargs) File "/home/wscube/.local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 3125, in _initialize_master_working_set working_set = WorkingSet._build_master() File "/home/wscube/.local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 580, in _build_master return cls._build_from_requirements(__requires__) File "/home/wscube/.local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 593, in _build_from_requirements dists = ws.resolve(reqs, Environment()) File "/home/wscube/.local/lib/python3.6/site-packages/pkg_resources/__init__.py", line 781, in resolve raise DistributionNotFound(req, requirers) pkg_resources.DistributionNotFound: The 'supervisor==3.3.1' distribution was not found and is required by the application Please help me. -
Django default form: populate some fields with values from last saved object
I'm using Django to record game sessions. A session has a time, place, league and game for example. At one sitting I may need to record many played games. I a create form for the session, I can enter these comfortably now and all is good. The problem is on one sitting all the games are typically at the same place in the same league for example and around the same time so I'd like after saving one form, to be presented with a new create form, in which the place, league and time are already set to sensible defaults (same place and league as the last save and maybe same time plus 90mins). I'm not sure of the best way to approach this. The session data store seems attractive, but is rather limited by the fact that each of these needs to JSON serializable to store there. I'm thinking maybe I can pull the info out of the database, and for example in the view's context add a copy of the last such object saved. But somehow I have to use that context to populate the default for which is only in my template as: {{ form.as_table }} and … -
Django 2 systemd/journalctl runserver logs not working as expected
We recently updated our project from Django 1.7 on Ubuntu 14 to Django 2.0 Ubuntu 18 (i know... pretty big jump). There were a few issues but we've slowly got everything up and running. Switching from uwsgi to gnuicron being one. I don't know if this is by design or a difference between Upstart Vs systemd, or perhap django2 and django 1.7's runserver, but logging is behaving different. With our old project, I would run server, then check logs: sudo python manage.py runserver 0:8888 sudo tail -f /var/log/upstart/backend.log These logs would give me a print for every refresh and code change. This includes if I made a python error in a file, the server would restart - fail - and then show me the error. With the new project: sudo python3 manage.py runserver 0:8888 sudo journalctl -f -u backend (I assume journalctl is the correct way I should be viewing these logs) However now, if I have an error in my python script files, the server reboots but there's no print of this happening. If I fix the error, then the server auto reboots again and prints the error I did have while also showing me the usual "your server … -
Django model serialization problem with default fields
Inside of my app model, I use IntegerRangeField fields: from django.db import models from django.contrib.postgres.fields import IntegerRangeField from django.contrib.postgres.validators import RangeMinValueValidator, RangeMaxValueValidator from psycopg2.extras import NumericRange class MyModel(models.Model): ... field = IntegerRangeField(default=NumericRange(400, 600), validators=[ RangeMinValueValidator(1), RangeMaxValueValidator(1000) ]) ... The "default" attributes are used in the admin panel UI only, and are not needed anywhere else. If I add them after migration, they work smoothly. However, if I add them before I run makemigrations, I get this message: ValueError: Cannot serialize: NumericRange(400, 600, '[)') There are some values Django cannot serialize into migration files. I don't even want the default values to be saved to my PostgreSQL database, I just want to not have to remove and bring them back every time I run makemigrations. Any ideas? (Didn't work: a custom object with "lower" and "higher" attributes, a single integer, a string, a tuple) Python: 3.6.6, Django: 2.1.2, PostgreSQL: 11.0 -
How can I pass the value of variable from one div to another div in the same template.I'm using Django
I'm using a loop to fetch data from model object.I'm trying to pass the same variable i among two different div.I want same i as I need it to get the same object.I'm new to this field and maybe I'm doing something stupid.Any help will be kindly appreciated.Here is the snippet <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table class="table table-striped table-dark"> <thead> <tr> <th scope="col">S.N</th> <th scope="col">Company Name</th> <th scope="col">Trade Ref Date</th> </tr> </thead> <tbody> {% for i in records %} <tr> <!--I'm getting objects variable value in here--> <th scope="row">1</th> <td>{{i.company}}</td> <td>{{i.address}}</td> <td>{{i.contact}}</td> </td> </tr> {% endfor %} </tbody> </table> <div class="modal fade" id="data1" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h3 class="modal-title title" id="exampleModalLabel">Trade Details</h3> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="card-body card-block"> <div class="displaydata"> <div class="description"> <ul> <!--I'm not able to get objects variable value in here--> <li>{{i.sn}}</li> <li>{{i.company}}</li> <li>{{i.address}}</li> <li>{{i.contact}}</li> </ul> </div> <table class="table table-bordered"> <tbody> <tr> <th scope="col">Sales </th> <th scope="row">Purchase</th> </tr> <tr> <th scope="col"><span>Sale/Cancel Sales : </span>{{i.sales}}<span></span></th> </tr> </tbody> </table> -
Display live wordcount in django wagtail backend
I'm currently working with django wagtail CMS. how can i add word count for blog richtextfield in wagtail. What should i use for that here's some of my code from my models.py class BlogPage(Page): date = models.DateField("Post date") intro = models.CharField(max_length=250) body = RichTextField(blank=True) my goal is to display word count for field body in the CMS backend -
Need to identify user by browser in python/ django?
I need to send notifications to all the users who follow a topic. I use the following model: class FollowPage(TimeStampedModel): user = models.ForeignKey(User, related_name='user_following_page', on_delete=models.CASCADE) url = models.CharField(max_length=250, null=True, blank=True) In the case, when user is not logged in, how do I store the browser info and send the notification to the browser. Should I create a new user by browser or change the model to follow the topic by browser? -
Building my first Django app. (Actually, building my first project ever)
I'm about to to start building my first web application, I'm using Django on it. Coud you guys give me any tips or advices? Thanks. -
I'm confused about python web application
I just learned , "python" programming and basic knowledge about css and html and java script and i was a "php" programmer before , I'm confused ,is it possible to program a web application just in python (a server side) with out using a framework like (django, flask , etc) or if i use django to develope , is it possible to put them both (django and pyhotn) in a single programm Regards -
Django-PayPal subscription IPN not returning next_payment_date
I am using django-paypal, to setup subscription payment. Everything seems to be working as expected. The only problem is that the next_payment_date attribute of PayPalIPN object always returns None. When I login to sandbox account dasboard, I can clearly see the next payment date. Also, PayPal documentation clearly states the purpose of next_payment_date, So, why IPN is not giving me this information? next_payment_date: Next payment date for a recurring payment I am using exactly the same code as suggested by the documentation of django-paypal. -
Working with PostgreSQL and Django on Google App Engine standard environment
I'm currently setting up a Django app on the Google App Engine platform, using a standard environment. Is it possible to connect to a PosgreSQL Google Cloud SQL instance? I can connect to a MySQL instance by following this tutorial (https://cloud.google.com/python/django/appengine). I can't get PostgreSQL to work however - is this because PostgreSQL only works on a flexible environment? Many thanks -
How to use def(include update_or_create method) by button in template?
I try this construction, but it do nothing. Maybe I must try use synch_db in views, but im not sure about that. models.py from django.db import models import requests, json from requests.exceptions import ConnectionError from time import sleep import sys # Create your models here. class Company(models.Model): Id = models.IntegerField(primary_key=True) Name = models.CharField(max_length=255) ClientInfo = models.CharField(max_length=255) StartDate = models.CharField(max_length=20) EndDate = models.CharField(max_length=20) TimeZone = models.CharField(max_length=50) # DailyBudget = models.CharField(max_length = 255) Type = models.CharField(max_length=255) Status = models.CharField(max_length=255) State = models.CharField(max_length=255) StatusPayment = models.CharField(max_length=255) StatusClarification = models.CharField(max_length=255) Statistics = models.CharField(max_length=255) Currency = models.CharField(max_length=255) Funds = models.CharField(max_length=255) Amount = models.FloatField() Mode = models.CharField(max_length=255) Impressions = models.FloatField() Clicks = models.FloatField() Sum = models.FloatField() Balance = models.FloatField() Spend = models.FloatField() def __str__(self): return self.Name def synch_bd(): if sys.version_info < (3,): def u(x): try: return x.encode("utf8") except UnicodeDecodeError: return x else: def u(x): if type(x) == type(b''): return x.decode('utf8') else: return x result = _get_companies() for campaign in result.json()['result']['Campaigns']: company, created = Company.objects.update_or_create( Id=u(campaign['Id']), Name=u(campaign['Name']), ClientInfo=u(campaign['ClientInfo']), StartDate=u(campaign['StartDate']), EndDate=u(campaign['EndDate']), TimeZone=u(campaign['TimeZone']), Type=u(campaign['Type']), Status=u(campaign['Status']), State=u(campaign['State']), StatusPayment=u(campaign['StatusPayment']), StatusClarification=u(campaign['StatusClarification']), Statistics=u(campaign['Statistics']), Currency=u(campaign['Currency']), Funds=u(campaign['Funds']), Amount=u(campaign['DailyBudget']['Amount']), Mode=u(campaign['DailyBudget']['Mode']), Impressions=u(campaign['Statistics']['Impressions']), Clicks=u(campaign['Statistics']['Clicks']), Sum=u(campaign['Funds']['CampaignFunds']['Sum']), Balance=u(campaign['Funds']['CampaignFunds']['Balance']), Spend=u(campaign['Funds']['CampaignFunds']['Spend']), defaults={"Name": Name, "ClientInfo": ClientInfo, "StartDate": StartDate, "EndDate": EndDate, "TimeZone": TimeZone, "Type": Type, "Status": Status, "State": State, "StatusPayment": StatusPayment, "StatusClarification": StatusClarification, "Statistics": … -
django models relationship how to link a models A twice to model B
Let say i'm implementing a messaging service using django so i have 2 models 1 for messages and the second for users. A message sender is a user's model instance and the message receiver also is a user's model instance. is it a right way to do like this ? class User(models.Model): first_name = models.CharField(max_length=40, default='', null=True) last_name = models.CharField(max_length=40, default='', null=True) class Message(models.Model): sender = models.ForeignKey(User) receiver = models.ForeignKey(User) message = models.CharField(max_length=5000) created_at = models.DateTimeField(auto_now_add=True, blank=True) updated_at = models.DateTimeField(auto_now=True, blank=True) Thanks -
Wagtail render page tree
I am trying to create a sitemap that a user can use to see the Hierarchy of the site, child pages and parent pages etc but I can't seem to find a way of showing this. Is there an app I can use or will I need to write a custom function? -
Add new line to admin action message
How can you add a new line after, for example, triggering an admin action. from django.contrib import messages messages.error(request, 'This is a line \n and this is another line') I also tried with html tag but didnt work. -
Django - html5 range slider renders strangely
I'm using the html5 range slider on a Django form. I have multiple sliders on the form. The functionality works fine but it always renders in html with these weird little errors (see image). and . It seems like the problem is using template tags for the slider ID. When I remove them, the little errors go away. But of course, this means I can't save the input from the range slider to the associated field. I've also tried moving the ID into various places in the input tag but that just breaks how it renders the slider altogether. Any ideas on how I can fix this would be appreciated. This is the template: <div class="range-slider"> {{ form.content_rating_1.errors }} <p> <h6> <span class="range-slider__value">0</span></p></h6> <input class="custom-range" type="range" value="0" min="0" max="50" id="{{ form.content_rating_1 }}" > </div> -
How to remove auto-generated fields from DRF - Swagger UI
I've a model where few fields are auto-generated. How do I hide those fields from the Swagger UI during POST request? Following is the example:- class ModelX(models.Model): a = models.CharField() b = models.CharField() c = models.CharField() d = models.CharField() Below is my serialzer:- class Serializerx(serializers.Serializer): class Meta: model = ModelX fields = '__all__ In the above model, fields b and d are auto generated from my code, which means these fields are not required as an input from the user. If I add b and d as read-only fields, then I wont be able to create an object with these values. How do I hide some attributes from the payload request.? Somewhat similar to this -
how to modify django with bootstrap template
i try to create a static folder that keep css and other static file in django project by run command "python manage.py collectstatic " but it is always create admin folder in static folder and then when i runserver . it show error [03/Nov/2018 01:31:58] "GET / HTTP/1.1" 200 37323 [03/Nov/2018 01:31:58] "GET /static/assets/css/normalize.css HTTP/1.1" 404 1696 [03/Nov/2018 01:31:58] "GET /static/assets/css/font-awesome.min.css HTTP/1.1" 404 1717 [03/Nov/2018 01:31:58] "GET /static/assets/css/themify-icons.css HTTP/1.1" 404 1708 [03/Nov/2018 01:31:58] "GET /static/assets/css/flag-icon.min.css HTTP/1.1" 404 1708 [03/Nov/2018 01:31:58] "GET /static/assets/scss/style.css HTTP/1.1" 404 1687 [03/Nov/2018 01:31:58] "GET /static/assets/css/cs-skin-elastic.css HTTP/1.1" 404 1714 [03/Nov/2018 01:31:58] "GET /static/assets/css/lib/vector-map/jqvmap.min.css HTTP/1.1" 404 1744 [03/Nov/2018 01:31:58] "GET /static/images/logo.png HTTP/1.1" 404 1669 [03/Nov/2018 01:31:58] "GET /static/images/logo2.png HTTP/1.1" 404 1672 [03/Nov/2018 01:31:58] "GET /static/assets/js/plugins.js HTTP/1.1" 404 1684 [03/Nov/2018 01:31:58] "GET /static/assets/js/dashboard.js HTTP/1.1" 404 1690 [03/Nov/2018 01:31:58] "GET /static/assets/js/lib/chart-js/Chart.bundle.js HTTP/1.1" 404 1738 [03/Nov/2018 01:31:58] "GET /static/assets/js/main.js HTTP/1.1" 404 1675 [03/Nov/2018 01:31:58] "GET /static/assets/js/widgets.js HTTP/1.1" 404 1684 [03/Nov/2018 01:31:58] "GET /static/assets/js/lib/vector-map/jquery.vmap.min.js HTTP/1.1" 404 1753 [03/Nov/2018 01:31:58] "GET /static/assets/js/lib/vector-map/jquery.vmap.js HTTP/1.1" 404 1741 [03/Nov/2018 01:31:58] "GET /static/assets/js/lib/vector-map/jquery.vmap.sampledata.js HTTP/1.1" 404 1774 [03/Nov/2018 01:31:58] "GET /static/assets/js/lib/vector-map/country/jquery.vmap.world.js HTTP/1.1" 404 1783 [03/Nov/2018 01:31:58] "GET /static/images/avatar/3.jpg HTTP/1.1" 404 1681 [03/Nov/2018 01:31:58] "GET /static/images/avatar/1.jpg HTTP/1.1" 404 1681 [03/Nov/2018 01:31:58] "GET /static/images/avatar/2.jpg HTTP/1.1" 404 1681 [03/Nov/2018 01:31:58] "GET … -
Create custom Django API response template
I am trying to build a response structure with django rest framework and have some standard template body: Response body should have below parameters: status_code : It should accept status code and provide it as response object Invalid entries: These are the invalid entrees made by user in the form and request did not process it. Message: Should provide a success/failure message with details Data: Json response data to front end Anything which is blank should not go with response body.