Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to color text with condition in django?
I have a django app and I want to color some text, if that text is true in dictionary. So I have this method:views.py def data_compare2(request): template = get_template("main/data_compare.html") dict2 = {"appel": 3962.00, "waspeen": 3304.07, "ananas":24} context = {"dict2": dict2} res = dict((v,k) for k,v in dict2.items()) return HttpResponse(template.render(context, request, res[3962.00])) and this is the template: <body> <div class="container center"> {% for key, value in dict1.items %} {%if {{res}} %} <div style="background-color:'red'"></div> {%endif%} {{ key }} {{value}}<br> {% endfor %} </div> </body> So the text appel": 3962.00 has to appear in red. Question: how to make the founded text in dictionary red? -
Circular import error while trying to implement a new ForeignKey() in Django
I am working on an API project that provides endpoints to front-end. There is a new field must added to related model that is "organization". Firstly, this field must added to "File" model as a foreign key and other related files like populator, renderer and validator. Secondly, 'organizationId" filter must added to /files/ endpoint. Here are my codes: files/models.py # Django from django.db.models import( CharField, ForeignKey, PROTECT, ) # Authic - Common from authic.common.models import Model # Authic - Organization from authic.organizations.models import Organization ALLOWED_EXTENSIONS = [ 'avif', 'gif', 'jpeg', 'jpg', 'mp4', 'png', 'svg', 'webm', 'webp' ] class File(Model): cloudinary_public_id = CharField( blank=True, null=True, default=None, max_length=64 ) extension = CharField( blank=True, null=True, default=None, max_length=4 ) organization = ForeignKey( Organization, on_delete=PROTECT, related_name='+', blank=True, null=True, default=None, ) class Meta: db_table = 'files' organizations/models.py # Django from django.db.models import ( BooleanField, CharField, ForeignKey, PROTECT, TextField ) # Authic - Common from authic.common.models import Model # Authic - Files from authic.files.models import File class Organization(Model): name = CharField( blank=False, null=False, default=None, max_length=256 ) url = CharField( blank=False, null=False, default=None, max_length=2048 ) theme_color = CharField( max_length=7, blank=False, null=False, default=None ) logo = ForeignKey( File, on_delete=PROTECT, related_name='+', blank=True, null=True, default=None ) html_title = CharField( blank=False, null=False, … -
Filter current user products using queryset in DRF returns []
I am trying to filter list of products linked with a user. I want to display only current users product instead of listing all. I tried this class ProductCreateList(generics.ListCreateAPIView): serializer_class = ProductSerializer def get_queryset(self): user = self.request.user return Product.objects.filter(user=user.id) serializers.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['id', 'user', 'name', 'imgUrl', 'selling_price', 'actual_price', 'quantity', 'get_profit'] models.py class Product(models.Model): user = models.ForeignKey('accounts.Account', on_delete=models.CASCADE, default=1) name = models.CharField(max_length=100, null=True, blank=True) imgUrl = models.TextField(default='') selling_price = models.FloatField(null=True, blank=True) actual_price = models.FloatField(null=True, blank=True) quantity = models.IntegerField() I got [] object when I tried to execute the endpoint. What's my mistake here? -
How to get specific objects from two list of dictionaries on a specific key value?
As i said I have two lists of dictionaries. Which are following below. timing = [ {"day_name":"sunday"}, {"day_name":"monday"}, {"day_name":"tuesday"}, {"day_name":"wednesday"}, {"day_name":"thursday"}, {"day_name":"friday"}, {"day_name":"saturday"}, ] hours_detail = [ {"day_name":"sunday","peak_hour":False}, {"day_name":"monday","peak_hour":False}, {"day_name":"tuesday","peak_hour":False}, {"day_name":"wednesday","peak_hour":False}, {"day_name":"thursday","peak_hour":False}, {"day_name":"friday","peak_hour":False}, {"day_name":"saturday","peak_hour":False}, {"day_name":"saturday","peak_hour":True}, {"day_name":"friday","peak_hour":True}, {"day_name":"thursday","peak_hour":True} ] now i want to create an other list of dictionaries. that contain values like below. i'm basically combining these two lists and also rearranging according to the day name. final_data_object = [ { "timing" :{"day_name":"saturday"}, "hour_detail":[ {"day_name":"saturday","peak_hour":False}, {"day_name":"saturday","peak_hour":True}, ] }, { "timing" :{"day_name":"friday"}, "hour_detail":[ {"day_name":"friday","peak_hour":False}, {"day_name":"friday","peak_hour":True}, ] }, soon on... ] I have tried this but it didn't work. data = [] for time_instance in timing: obj={ "timing":time_instance } for pricing_instance in pricing: if time_instance["day_name"] == pricing_instance["day_name"]: obj["pricing"] = pricing_instance data.append(obj) return data -
No Module Found, "name of the app", when running django from pipeline
So here is my set up : "aws:elasticbeanstalk:application:environment": DJANGO_SETTINGS_MODULE: backend.project.settings "PYTHONPATH": "/opt/python/current/:$PYTHONPATH" "aws:elasticbeanstalk:container:python": WSGIPath: backend.project.wsgi:application NumProcesses: 3 NumThreads: 20 "aws:elasticbeanstalk:environment:process:default": HealthCheckPath: "/ht/" MatcherHTTPCode: "200" "aws:elasticbeanstalk:environment:proxy:staticfiles": /html: statichtml /static-files: static-files /media: media-files container_commands: 10_deploy_hook_permissions: command: | sudo find /backend/.platform/ -type f -iname "*.sh" -exec chmod -R 755 {} \; sudo find /var/app/staging/backend/.platform/ -type f -iname "*.sh" -exec chmod -R 755 {} \; Which it runs: #!/bin/sh source /var/app/venv/staging-LQM1lest/bin/activate python /var/app/current/backend/manage.py makemigrations --noinput python /var/app/current/backend/manage.py migrate --run-syncdb python /var/app/current/backend/manage.py collectstatic --noinput wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.project.settings') application = get_wsgi_application() Logs from web.stdout.log Nov 30 13:50:46 ip-172-31-32-98 web: ModuleNotFoundError: No module named 'category' 'category' is one of the django app or module that contains models, view etc Any help on what's wrong here I can run the app with eb deploy but when trigger from pipeline it does not -
Django first part of accordion open but not the other within for loop
I tried to make an accordion using jquery inside my code but there is a problem when I try to open a section. This first one is working but not the second one. The code is inside a django for loop. **HTML : ** <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(function() { $('#accordeon').on('click', function(){ $(this).next().slideToggle(300); $('.accordeon-content').not($(this).next()).slideUp(300); $(this).toggleClass('active'); $('#accordeon*').not($(this)).removeClass('active'); }); }); </script> <div class="consultations"> <div class="section nosProduits"> <div class="two-blocks"> <div class="content"> <h2>Qu’est-ce que la consultation patrimoniale ?</h2> <p>Vous pensez l’expertise sur mesure d’un CGP expert inaccessible ? Pour feter nos 20 ans, nous avons innové pour vous permettre de bénéficier de l’accompagnement d’une équipe de spécialistes du patrimoine sous la forme d’une consultation de 30 minutes à 120 € TTC. </p> </div> <div class="video"> {% embed 'https://www.youtube.com/watch?v=LqiaOqiLcU4' %} </div> </div> {% for subcategory, products2 in products.items %} <div class="head" id="accordeon"> <h2>{{subcategory}}</h2> </div> <div class="accordeon-content line" style="display: none;"> {% for product in products2 %} <div class="block-consultation"> <div class="titre"> <h3>{{ product.name }}</h3> {% if product.images %} <img src="{{ product.images|first }}" class="categoryImg" alt="Image of {{ product.name }}."> {% endif %} </div> <div class="content"> <div class="description"> <p>{{ product.description }}</p> </div> <div class="options"> <div class="product"> <div> <a href="{% url 'product-purchase' pk=product.djstripe_id %}" class="btn">Souscrire</a> </div> </div> </div> </div> </div> {% … -
need a better way to validate fields in request body django depending on a specific field value
The requirement is to verify body fields in an api request depending on another field. Like: the request data has a field: action If actions is deactivate then no other field should be present in the body data however if the action is anything else we want to allow updating other fields as well such as name. currently we have a validation where we are going through the dictionary keys and comparing like below: expected_keys = ['client_updated', 'updated_by', 'actions'] if key not in expected_keys: raise ValidationError("Deactivation action does not allow {} to be updated".format(key)) Just wanted to know if there is a better way to handle via django or django rest framework, with somewhat less harcoding. -
Why create_superuser manager is not working in custom user model?
When I try to create a superuser in my app I get the next error: Traceback (most recent call last): File "C:\Users\acer\Desktop\prod\DirCom\DirCom\manage.py", line 22, in <module> main() File "C:\Users\acer\Desktop\prod\DirCom\DirCom\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 88, in execute return super().execute(*args, **options) File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 183, in handle validate_password(password2, self.UserModel(**fake_user_data)) File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\db\models\base.py", line 561, in __init__ _setattr(self, field.name, rel_obj) File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 338, in __set__ super().__set__(instance, value) File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 235, in __set__ raise ValueError( ValueError: Cannot assign "1": "User.persona" must be a "Persona" instance. Before that createsuperuser step I have a custom script that creates the first Persona of the project, and what I'm trying is to assign the first person created with ID 1 to this superuser. My model looks like this: class Persona(models.Model): """ Clase para generar mi modelo de Persona que es el modelo previo a crear un usuario, en este modelo se guardan todos los datos personales """ DEPENDENCIES_CHOICES = ( ("1", "Rectorado - Gabinete"), ("2", "Vice Rectorado"), ("3", "Rectorado - Secretaria … -
How to Implement Conditional Filter in Django Query set
I am writing a queryset in which I am in need to check the value that exists in the table or not but here is a twist. example: if a value is: "12345, ABVC43F, T5T5YUH/KJUTG678, 1234567890PO-QWERT4567-OIUYT8765-POIUY7890" which I am getting in request and like this lots of values are stored in the table. but the checking is like out of these 4 values (after split from comma we will get 4 values ) if any 3 or more than 3 gets matched with any of the records in the table then this queryset will return that complete string value from the table to which it matches. key_in_request = "12345, ABVC43F, T5T5YUH/KJUTG678, 1234567890PO-QWERT4567-OIUYT8765-POIUY7890" req_key_array = key_in_request.split(',') for getting more clarity i have a example of sql query for what i need but unable to write queryset: SQL query is here: select if((key_value is having req_key_array[0]), 1, 0) + if((key_value is having req_key_array[1]), 1, 0) as Result; here it will sum then all the 1 and 0 if conditions will be false or true, it's not a exact query but near to that. It's my first try to post question hope you will understand, if any issue please comment. -
How to test if a function gets called when another function executes in django test?
I've a method inside a manager, this method calls a function imported from different module now I'm trying to write a test that make sure the function gets called, when the manager method executes. I've tried some methods by it didn't work here is the code example. hint: I'm using pytest as testrunner from unittest import mock # Customer Manager class class ItemsManager(models.Manager): def bulk_update(self, *args, **kwargs): result = super().bulk_update(*args, **kwargs) items_bulk_updated(*args, **kwargs) return result # signals.py file def items_bulk_updated(*args, **kwargs): print("items bulk updated") # test file # Base TestCase Inherits from APITestCase class TestItems(BaseTestCase): @mock.patch("items.signals.items_bulk_updated",autospec=True) def test_bulk_update_items_triggers_signal(self, mock_function): items_qs = Items.objects.all() result = Items.objects.bulk_update(items_qs, ['item_name']) mock_function.assert_called() -
django gives me error 404 when i try to use unicode urls
there is a problem when django uses Arabic slugs . It can accepts them . But when you go for its url . It can't find a matching query in database for them . It gives me 404 . this is the urls.py and my url : re_path(r'detail/(?P<slug>[\w-]+)/$' , detail_course , name='detail_courses') and its the url that i try to enter : http://127.0.0.1:8000/course/detail/%D8%AA%D8%AD%D9%84%DB%8C%D9%84_%D8%A8%DB%8C%D8%AA_%DA%A9%D9%88%DB%8C%D9%86/ what is its problem ? -
Django Rest Framework : RetrieveUpdateAPIView
I want to add multiple data to database with RetrieveUpdateAPIView and I am not able to add that data in database. How can I update this all date in single Patch method. My view is like class CompanyDetailViewAPI(RetrieveUpdateAPIView): queryset = Companies.objects.all() serializer_class = CompanyDetailsSerializer permission_classes = [IsAuthenticated] authentication_classes = [JWTAuthentication] lookup_field = "id" and my serializer is like class KeyPersonsSerializer(serializers.ModelSerializer): class Meta: model = KeyPersons fields = [ "id", "person_name", "designation", "email", "contact_number", ] class CompanyDetailsSerializer(serializers.ModelSerializer): key_person = KeyPersonsSerializer(many=True) class Meta: model = Companies fields = [ "id", "address_line_1", "address_line_2", "city", "landmark", "state", "country", "pincode", "website", "person_name", "designation", "email", "phone", "ho_email", "ho_contact_number", "company_registration_no", "gst_no", "key_person", "company_corporate_presentation", "about_company", "company_established_date", "no_of_facilities", "no_of_employees", ] I have tried this but I cant see any result. How can I update this all date in single Patch method -
Convert datetime object to string in annotate in Python(Django)
I have a queryset like: qs = MyModel.objects.filter(name='me').values_list('activation_date') here activation_date is DateTimeField in models. How can I convert this field('activation_date') in string? I am getting error like: 'datetime object not JSON serializable' -
How to count model ForeingKeys instances per row in a template table?
I want to count how many "plans" does a "client" have per table row in my template, there's a bit of the code urls.py>>> urlpatterns = [ path('clients/', views.indexClient, name='clients'),] models.py class Plan (models.Model): name = models.CharField(max_length=100, unique=True) client = models.ForeignKey('Client', on_delete=models.RESTRICT) gp_code = models.CharField(max_length=13, primary_key=True) dispatch_conditions = models.TextField() elaboration = models.CharField(max_length=100) reviewer = models.CharField(max_length=100) def __str__(self): return self.product ------------------------------------------------------------------------------------ class Client (models.Model): name = models.CharField(max_length=100, unique=True) rif_num = models.CharField(max_length=10, primary_key=True) def __str__(self): return self.name views.py from django.db.models import Count from .models import * def indexClient(request): client_list = Client.objects.all() plans = Client.objects.annotate(num_plan = Count('plan')) template = loader.get_template('app/clients.html') context={'client_list':client_list, 'plans':plans} return HttpResponse(template.render(context, request)) template clients.html <table> <thead> <tr> <th>Client</th> <th >Plans</th> </tr> </thead> <tbody> {% for client in client_list %} <tr> <td>{{ client.name }}</td> <td>{{ plans.num_plan }}</td> </tr> {% endfor %} </tbody> </table> i tried to apply the methods said in this, this and this question but it didn't work for me or i'm applying the Count() incorrectly want the table to display just like... Client Plans Jhon 2 Mark 4 Louis 0 Vic 1 but currently the 'Plans' displays blank like this... Client Plans Jhon Mark Louis Vic -
How to access Foreign Key models attribute values into another model in Django?
I am trying to filter choices of models attribute based on its foreign key models attribute. parent_choices = [('fruits', 'fruits'), ('veggie', 'veggie')] dict_options = { 'fruits': [('apple', 'apple'), ('orange', 'orange')], 'veggie': [('carrot', 'carrot'), ('peas', 'peas')], } class Parent(models.Model): name = models.CharField(max_length=50) like_to_eat = models.CharField(max_length=20, choices=parent_choices) class Child(models.Model): name = models.CharField(max_length=50) parent = models.ForeignKey(Parent, on_delete=models.CASCADE) given_to_eat = models.CharField(max_length=20, choices=dict_options[parent.like_to_eat]) Error Message: AttributeError: 'ForeignKey' object has no attribute 'like_to_eat' -
(-2147024891, 'Access is denied.', None, None)
I am developing a Django (v 3.2.6) application (Python 3.9.1.) which needs to write into an Excel file using pywin32.com. On the client side it works fine, but when I put in production using IIS (v 10) on a Windows 11 server, I get the error above. I have a routine that reads in a file input by the user and writes to the project directory: if request.method == 'POST': # Create a form instance and populate it with the file from the request (binding): form = Name1_uploadForm(request.POST, request.FILES) if form.is_valid(): # Create variable for uploaded file uploaded_excel_file = form.cleaned_data['excel_file'] # Write it to BASE_DIR with open(os.path.join(settings.BASE_DIR, form.cleaned_data['excel_file'].name), 'wb+') as destination: for chunk in uploaded_excel_file.chunks(): destination.write(chunk) # Allow the write process to conclude time.sleep(12) # Close the file destination.close() # Call conversion function Name1_extraction(os.path.join(settings.BASE_DIR, form.cleaned_data['excel_file'].name)) # redirect to a new URL: return HttpResponseRedirect(reverse('index') ) else: form = Name1_uploadForm() This calls another function (below) that should open that same file: def Name1_extraction(uploaded_excel_file): const = win32.constants # Need to run CoInitialize to use win32com.client pythoncom.CoInitialize() # Open Name1 excel with Win32com excelFile = win32.gencache.EnsureDispatch('Excel.Application') The complete error is the following: enter image description here enter image description here enter image description here … -
I want to deploy django app on AWS EC2 using docker container with nginx, gunicorn. 502 Gateway error is happening [closed]
I make a docker container for Django-app. I tested it on my local host, and everything is working fine. I want to implement it on the AWS Linux server(EC2). Docker-compose-up is running successfully, but a 502 gateway error happens. Last time i had the same issue, but there was no docker container and i find out the problem was in nginix config. I added user "mylinuxname"; and it was working. Now i don't know how to update that config file, because i'm using container and when i add user "mylinuxusername" it is not working. output : "it is not place where u can use user settings". Anyone can help me or give me any references.enter image description hereenter image description here[enter image description here](https://i.stack.imgur.com/6S9ow.png) -
(Django) Why my login only work for db table:auth_user can't work another table:myapp_user?
Sorry bad English! I have a login function in my project like: from django.contrib.auth.forms import AuthenticationForm from django.contrib import auth from django.http import HttpResponseRedirect from django.shortcuts import render def log_in(request): form = AuthenticationForm(request.POST) if request.method == "POST": form = AuthenticationForm(data=request.POST) username = request.POST.get('username') password = request.POST.get('password') user = auth.authenticate(request,username=username,password=password) if user is not None and user.is_active: auth.login(request,user) return HttpResponseRedirect('/index') context = { 'form': form, } return render(request, 'login.html', context) This function can work for any accounts that save in database table:auth_user,but can't work for my define class User: from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class User(AbstractBaseUser): username = models.CharField(unique=True,max_length=20,default="") email = models.EmailField() date_of_birth = models.DateField() date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = AccountManager() USERNAME_FIELD = 'username' #類似主鍵的功用 REQUIRED_FIELDS = ['email','username'] #必填 def __str__(self): return self.email def is_staff(self): return self.is_admin def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return self.is_admin If I use register page to create a new account data,it will save in table:function_user("function" is my app name),and if my login table:auth_user accounts it will jump to /index,this right,but when I login new register account,it not do anything , I really sure the username and password is already created in table:function_user. … -
Django slice variable in template
I am trying to cut a slice a list of images to split them over a few pages of a pdf I am generating. But im not sure what the syntax I need to use is. (or if there is a better way). {% for page in image_pages %} // range loop for number of pages (passed from view) <p style="page-break-before: always"></p> // new page break for each page <div class="img-wrapper"> {% for image in project_images|slice:"0:12" %} <div class="img-box" style="margin: 5px"> <img class="report-img" src="{{ base_url }}{{ image.path.url }}" /> </div> {% endfor %} </div> {% endfor %} What i want to do is adjust this line {% for image in project_images|slice:"0:12" %} To something like (to print 12 images from total image list sent) {% for image in project_images|slice:"page*12:page*12+12" %} -
Continuous deployment of django react project
I have a react app with django backend. Every time when I need to deploy the app I have to follow following steps - Git pull new django code Copy react build from local to aws Collect static files using python manage.py collectstatic I have to automate this process using bare minimum dependencies. What can be done in such case? Thanks in Advance. -
How to use AdminEmailHandler class to send mails to admins with celery task in django?
I'm trying to send a mails to admins with celery by overriding the current AdminEmailHandler class of django from django.utils.log import AdminEmailHandler from celery import shared_task class CeleryAdminEmailHanadler(AdminEmailHandler): @shared_task(bind=True) def celery_send(self,subject, message, *args, **kwargs): super().send_mail(subject, message, *args, **kwargs) def send_mail(self, subject, message, *args, **kwargs): self.celery_send.delay(subject, message, *args, **kwargs) whenever celery_send function run the super().send_mail function getting this error Error('super(type, obj): obj must be an instance or subtype of type') Traceback (most recent call last): File "D:\cmms\env\lib\site-packages\celery\app\trace.py", line 451, in trace_task R = retval = fun(*args, **kwargs) File "D:\cmms\env\lib\site-packages\celery\app\trace.py", line 734, in __protected_call__ return self.run(*args, **kwargs) File "D:\cmms\core\utils\log.py", line 7, in celery_send super().send_mail(subject, message, *args, **kwargs) TypeError: super(type, obj): obj must be an instance or subtype of type I'm using this for logging purposes to send mail to admins on critical errors in the website with celery. -
How to get value by index in jinja2 list?
I am using plotly to make multiple graphs and django framework to present the graph to user. I am storing all the graphs in list, example: all_graphs=[graph1, graph2] I need to show only one graph at a time according to value selected in dropdown in HTML. I am using javascript and jinja2 element for the same. Below is my javascript code: ` function graphshow(s){ var id=Number(s[s.selectedIndex].id); var graph1 = {{ all_graphs.0 | safe}}; Plotly.plot('id_of_div_to_show_graph', graph1, {}); } ` The above code works perfectly but when i replace 0 in line 2 with 'id' which is the index value of graph to be shown the code doesn't work. The value stored in 'id' is correct i've already checked. -
Django using URL parameters in template
I need to redirect to another page with same url parameters so I don't understand how to use url parameters in current template to redirect. dborg.html: {% extends './frame.html' %} {% block content %} <a href="{% url 'create_user' {{orgtype}} {{deg}} %}">Создать нового пользователя</a> {% csrf_token %} {{form}} {% for i in o %} <p><a href='{% url "view_user" i.id %}'>{{i.fld}}</a></p> {% endfor %} {% endblock %} urls.py from django.urls import path from . import views urlpatterns = [ path('', views.main, name='main'), path('view_org/<str:orgtype>/<str:deg>', views.view_org_db, name='view_org'), path('token/<str:orgtype>/<str:deg>', views.get_token, name='token'), path('token/<str:orgtype>', views.get_token, name='token'), path('create/<str:orgtype>/<str:deg>', views.create_user, name='create_user'), path('search/', views.search_user, name='search_user'), path('report/', views.view_report, name='view_report'), path('view/<int:id>', views.view_user, name='view_user') ] -
How do I get a cloned Django project running?
When I do 'pip install -r requirements.txt', I get this message: python setup.py egg_info did not run successfully I tried python 'python3 -m pip install -U setuptools' but that didn't work. -
Django issue saving data to database
username is saving but information such as first_name, email and etc are not. `from django.contrib.auth.models import User from django.contrib.auth.password_validation import validate_password from rest_framework import serializers class RegisterSerializer(serializers.ModelSerializer): email = serializers.CharField(required=True) first_name = serializers.CharField(max_length=50, required=True) last_name = serializers.CharField(max_length=50, required=True) password = serializers.CharField( write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True, required=True) is_admin = serializers.BooleanField(default=False) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password', 'password2', 'is_admin') def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError( {"password": "Password fields didn't match."}) return attrs def create(self, validated_data): user = User.objects.create( username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user` i have searched online for hours, but have not managed to make much progress. if someone could elaborate on my issue and explain what I have done wrong that would be greatly appreciated