Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Does WSGI behave dynamicly?
I remember when I save my files in PHP language, it didn't need to restart or reload apache web server. In Python, specialy Django, If I use django webserver with runserver command,it needs to restart django if I change my files. Question is, if I use WSGI in server, Does it behave such as php or runserver command? -
How to remove , while using Django {% for in %}
Trying to stop a comma being used on last item in loop, I want to seperate everything with a , but not the last thing as it is closing with a ] bracket. series: [{`enter code here` {% for service in availability.getSortedServices %} name: '{{ service }}', data: [12908, 5948, 8105, 11248, 8989, 11816, 18274, 18111] }, <----------------------------------------------------------------------how can i stop Django/Script stop this for last item on list, i want comma in all items except at end of last {% endfor %} ] -
I am not able to pass dynamic data in html file
I want to render my database information into HTML pages. I have used the way of passing dynamic data from databases. But, it's not working. I am seeing an empty page as a result. -
Mock decorator in django test
I want to test below code in view.py: class A(view): @has_access def get(request): ..... but I couldn't mock @has_access with patch('pathtouse.has_access').start() and even I tried with patch('pathtouse.has_access') as has_access how can I mock @has_access? I don't want execute decorator when I test A.get() -
How can I connect my buttons with two URLs in django?
I'm trying to connect a template that has two buttons with other two templates. The first button sends you to a login form and the second to a register one. I want to know how to modify my HTML template for it to do this. paginaPrincipal.html {% extends "base.html" %} {% block titulo %} PAGINA PRINCIPAL {% endblock %} {%block contenido %} <p>Tengo una cuenta</p> <p><button>Iniciar Sesion</button></p> <p>No tengo una cuenta</p> <p><button>Registrarse</button></p> {% endblock %} urls.py path('principal/', views.intro, name='pagina_principal'), path('registro/', views.registro_usuario, name='registro_usuario'), path('login/', views.login_view, name="login"), I want to connect those two button tags with login and registro urls, I guess I have to use the a tags but I don't know how to do this. Help is much appreciated -
Paginating a filtered queryset
I'm trying to implement a dynamic filter form in my web application for an e-commerce website, the filter works fine, but getting to paginate it is the issue, once the set is filtered, and i to click next page, it runs through the whole function again and the filtered set is overridden by Product.objects.all() def explore(request): categories = Category.objects.all() product_list = Product.objects.all().order_by('-Name') if request.GET: name = request.GET.get('name') brand = request.GET.get('brand') price = request.GET.get('price') colour = request.GET.get('colour') size = request.GET.get('size') if is_valid(name): product_list = product_list.filter(Name__icontains=name) if is_valid(brand): product_list = product_list.filter(Brand__icontains=brand) if is_valid(price): product_list = product_list.filter(Price__lte=price) if is_valid(colour): product_list = product_list.filter(variations__product_variations__value__icontains=colour).distinct() if is_valid(size): product_list = product_list.filter(variations__productvariation__value__icontains=size).distinct() paginator = Paginator(product_list, 2) # Show 25 products per page page = request.GET.get('page') products = paginator.get_page(page) else: paginator = Paginator(product_list, 25) # Show 25 products per page page = request.GET.get('page') products = paginator.get_page(page) context = {'categories':categories, 'products':products} if request.GET: if is_valid(name): context.update({'name':request.GET['name']}) if is_valid(brand): context.update({'brand':request.GET['brand']}) if is_valid(price): context.update({'price':request.GET['price']}) if is_valid(colour): context.update({'colour':request.GET['colour']}) if is_valid(size): context.update({'size':request.GET['size']}) return render(request, 'commercial/explore.html', context) -
Issues with Gunicon and Docker alpine-fat Image
I'm having a strange issue regarding Gunicorn installation for a Django project. My Dockerfile extends FROM openresty/openresty:alpine-fat as follows: FROM openresty/openresty:alpine-fat # VERSIONS ENV ALPINE_VERSION=3.8 \ PYTHON_VERSION=3.8.0 # PATHS ENV PYTHON_PATH=/usr/local/bin/ \ PATH="/usr/local/lib/python$PYTHON_VERSION/bin/:/usr/local/lib/pyenv/versions/$PYTHON_VERSION/bin:${PATH}" \ # These are always installed. # * dumb-init: a proper init system for containers, to reap zombie children # * musl: standard C library # * lib6-compat: compatibility libraries for glibc # * linux-headers: commonly needed, and an unusual package name from Alpine. # * build-base: used so we include the basic development packages (gcc) # * bash: so we can access /bin/bash # * git: to ease up clones of repos # * ca-certificates: for SSL verification during Pip and easy_install PACKAGES="\ dumb-init \ musl \ libc6-compat \ linux-headers \ build-base \ bash \ git \ ca-certificates \ libssl1.0 \ libffi-dev \ tzdata \ postgresql \ postgresql-dev \ " \ # PACKAGES needed to built python PYTHON_BUILD_PACKAGES="\ bzip2-dev \ coreutils \ dpkg-dev dpkg \ expat-dev \ findutils \ gcc \ gdbm-dev \ libc-dev \ libffi-dev \ libnsl-dev \ libtirpc-dev \ linux-headers \ make \ ncurses-dev \ libressl-dev \ pax-utils \ readline-dev \ sqlite-dev \ tcl-dev \ tk \ tk-dev \ util-linux-dev \ xz-dev \ zlib-dev … -
What is the best practice to dynamically change content in django cms template depends on country/endpoint
I'm looking for the very best practice to change some content on the site in the header depends on the endpoint in site url. I'm using django cms to generate html templates with a content. I have aside tag with some content written in german with german adress. If user from Brasil visits my website I want to use the adress of an office that is not placed in Germany but in Brasil - so a pure translation is not the way. I'm using python 3+, django cms. I'm new into django cms, and dunno if there is any preffered option. -
my form just loads but I can't edit it . Its Profile create form
This is my models . I have created abstract user instead of django built in user . I have also added image field from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import gettext_lazy as _ from PIL import Image class User(AbstractUser): ROLES = (('0','Admin'),('1','Reporter'),('2','Guest')) role = models.CharField(choices=ROLES, default='2', max_length= 1) email = models.EmailField(_('email address'), unique=True) REQUIRED_FIELDS = ('email',) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) dob = models.DateField(null= True, blank = True) address = models.CharField(max_length=100, blank=True) image = models.ImageField(default='default.jpg', upload_to='profile_pic') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) This is my signals . i have created so that I can have instant Profile after I register from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from accounts.models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() this is my view.. I have done function based view.. this view contains 2 forms one for profile and other for username and firstname @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance= … -
Blockquote Not working in CKEditor (Django)
I'm working on a project and I'm using CKEditor. After struggles, most features work but blockquote is not working. I work on the editor itself but when I display on template it's not. see screen shorts on templates after printing the field its gone Here is how I added it -
IntegrityError: duplicate key value violates unique constraint
I created a model in a django app and populated the data into the table from pgadmin but now when I am trying to create a record from the app it throws this integrity error: duplicate key value violates unique constraint "packsapp_foo_pkey" DETAIL: Key (id)=(4) already exists. Here's the models.py class foo(models.Model): a = models.CharField(max_length=500, default=0) b = models.EmailField(max_length=500, default=0) c = models.CharField(max_length=500, default=0) d = models.CharField(max_length=500, default=0) Do I always have to insert data from the app itself ? -
How to use 2 models within a serializer in Django REST API?
I just started using the Django Rest Framework recently and was wondering how to use 2 models within a single serializer. I have a custom model named 'Profile' and am also using a default Django model 'User'. With these two tables, I planned to use nested representations. Finally, in order to test the RegisterAPI, I wanted to create data using the POSTMAN tool but currently, it's not working as expected. This is what I had done so far: models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) company = models.CharField(max_length=100, blank=True, null=True) address = models.TextField() views.py: class RegisterAPI(APIView): permission_classes = [AllowAny] def post(self, request, format=None): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() content = { 'result': 'Thanks for registering!' } return Response(content, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py: from rest_framework import serializers from myapp.models import Profile from django.contrib.auth.models import User class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['company', 'address'] class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer(many = True) class Meta: model = User fields = ['username', 'email', 'password', 'profile'] def create(self, validated_data): profile_data = validated_data.pop('profile') password = validated_data.pop('password', None) # instance = self.Meta.model(**validated_data) user = User.objects.create(**validated_data) if password is not None: user.set_password(password) user.save() Profile.objects.create(user = user, **profile_data) return user Within POSTMAN, I … -
Is there any way to get selected values from ManyToManyField before save in Django Model
I've a model with many-to-many field. And I want to pre-process the values that will be selected on the many-to-many field. I need help from the experts. Thanks in advance. I've already tried to solve according to my scenario. But it's not working what I want. My code is given below: class Product(models.Model): sku = models.CharField(max_length=50, null=True, blank=True, verbose_name='sku'.upper()) title = models.CharField(max_length=50, null=False, blank=False, verbose_name='title'.title()) slug = models.SlugField(null=True, blank=True) category = models.ManyToManyField(Category, null=True, blank=True) ..... def save(self, *args, **kwargs): selected_categories = self.category.all() ......