Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
IndentationError: unindent does not match any outer indentation level (views.py, line 20)
enter image description here Tried every damn thing from changing indentation to spaces to writing a new file, this error is determined to not go from django.urls import path from . import views app_name="main" urlpatterns= [ path("",views.homepage,name="homepage"), path("register/", views.register, name="register") ] -
I want to fetch the data using api in flutter
I am trying to build freelancing type app. I am using flutter and for my backend data i created an api using django rest framework. Here is the models.py: class Package(models.Model): management_duration_choices = ( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5"), ("6", "6"), ("7", "7"), ("8", "8"), ("9", "9"), ("10", "10"), ("11", "11"), ("12", "12"), ("13", "13"), ("14", "14"), ("15", "15") ) title = models.CharField(max_length=120) delivery_time = models.ForeignKey( DeliveryTime, on_delete=models.CASCADE, null=True) package_desc = models.TextField(null=True) revision_basic = models.ForeignKey(Revision, on_delete=models.SET_NULL, null=True, blank=True, related_name="revision_basic") revision_standard = models.ForeignKey(Revision, on_delete=models.SET_NULL, null=True, blank=True, related_name="revision_standard") revision_premium = models.ForeignKey(Revision, on_delete=models.SET_NULL, null=True, blank=True, related_name="revision_premium") num_of_pages_for_basic = models.ForeignKey(NumberOfPage, on_delete=models.SET_NULL, null=True, related_name="num_of_pages_for_basic", blank=True) num_of_pages_for_standard = models.ForeignKey(NumberOfPage, on_delete=models.SET_NULL, null=True, related_name="num_of_pages_for_standard", blank=True) num_of_pages_for_premium = models.ForeignKey(NumberOfPage, on_delete=models.SET_NULL, null=True, related_name="num_of_pages_for_premium", blank=True) is_responsive_basic = models.BooleanField(default=False, null=True, blank=True) is_responsive_standard = models.BooleanField(default=False, null=True, blank=True) is_responsive_premium = models.BooleanField(default=False, null=True, blank=True) setup_payment = models.BooleanField(default=False, null=True, blank=True) will_deploy = models.BooleanField(default=False, null=True, blank=True) is_compitable = models.BooleanField(default=False, null=True, blank=True) supported_formats = models.ManyToManyField(FileFormats, blank=True) # For Logo Design provide_vector = models.BooleanField(default=False, null=True, blank=True) is_3dmockup = models.BooleanField(default=False, null=True, blank=True) is_high_res_for_basic = models.BooleanField(default=False, null=True, blank=True) is_high_res_for_standard = models.BooleanField(default=False, null=True, blank=True) is_high_res_for_premium = models.BooleanField(default=False, null=True, blank=True) will_sourcefile_for_basic = models.BooleanField(default=False, null=True, blank=True) will_sourcefile_for_standard = models.BooleanField(default=False, null=True, blank=True) will_sourcefile_for_premium = models.BooleanField(default=False, null=True, blank=True) # For Digital … -
What is a good way to proceed to store and use sensitive data in prod environment?
I have a django web app in a production environment hosted on a server. To store sensitive data I am using a .env file excluded from my git process stored on the server where my app is hosted. # .env file { "ENV_TYPE": "prod", "SECRET_KEY": "mysecretkey", "ALLOWED_HOSTS":[ "somewhere.com" ], "DEBUG": false, "STATIC_ROOT": "/somewhere/staticfiles", "DATABASES": { "default": { "ENGINE": "django.db.backends.mysql", "NAME": "databaseName", "USER": "username", "PASSWORD": "myPassword", "HOST": "somewhereelse.com" } } } And in my app I get back data like this in setting.py for instance: # setting.py # Get back non secret env data such as DEBUG, ALLOWED HOSTS with open(os.path.join(BASE_DIR, '.env'), 'r') as f: env_data = json.load(f) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env_data["SECRET_KEY"] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env_data["DEBUG"] ALLOWED_HOSTS = env_data["ALLOWED_HOSTS"] Do you believe this is a good way to proceed ? Indeed I still have somewhere on my server some passwords that are hard coded. -
Apache24 Production Server For Django React App: React Shows 403 Forbidden Error
I am trying to run a production server on an AWS EC2 instance (Windows) using Apache for a Django backend connected with a React frontend. When I test the app on Django's runserver everything works well, but currently, when I try to use it on Apache I am just seeing a blank screen. When I check the console it tells me that I don't have permission to access the react static files (403 forbidden error). In my attempts to fix this, I have run collectstatic, which has put all of the static files (including the react ones) on an S3 Bucket. This means that the Django pages (admin pages) are able to use the static files, but the React pages aren't accessing the files from the S3 bucket. I'm not sure if it is better to find a way to get my React app to use the static files from the bucket, or if I should just continue to find a way to get Apache to serve the static files. I know that the files are able to be found because it isn't a 404, but a 403, so it must be some problem with my configuration that isn't giving … -
I got error while creating virtual environment in django
while creating a virtual environment in Django I got site-package is not writable and that's why when i write command of Django-admin so i got error not found in external or internal can anyone how I solve this -
How to Iterate a list sent from React in Django
I want to iterate colors in Django, it should print first red then green # data from frontend react data = request.data print(data) <QueryDict: {'colors': ['red', 'green']}> result should be like this : red green -
How do i maintain a user cover uploaded image in fields whiles adding new images without it getting deleted in django
How do i get Django to store already uploaded cover image to a user without getting it deleted when a new image is uploaded, but simply replace it? I'm having a challenge trying to figure out how to maintain old cover images while adding new once to a user. what happens is that when i upload a new cover image it simply deletes the previous one from the database. Here is my cover image models: class AccountCover(models.Model): account = models.ForeignKey(Account,on_delete=models.CASCADE) cover_image = models.ImageField(max_length=255,upload_to=get_cover_cover_image_filepath,default=get_default_cover_image,) Here the view to upload cover image cover = AccountCover.objects.filter(account=account.id).first() if request.user: forms = CoverImageForm(request.POST, request.FILES,instance=cover, initial = {'cover_image':cover.cover_image}) if request.method == 'POST': f = CoverImageForm(request.POST, request.FILES,instance=cover) if f.is_valid(): data = forms.save() data.account = cover.account data.save() return redirect('account:edit', account.id) else: f = CoverImageForm() context['f'] = f -
Sending data from django app to the arduino
I have written an arduino sketch to turn on and off a light using serial port. I coded to send serial data using pyserial. It worked fine. The python script below worked fine. But the problem is when I implemented that in the django application. Everthing works fine sending data, return values everything works fine but it doesn't turn on the light. I checked return value for s.write("on".encode()) it is also same as of the python script but in django it doesn't turn on the light. **Code from Arduino Sketch** String command; void setup() { Serial.begin(9600); Serial.println("Type your command"); } void loop() { if(Serial.available()){ command = Serial.readStringUntil('\n'); if(command =="on"){ digitalWrite(7, HIGH); } else if(command == "low"){ digitalWrite(7, LOW); } } } **code from python script** import serial ser = serial.Serial() ser.baudrate = 9600 ser.port = 'COM5' ser.open() data = ser.readline(82) ser.write("on".encode()) print(data.decode("utf-8")) **code from django** import serial # Create your views here. @csrf_exempt def index(request): if (request.method=="POST"): giveCommand = ReadFromArduino(baudrate=9600, port = "COM5") res = giveCommand.writeData(commandData = "on") return HttpResponse(res) s = serial.Serial() s.baudrate = 9600 s.port = "COM5" s.open() ret = s.write("on".encode()) print(ret) s.close() return HttpResponse("Hello") # giveCommand = ReadFromArduino(baudrate=9600, port = "COM5") # res = giveCommand.writeData(commandData = "on") … -
How to make the django rest framework POST button work?
I have a model like this: class Ad(models.Model) : title = models.CharField( max_length=200, validators=[MinLengthValidator(2, "Title must be greater than 2 characters")] ) price = models.DecimalField(max_digits=7, decimal_places=2, null=True) text = models.TextField() # Shows up in the admin list def __str__(self): return self.title A Viewset like this: class AdViewSet(viewsets.ModelViewSet): """ API endpoint that allows ad to be viewed or edited. """ queryset = Ad.objects.all().order_by('-created_at') serializer_class = AdSerializer I have made the router and the serializer that I didn't include here because I don't think it's needed to show my issue. In the Django Rest Framework in /api/ads/ I can see all my previous ads created using the django admin and below a form to post data which looks like this: When I click on the POST button of the form,it doesn't make a POST request it just reload the page. I can confirm it from the Firefox devtool and the server log, no POST request are made. So my question is this: how to make this POST button works as expected so I can check my serialiser and everything work as it should ? -
Shows ERROR 405 in browser and method not allowed in shell - Django
I'm building a website that has 2 user types. The registration forms works fine but the login form and the Add Products form gives HTTP 404 ERROR in the browser and shows method not allowed in the shell. Here's all the codes of the project: seller/forms.py def login_seller(request): if request.user.is_authenticated: return redirect('home') else: if request.method=='POST': logform = AuthenticationForm(data=request.POST) if logform.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None : login(request,user) return redirect('home') else: messages.error(request,"Invalid username or password") else: messages.error(request,"Invalid username or password") return render(request, 'Seller/login-seller.html', context={'logform':AuthenticationForm()}) seller/models.py from django.db import models from Accounts.models import CustomUser class SellerProfile(models.Model): user = models.OneToOneField(CustomUser, on_delete= models.CASCADE) name = models.CharField(max_length= 90) email = models.EmailField(max_length = 90, unique = True) store_name = models.CharField(max_length = 30, unique = True) def __str__(self): return self.name products/models.py CATEGORY_CHOICES = [ ("ILLUSTRATION", "Digital Illustration"), ("EBOOKS", "eBooks"), ("PHOTOGRAPHS", "Photographs"), ("COMICS", "Comics"), ] class Products(models.Model): seller = models.ForeignKey(SellerProfile, on_delete = models.CASCADE) title = models.CharField(max_length = 255) product_category = models.CharField(choices = CATEGORY_CHOICES, max_length = 100, default = 'eBooks') description = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2) discounted_price = models.DecimalField(max_digits=10, decimal_places=2, default = 0.00) thumbnail = models.ImageField(upload_to = 'media/thumbnail/',null=True, blank = True) files = models.FileField(upload_to = 'media/product_files/', null = … -
Get list of linked objects(used as foreign keys) when deleting an object in Django
I wish to create an API that can be called from the frontend and displays the summary and linked objects to the object i want to delete( Just like in the Django admin delete view) The linked objects are deleted as cascade is being used in the model definition How can I do that? I tried overriding the delete model and the delete view but couldn't get the desired results. -
pop up at if condition in views.py in django
I want to show a pop-up instead of the httpresponse shown as below in views.py after satisfying the if condition - (below is section of code in views.py) if data['check_in'] > now and data['check_out'] > now and data['check_out'] > data['check_in']: #Check if the room is available if available_rooms is not None: if len(available_rooms) >= int(num_rooms_req): for i in num_rooms_req_lst: #Book the First available room # print(available_rooms[i-1]) booking = book_room(request, available_rooms[i-1],data['check_in'],data['check_out'],total_cost) return HttpResponse(booking) else: return HttpResponse('Only 1 rooms available in this category') else: return HttpResponse('All the rooms of this category are booked! Try another category!') else: return HttpResponse('checkin/checkout date in past or checkout date is prior to checkin date!') so in the above views.py code section - what would be the best way to show the return HttpResponse pop-ups or alerts (but alerts would take me to different html) - I don't want to navigate away from the parent html... -
Dynamic user creation in django
I'm creating web-app with the following users, National Director Regional Director Project Coordinator Agent Expected Outcome: A National Director should be able to create a Regional Director, a Regional Director should be able to create a Project Coordinator, and a Project Coordinator should be able to create Agents. Question: How should I make views and forms to accomplish such? #Models class User(AbstractUser): pass class National_Director(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) user = OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL) gender = models.CharField(max_length=20, null=False, blank=False, choices=GENDER) id_no = id_no = models.CharField(max_length=150, null=False, blank=False, unique=True) address = models.TextField(null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True) class Regional_Director(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) user = OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL) REGION = ( ('North', 'Northern Region'), ('East', 'Eastern Region'), ('West', 'Western Region'), ('South', 'Southern Region'), ) region = models.CharField(max_length=20, null=False, blank=False, choices=REGION) gender = models.CharField(max_length=20, null=False, blank=False, choices=GENDER) national_director = models.ForeignKey(National_Director, null=True, blank=True, on_delete=SET_NULL) id_no = id_no = models.CharField(max_length=150, null=False, blank=False, unique=True) address = models.TextField(null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True) class Coordinator(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) user = OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL) regional_director = models.ForeignKey(Regional_Director, null=True, blank=True, on_delete=SET_NULL) region = models.CharField(max_length=15, null=True, blank=True) id_no = id_no = models.CharField(max_length=150, null=False, blank=False, unique=True) … -
What do you think the pros/cons of the integration of Django and Vue.js? [closed]
Vue.js can handle SQL with node.js. Django can have Javascript. Integration of Django and Vue.js is more complicated than the above two ways. My question is what kind of situation is suitable for the Integration of Django and Vue.js. And if you could, give me some example of service of it. -
Is there a posibility to link 2 models in Django?
I'm trying to create a quiz web app , where u will enter the app and u will have 2 buttons: create a quiz , and solve a quiz. You can do it without needing to register. I've created the models, one for Quiz and one for Question and i've put an UUID primary key to the quiz so that i can use this unique id as an extension to my link to get to the quiz that contains the questions. My problem is this. After i create a quiz , i want to directly go to the create questions file regarding the created quiz. Becouse right now after i create the quiz, i need to separately go and create a question, then make a dropdown to select the quiz wich the question is for. [image1][1] [1]: https://i.stack.imgur.com/dr4iP.png [image2][2] [2]: https://i.stack.imgur.com/K5tFt.png [image3][3] [3]: https://i.stack.imgur.com/7GdcK.png -
how to show active page while using base template and bootstrap
base.html The below file is my base template, I'm extending this template in my other pages like index, profile, etc. now in base.html home is my active page and I have done this with help of bootstrap class active, help me that how I can use this active class for different pages to show them active. I'm using the Django framework for rendering templates. <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <title>Student Portal</title> </head> <body> <!-- nav bar start --> <nav class="navbar navbar-expand-lg navbar-light "> <div class="container-fluid"> <a class="navbar-brand" href="/">StudentPortal</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02" aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarTogglerDemo02"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="/">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'signup' %}">signup</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'login' %}">Login</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'profile' %}">profile</a> </li> </ul> </div> </div> </nav> {% block content %} {% endblock content %} <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <!-- Option 2: … -
Can I modify the URLs Django uses for "View on site" admin links to override caching?
My site is behind a cache. I use Django's "View on site" functionality (eg. by defining a get_absolute_url method for each model), but when I make a change to an object and then click "View on site", I don't see the changes because the cache hasn't expired. I don't particularly want to do things like check the referrer header (eg. Django admin routes these URLs via a redirect like /admin/r/19/1653/, which I could test for) as this breaks my cache strategy (I don't currently cache based on referrer). I tried injecting a timestamp query parameter via JavaScript (eg. to send admin users to /some-django-url?ts=12345, which would bust the cache) but this doesn't work because of the above redirect step (eg. I can't "see" the final Django URL in the admin screen, just the /admin/r/ redirect). Does anyone have a good strategy for this? -
Add single field for queryset
I have a list of elements (queryset) that I display in my admin as a list, and also as detail for each element. The whole list should be sent to the frontend with a Boolean flag, saying if these elements will be displayed before or after other elements (the frontend takes care of this, depending on this flag). The flag, which will be a checkbox in the admin, applies for the whole list, not for each element. I am not sure how to handle this, and two options come to mind: I could add a model just to handle this flag, and then combine it with my model for the queryset in the admin class, so the checkbox appears next to the list. I could display the checkbox in each detail view, which will change the value for all elements on save, and keep the exact same flag with the same value inside each element. I could add a helper_text in the admin saying that the value changes all elements' value. Any other idea is welcome. For clarity, this is what I would like to end up in my API: {display_at_beginning: true, elements: [{...}, {...}, {...}]} -
How to implement the "selectpicker" class for all the select element in website?
I have a website, backend using Django, frontend using normal HTML5. I want to change all the default selection box to the class: "selectpicker" once in some place so it could be implemented in all the selection box in the websites. How could I do that in one place? I have tried: base.html <style> select { class="selectpicker"; } </style> ... app.html {% extends 'base.html' %} <style> select { class="selectpicker"; } </style> But failed to do so. I want this kind of solution, better only make change in base.html to change all the selection box in the websites as I have tons of HTML in my website. -
Django admin page copy ManyToMany related field from one model to another
I am trying to write a scheduling app. Here there are multiple workers and I create a group of workers. The Group is used as a template to create schedule. When I create a Schedule object I want to take input of a Group object and copy the members from the Group object to the Schedule object. I don't want to give a ForeignKey to the Group object itself because the workers might change for a single day, whereas the group should be left intact as a template. models.py class Worker(models.Model): name = models.CharField(max_length=30) email = models.EmailField() class Group(models.Model): name = models.CharField(max_length=30) members = models.ManyToManyField(Worker, blank=True) class Schedule(models.Model): start_time = models.DateTimeField() end_time = models.DateTimeField() date = models.DateField() members = models.ManyToManyField(Worker, blank=True) I understand this can be done easily with views and html templates. But I am trying to do the same under admin page. I have a form for Schedule and registered it in admin.py forms.py class CreateScheduleForm(forms.ModelForm): group = ModelChoiceField(queryset=Group.objects.all()) class Meta: model = Schedule fields = ( 'date', 'start_time', 'end_time') admin.py @admin.register(Schedule) class ScheduleAdmin(admin.ModelAdmin): form = CreateScheduleForm I don't quite understand how to receive this input and process the Group object instance and copy the members. Any help … -
How to get modelform field data filtered by another field?
I am trying to create a new custome model form forthe admin page, but i am facing an issue getting districts filtered by selected city. Here is my code class MinimumListingPriceAdminForm(forms.ModelForm): city = forms.ModelChoiceField( queryset=City.objects.all(), empty_label="Select a city", required=False ) districts = forms.ModelMultipleChoiceField( queryset=District.objects.all(), required=False ) class Meta: model = ListingPrice exclude = ('price',) I need to filter districts based on the selected city. -
getting error on migrating raise TypeError("'Collection' object is not callable. If you meant to " TypeError: 'Collection' object is not callable
I am using djongo to connect my rest_framework API with MongoDB. I have deleted the 0001_initial.py file and try to push the migrations using python manage.py makemigrations and python manage.py migrate but I am getting these errors while doing this. my settings.py file DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'TMS', } } (env) D:\inductionplan\django-api\backend>python manage.py migrate Operations to perform: Apply all migrations: admin, api, auth, authtoken, contenttypes, sessions, token_blacklist Running migrations: This version of djongo does not support "NULL, NOT NULL column validation check" fully. Visit https://nesdis.github.io/djongo/support/ Applying contenttypes.0001_initial...This version of djongo does not support "schema validation using CONSTRAINT" fully. Visit https://nesdis.github.io/djongo/support/ OK Applying auth.0001_initial...This version of djongo does not support "schema validation using KEY" fully. Visit https://nesdis.github.io/djongo/support/ This version of djongo does not support "schema validation using REFERENCES" fully. Visit https://nesdis.github.io/djongo/support/ OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name...This version of djongo does not support "COLUMN DROP NOT NULL " fully. Visit https://nesdis.github.io/djongo/support/ This version of djongo does not support "DROP CASCADE" fully. Visit https://nesdis.github.io/djongo/support/ Traceback (most recent call last): File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 857, in parse return handler(self, statement) File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 894, in _alter query.execute() File "D:\inductionplan\django-api\env\lib\site-packages\djongo\sql2mongo\query.py", line 533, in _drop_column self.db[self.left_table].update( … -
Insert data into models which has a foreign key in Django
I want to perform the below query in Django models where image and caption is the field of posts model and user is the foreign key of posts model : insert into posts values('" + user + "','" + image + "','" + caption + "') Here are my models: #posts model class Posts(models.Model): user=ForeignKey(User, on_delete=models.CASCADE) image=ProcessedImageField(upload_to="/images",help_text="Post", verbose_name="Post", processors=[ResizeToFill(400, 400)], format='JPEG', options={'quality': 80}) caption=models.CharField(max_length=40,null=True,default=" ",blank=True) def __str__(self): return self.user.username #user model the default user model #views def UploadPost(request): if 'user' in request.session: if request.method=='POST': post_form=UploadPostForm(request.POST, request.FILES,instance=request.user) if post_form.is_valid(): post_form.save() messages.success(request,"post uploaded") else: return error else: post_form=UploadPostForm(instance=request.user) return render(request, 'users/upload_post.html', context={'post_form': post_form}) else: return redirect('login') #html {% extends "users/base.html" %} {% load static %} {% block content %} <div class="container text-center"> {% if messages%} {% for msg in messages%} {{msg}} {%endfor%} {%endif%} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{post_form.as_p}} <button class="btn btn-outline-dark" type="submit">Upload</button> </form> <a href="{% url 'logout'%}">logout</a> </div> {% endblock content %} when I click on the upload button, it shows the success message but the post isn't uploaded -
Django (DRF) - get_queryset - Trying to return "images" with model "Product" as an extra field
I'm trying to make a queryset which returns all Products. Every Product has one or more ProductImages and I want to add them as an extra field "images" for every product. So the response I'm after is like [ { id: 1, name: "prod1", images: images } ] I've tried the following implementations: Models class Product(models.Model): name = models.CharField(max_length=255) description = models.TextField() price = models.FloatField() class ProductImage(models.Model): name = models.CharField(max_length=255) product = models.ForeignKey(Product, on_delete=models.CASCADE) My idea implemented in the simplest way class ProductViewSet(viewsets.ModelViewSet): serializer_class = ProductSerializer queryset = Product.objects.all() def get_queryset(self): queryset = Product.objects.all() product_list = [] # iterate over all products for product in queryset: images = ProductImage.objects.filter(product=q.id) product['images'] = images product_list.append(product) return product_list gives error "TypeError: 'Product' object does not support item assignment" New idea, make a new dict and add elements of product and add "images" as an extra field. class ProductViewSet(viewsets.ModelViewSet): serializer_class = ProductSerializer queryset = Product.objects.all() def get_queryset(self): queryset = Product.objects.all() product_list = [] # iterate over all products for q in queryset: images = ProductImage.objects.filter(product=q.id) product = {"id": q.id, "name": q.name, "description": q.description, "price": q.price, "images": images} product_list.append(product) return product_list gives error Internal Server Error: /api/product/ Traceback (most recent call last): File "C:\Users\Simon\.virtualenvs\django_backend-ZmgaAA1F\lib\site-packages\django\core\handlers\exception.py", line … -
UNIQUE constraint failed: account_customuser.username
I have a problem with user's signup. I use Django. When I register the first user everything is fine and the user appears in the admin panel. The problem occurs when I want to register the second user. After submiting the signup form, this error shows up: File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: account_customuser.username So it looks like the user will not be saved because the username (email) is not unique, but the email of the second user is different from the first one. Only superuser and first registered user appear at the admin panel. models.py from django.db import models from django.contrib.auth.models import AbstractUser from orders.models import Order class CustomUser(AbstractUser): email = models.EmailField(unique=True, max_length=255, default='') zip_code = models.CharField(max_length=6) address = models.CharField(max_length=255) street = models.CharField(max_length=255) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) email_confirmed = models.BooleanField(default=False) orders = models.ForeignKey( Order, related_name='orders', on_delete=models.CASCADE, null=True, blank=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.email views.py from django.shortcuts import render, redirect from .forms import CreateUserForm def signup(request): form = CreateUserForm() if request.method …