Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Remove messages before the response is rendered
I've got a page which contains 2 forms & allows updating of the model attached to each. I've also got the messages framework integrated which for the most part is perfect. But after posting to this page you get two messages of success and I'd like to display 1 simple message in their place. I've tried various approaches suggested in other questions; Django: Remove message before they are displayed Deleting/Clearing django.contrib.messages But I'm unable to clear the message queue. def post(self, request, **kwargs): profile_valid = False user_valid = False post_data = request.POST or None profile_form = self.profile_form_class( post_data, instance=request.user.profile, prefix='profile' ) user_form = self.user_form_class( post_data, instance=request.user, prefix='user' ) context = self.get_context_data( profile_form=profile_form, user_form=user_form ) if profile_form.is_valid(): profile_valid = True self.form_save(profile_form) if user_form.is_valid(): user_valid = True self.form_save(user_form) if profile_valid and user_valid: # First get the messages from the above save methods storage = messages.get_messages(request) for message in storage: # Need to iterate over the messages to achieve what we need pass # Set the messages as used storage.used = True # Add our simple message messages.success(self.request, self.success_message) return self.render_to_response(context) I'm using session based message storage, but that doesn't seem to have an impact on what's available in the view. I'm using; … -
I was given a task to run the deployed python django project on localhost. How can we achieve that?
I have the Django project which is deployed in the Digital ocean. I am trying to access that code internally through localhost:8000, but I am unable to access the project. Is there any setting that I need to look upon. Please help. -
ModuleNotFoundError: No module named 'chess.uci'
I am having this error when I try to do makemigrations using Django, but I already got python-chess installed and also tried to uninstall and reinstall it, and it still didn't work. Any clue about why I am having this error or how should I fix it? Really appreciate. -
ngrok 504 timeout error when server is overloaded
i'm using ngrok to host my django webapp. The page makes an api request to obtain some information from a server (basically running some sql codes there and returning a file), but when the server is busy and all queries are slow, ngrok returns a timeout error. Does anyone know how to mitigate this? I've tried adding timeout number in settings.py but doesnt seem to work. However, when i host it locally, using my ip, it seems to work even though its slow, it doesnt have timeout error. -
'Post' object is not iterable:TypeError
This is my view . I have used function based view to show to detail of post. def post_detail(request,slug,pk): detail = get_object_or_404(Post,slug=slug,pk=pk) context={ 'detail':detail } return render(request,'post/post_detail.html',context) This is my urls . of post_detail , and its name is also post_detail path('<int:pk>/<str:slug>/', views.post_detail, name='post_detail'), This is my models. It is a post model I have got get_absolute_url () to render to detail view class Post(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(User,on_delete=models.SET_NULL,null=True) story= models.TextField() image= models.ImageField() slug = models.SlugField() def get_absolute_url(self): return reverse('post_detail',kwargs={'pk':self.pk,'slug':self.slug}) def __str__(self): return self.title This is the post/post_detail.html for my post_detail view {% extends "post/base.html" %} {% block content %} {% for posts in detail %} {{posts.image.url}} {{posts.title}} Written by: {{posts.author}} {% endfor %} {% endblock content %} -
Django switch between inlines in the admin
I am currently working on a multi-role user login module for my Django project. I currently have two roles How can I change the inlines showing on the admin page according to the role choice? #models.py in users class User(AbstractUser): role_choice = ( ('Reader', u'Reader'), ('Author', u'Author'), ('Editor', u'Editor'), ('Admin', u'Admin') ) user_role = models.CharField(choices=role_choice, max_length=150, default='Admin', verbose_name='Role') #admin.py in users class ReaderInline(admin.TabularInline): model = Reader extra = 2 class AuthorInline(admin.TabularInline): model = Author extra = 2 class UserAdmin(admin.ModelAdmin): form = UserForm inlines = [ReaderInline, AuthorInline] -
SnapToGrid and group its value in Django
i have a problem regarding Django queryset grouping. i need to get queryset of points which are groped by point snaped grid ST_SnapToGrid, query should look like this: SELECT ST_AsGeoJSON( ST_SnapToGrid("events_place"."point", 1), 8 ) AS "point_geo", MAX("events_place"."adress") AS "adress" FROM "events_place" GROUP BY point_geo and code is fallowing: models.py class Place(models.Model): kode= models.BigIntegerField(blank=True, null=True) adress = models.CharField(max_length=250, blank=True, null=True) lat = models.FloatField(blank=True, null=True) lng = models.FloatField(blank=True, null=True) point = models.PointField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) + " "+str(self.adress ) + " ("+str(self.lat) + ", " + str(self.lat) + ")" class Meta: ordering = ('created_at',) def save(self, *args, **kwargs): super(Place, self).save(*args, **kwargs) # Call the "real" save() method. views.py class PlaceSTGViewSet(viewsets.ReadOnlyModelViewSet): queryset = Place.objects.all() serializer_class = PlaceSTGSerializer def get_queryset(self): queryset = Place.objects\ .annotate(point_geo=AsGeoJSON(SnapToGrid('point', 1)), adress=Max('adress'))\ .values('lng', 'point_geo') return queryset resulting query is fallowing: SELECT "events_place"."lng", ST_AsGeoJSON( ST_SnapToGrid("events_place"."point", 1), 8 ) AS "point_geo" FROM "events_place" GROUP BY "events_place"."id", ST_AsGeoJSON( ST_SnapToGrid("events_place"."point", 1), 8 ) ORDER BY "runis_events_place"."created_at" ASC Problem is that it includes "events_place"."id" in grop by statment. Could you please tell how to get rid of this id? -
Django - How to count child records
Given the following enter code heremodels: class Area(models.Model): area = models.CharField(unique=True, max_length=20, blank=False) is_deleted = models.BooleanField(default=False) ... class Group(models.Model): group = models.CharField(unique=True, max_length=20, blank=False) is_deleted = models.BooleanField(default=False) ... class Phone(models.Model): areacode = models.ForeignKey(Area, default=None, blank=True, null=True, on_delete=models.SET(0)) groupcode = models.ForeignKey(Group, default=None, blank=True, null=True, on_delete=models.SET(0)) name = models.CharField(max_length=20, null=True, blank=True) address1 = models.CharField(max_length=20, null=True, blank=True) address2 = models.CharField(max_length=20, null=True, blank=True) is_deleted = models.BooleanField(default=False) ... In Django, how do I count total records of parent table (Area and Group) that used in child table (Phone) eg area table Name Count Area1 5 Area2 8 and phone table Hotel 6 School 8 Office 9 -
DRF: only Author can create or update the book permission
So, I have two simple models: class User(AbstractUser, models.Model): username = models.CharField( 'Username', max_length=255, db_index=True, unique=True ) email = models.EmailField( 'Email', max_length=255, db_index=True, blank=True, null=True, unique=True ) objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ('email', 'password',) class Book(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) and a serializer like this: class BookSerializer(serializers.ModelSerializer): class Meta: model = models.Book fields = ['title', 'author'] def validate_author(self, author): # < --- it doesn't work if author != serializers.CurrentUserDefault(): raise serializers.ValidationError( 'You cant update other authors book' ) author = serializers.PrimaryKeyRelatedField( default=serializers.CurrentUserDefault(), queryset=models.User.objects.all() ) and a view with some permissions: class IsAuthorOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.author == request.user class BookViewSet(viewsets.ModelViewSet): queryset = models.Book.objects.all() serializer_class = serializers.BookSerializer permission_classes = [IsAuthenticatedOrReadOnly & IsAuthorOrReadOnly] So, how can I ensure that a user can get all of the books but can't create or update the books which don't belong to him? -
MacOS - ERROR: No matching distribution found for django==2.2.7
I was trying to install django in virtual env on MacOS but I'm getting this error $sudo pip install django==2.2.7 ERROR: No matching distribution found for django==2.2.7 $ python -m django --version /Users/mbp/django/django/bin/python: No module named django How do I install django? -
Unable to use wagtail with multiple databases
As the title suggests, I'm finding it difficult to use multiple databases with Wagtail. My Objective is simple: Implementation of a scenario where all the Django as well as Wagtail tables will be created in the sqlite database for now rather than in the postgreSQL db. The Why: Cause I'd like the postgreSQL DB to remain uncluttered as well as utilise it for search/select purposes using the inspectdb command. The Error generated: relation "wagtailcore_page" does not exist Cause for concern: In the default wagtail home app, migrations folder, there's a file: 0002_create_homepage.py whose contents look like: from django.db import migrations def create_homepage(apps, schema_editor): # Get models ContentType = apps.get_model('contenttypes.ContentType') Page = apps.get_model('wagtailcore.Page') Site = apps.get_model('wagtailcore.Site') So makes me wonder: is this an error that happens because Wagtail already has its own initial migration in the home app or am I doing something wrong? Better yet, how would I implement this concept with wagtail. Here's my code: base.py- database section DATABASES = { 'sqlite': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'OPTIONS': { 'options': '-c search_path=test_schema,public' }, 'NAME': os.environ.get('DBWORKNAME'), 'USER': os.environ.get('DBWORKUSER'), 'PASSWORD': os.environ.get('DBWORKPASSWORD'), 'HOST': os.environ.get('DBWORKHOST'), } } DATABASE_ROUTERS = [ 'school.router.NonPersonalDBAttributeRouter' # Router's module path ] my_project_dir/router.py … -
Django forms, adding information automatically
I am creating a Django app and I am trying to add information to some fields using values given by the usuary and saved in the same table but in another fields. For example, If the user introduce its age using a function I want to fill another field in the same table with a category lile 'under 21' or the oposite. I've tryed to define the function in the models.py file, before creting the class definition, but when I call it inside the class it just return something like users.User.age so the function is not accessing to the value contained in the field, it is using the field itself. How can I get the value contained in this field? -
select onchange tag does not run my Javascript function
I have the following code: JS: function updateLink() { var selType = document.getElementByID("Types"); var selLen = document.getElementByID("Length"); var selLoc = document.getElementByID("Location"); var selMan = document.getElementByID("Manufacturer"); var test = document.getElementByID("test"); test.innerHTML="Test"; var selectedType = (selType.options[selType.selectedIndex].text); var selectedLength = (selLen.options[selLen.selectedIndex].text); var selectedLocation = (selLoc.options[selLoc.selectedIndex].text); var selectedManufacturer = (selMan.options[selMan.selectedIndex].text); document.getElementById("apply").href="myURL?typeName="+selectedType+"length="+selectedLength+"location="+selectedLocation+"manufacturer="+selectedManufacturer; } </script> and HTML <div id="filterdiv" class="dark"> <center><h3 id="test">Filters</h3></center> <br> <center>Type</center> <select id="Types" onchange="updateLink()"> <option>All</option> {% for types in TypesList %} <option>{{types}}</option> {%endfor%} </select> <br> <br> <center>Inspection Period</center> <select id="Inspection Period"> <option>All</option> {% for inspections in InspectionList %} <option>{{inspections}}</option> {%endfor%} </select> <br> <br> <center>Length</center> <select id="Length"> <option>All</option> {% for lengths in LengthList %} <option>{{lengths}}</option> {%endfor%} </select> <br> <br> <center>Location</center> <select id="Location"> <option>All</option> {% for locations in LocationList %} <option>{{locations}}</option> {%endfor%} </select> <br> <br> <center>Manufacturer</center> <select id="Manufacturer"> <option>All</option> {% for manufacturers in ManufacturerList %} <option>{{manufacturers}}</option> {%endfor%} </select> <br> <br> <a href="" id="apply"><button onclick="updatelist()">Apply Filter (TODO)</button></a> <a href="http://myURL"><button>Reset Filters</button></a> </div> It's a list of select boxes with options taken from my Django models to filter a list in another div. On pressing my button I am redirected to the same URL, no parameters attached. And my test string to change the title also doesn't change anything. So I suspect that my JS code is never … -
Getting error : 'User' object has no attribute 'user'. in django python
i am new here in django python, I am learning 2 table relations, primary key foreign key scenario, for that i am using existing django user model and create another model userprofile, I want to list data of user and profile, so for that i have created rest api, when i do run api http://127.0.0.1:8000/api/v1/users/, it gives me this error : 'User' object has no attribute 'user'. here i have added my whole code, can anyone please look my code and help me to resolve this issue ? models.py from django.db import models from django.contrib.auth.models import User from django.contrib.auth import get_user_model class Songs(models.Model): # song title title = models.CharField(max_length=255, null=False) # name of artist or group/band artist = models.CharField(max_length=255, null=False) def __str__(self): return "{} - {}".format(self.title, self.artist) class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=255, null=False) dob = models.CharField(max_length=255, null=False) address = models.CharField(max_length=255, null=False) country = models.CharField(max_length=255, null=False) city = models.CharField(max_length=255, null=False) zip = models.CharField(max_length=255, null=False) photo = models.CharField(max_length=255, null=False) def __str__(self): return "{} - {}".format(self.title, self.dob, self.address, self.country, self.city, self.zip, self.photo, self.user) serializers.py from rest_framework import serializers from .models import Songs from .models import UserProfile from django.contrib.auth.models import User class SongsSerializer(serializers.ModelSerializer): class Meta: model = Songs fields = … -
Django TestCase do not pass anymore: wrong url
I develop a DJango project and have develop few tests One of these tests used to pass but do not anymore and I do not understand why class IndexPageTestCase(TestCase): def setUp(self): self.client = Client() self.pays = Pays.objects.create(pay_ide = 1,pay_nom = 'Côte d\'Ivoire',pay_abr = 'CIV') self.region = Region.objects.create(reg_ide = 1,pay = self.pays,reg_nom = 'Region 1',reg_abr = 'RE1') self.site = Site.objects.create(sit_ide = 1,reg=self.region,sit_typ = 'National',sit_nom = 'PA',sit_abr = 'PA') self.user = User.objects.create_user('user','user@user.com','password') self.profile = Profile.objects.create(user=self.user,site = self.site) def test_index_page(self): self.client.post('/registration/login/', {'username': 'user', 'password': 'password'}) response = self.client.get(reverse('randomization:index')) print(response) self.assertEquals(response.status_code,200) print show it is not the good url (/accounts/login/?next=/randomization/ instead of /registration/login/): <HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/accounts/login/?next=/randomization/"> -
Saving list in DB with Django
When I get a getlist in the server side in django and try to save it into DB the list seems saved like splited. nseries = request.POST.getlist('ns[]') obj.numero_serie = list(nseries) What the server receives The result should be an array like: ['656','657','658'], but it gives me that: [ ' 6 5 6 ' , ' 6 5 7 ' , ' 6 5 8 ' ] When I try to pass it as a js array -
Project structure for API only Django project
I want to create a Django based backend providing an API only. The API shall be used by/integrated with a JS frontend. The backend consists of several parts like configuration, visualization, etc. According to design best practices I'd first create a Django project my_project with django-admin startproject my_project . and add an app per part with python manage.py startapp configuration, python manage.py startapp visualization, etc. To me it's not clear how I have to adopt the Django design best practice of using apps to RESTful API based JS frontend integration. In case I want to integrate the backend with a JS frontend how should I structure my codebase? Should I create apps configuration, visualization, ... and define corresponding models with a single RESTful API. Where should I place the API sources w.r.t. project structure? How should I map the API to models? -
How to make a dependent drop-down be required only when there are options available in Django?
I'm fairly new to Django/Python, so apologies in advance. I have a form with a dependent drop-down. Currently, I have it set so that the second drop-down only appears if there are options available in it, otherwise is hidden. What I am having trouble with is that, whenever you choose a primary(Work Area) option that has a secondary(Station) drop-down, you can submit the form without having selected an option from the dependent (secondary) drop-down, which is supposed to be required whenever there are options in it. How can I modify this so that the dependent drop-down is required whenever it appears? models.py class WorkArea(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Station(models.Model): work_area = models.ForeignKey(WorkArea, on_delete=models.CASCADE, related_name="stations") name = models.CharField(max_length=50) def __str__(self): return self.name class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False, help_text="Work Area", related_name="work_area") station_number = models.ForeignKey(Station, on_delete=models.SET_NULL, null=True, help_text="Station", related_name="stations", blank=True) forms.py class WarehouseForm(AppsModelForm): class Meta: model = EmployeeWorkAreaLog widgets = { 'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}), } fields = ('employee_number', 'work_area', 'station_number') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['station_number'].queryset = Station.objects.none() if 'work_area' in self.data: try: work_area_id = int(self.data.get('work_area')) self.fields['station_number'].queryset = Station.objects.filter(work_area_id=work_area_id).order_by('name') except (ValueError, TypeError): pass elif … -
Django. How to call a python function from HTML button without reloading page?
I want to call a python function in the backend without reloading the page. Like this: index.html <button name="button" onclick="run_function(param1, param2)">Run</button> views.py some_function(param1, param2): return(param1, param2) Please don't answer with "learn the whole django documentation by hard!" i have already done some research, however I havn't quiete found any working code for my case. -
AWS Environment Variables in CodePipeline for Django Database Connection
I have been looking at CodePipeline with a basic Django Project and wanted to setup some database connections. I have been using a AWS CodeStar to create a basic project and then extending it into a 'beta' section and a 'prod' section with a manual sign off in between. I wanted the Django Project to connect to dbBeta if it was in the beta environment and dbProd if it was in the production environment. When I look at the build stage of the project, it is possible to create an environment variable, eg ENV 'BETA' (although I used PRERELEASE in this image) However, when I ssh into the EC2 instances it appears that these environment variables only exist in the build section (I believe this is done in docker), but not in the EC2 instances that are created (FYI: I am creating Elastic Beanstalk, not individual EC2 instances). It did occur to me that I could try to muck around with the CloudFormation template file so that it wrote 'PROD' or 'BETA' into an environment variable ( and the .bash_profile) when it was created. What I was wondering is if this is correct or if I am completely missing something. … -
Django ecommerce tags for intermediate model Views
I added quantity updation field using intermediate model "cartitem". I am able to add or change quantities in the backend. How do i do it in the front end? Do i need to change Django view model? What tags should i use in html templates? -
I get a socket error in my web application
I developed the frontend interface with reactjs. backend; I developed it with django and bought it on the docker with nginx. On the frontend side I get the following error. As far as I'm researching, nginx websocket support needs to be added. Can you help me ? upstream restgunicorn_server{ server myproject-django-api:8000; } server{ listen 80; resolver 127.0.0.11; location /.well-known/acme-challenge/ { root /var/www/certbot; } location / { return 301 https://$host$request_uri; } location /static/ { alias /opt/services/myproject-django-api/static/; } location /media/ { alias /opt/services/myproject-django-api/media/; } } # SSL server { listen 443 ssl; resolver 127.0.0.11; ssl_certificate /usr/share/nginx/certificates/fullchain.pem; ssl_certificate_key /usr/share/nginx/certificates/privkey.pem; include /etc/ssl-options/options-nginx-ssl.conf; ssl_dhparam /etc/ssl-options/ssl-dhparams.pem; location / { proxy_pass http://restgunicorn_server; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; #Websocket support proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } location /static/ { alias /opt/services/myproject-django-api/static/; } location /media/ { alias /opt/services/myproject-django-api/media/; } } -
Django DecimalField: remove Decimal('x') at the output when stored in a dictionary
I want to export a Python dictionary to a JSON file via json.dumps(). The data is collected using a Django modelfield "DecimalField" which is using the python decimal datatype. The problem now is, that the data inside the dictionary is presented like: 'interval': Decimal('2') and the json.dumps() cannot handle this because of this Decimal string. Is there any possibility to remove the "Decimal" from the output and just display the number like 'interval': 2 ? Or do I need to change all my ModelFields to Float/Integer? -
I don't understand Docker's "POSTGRES_USER: parameter not set"
It is difficult for Docker beginners. I created a project with cookiecutter-django. I want to start with Docker after that, but I can't start. So I run docker run -it apasn_local_django / bin / ash Entrypoint: line 10: POSTGRES_USER: parameter not set Was issued. The env_file: environment variable is set in the docker-compose file. Isn't it usable in Dockerfile? What should I do about this solution? docker-compose version: '3' volumes: local_postgres_data: {} local_postgres_data_backups: {} services: django: build: context: . dockerfile: ./compose/local/django/Dockerfile image: apasn_local_django depends_on: - postgres volumes: - .:/app env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - "8000:8000" command: /start postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: apasn_production_postgres volumes: - local_postgres_data:/var/lib/postgresql/data - local_postgres_data_backups:/backups env_file: - ./.envs/.local/.postgres entrypoint #!/bin/sh set -o errexit set -o pipefail set -o nounset if [ -z "${POSTGRES_USER}" ]; then base_postgres_image_default_user='postgres' export POSTGRES_USER="${base_postgres_image_default_user}" fi export DATABASE_URL="postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}" Dockerfile ... WORKDIR /app ENTRYPOINT ["/entrypoint"] -
Django Rest Framework: Return response from mixin's dispatch method
In order to interact with slack, a server needs to be able to validate requests based on some cryptographic hashing. If this check returns false, the server should respond with a 400. It seems sensible to do this as a mixin: class SlackValidationMixin: def dispatch(self, request, *args, **kwargs): if validate_slack_request(request): return super().dispatch(request, *args, **kwargs) else: return Response(status=status.HTTP_400_BAD_REQUEST) This gives the error "accepted_renderer not set on Response" Based on a SO question, I added the following: class SlackValidationMixin: def dispatch(self, request, *args, **kwargs): if validate_slack_request(request): return super().dispatch(request, *args, **kwargs) else: response = Response(status=status.HTTP_400_BAD_REQUEST) response.accepted_renderer = JSONRenderer response.accepted_media_type = "application/json" response.renderer_context = {} return response But this gives the error: AttributeError: 'NoneType' object has no attribute 'get_indent' Why does it need an accepted_renderer, given that it is only responding with an HTTP status code, with no additional data? What is the easiest way of getting around this?