Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to List Categories with Dropdown in Django
I would like to add a dropdown menu to my Django project that lists all categories from the database. The challenge I'm facing is that while I can get the categories listed on a single page (category), I would like them to be accessible throughout the entire website. I would really appreciate if someone helps. Thanks in advance. views.py #dropdown list of categories class CategoryListView(View): template_name = 'media/categories_dropdown.html' def get(self, request, *args, **kwargs): categories = Category.objects.all() return render(request, self.template_name, {'categories': categories}) urls.py path('category/', CategoryListView.as_view(), name='category-list'), media/categories_dropdown.html {% for category in categories %} <option value="{{ category.slug }}">{{ category.name }}</option> {% endfor %} -
how to access files in Views.py in django
I want to use an image that is in static folder/data/m.tif but I can't access that. here is my screenshot from pycharm. enter image description here and here is error: enter image description here get image path to pass in other function -
How to better structure variations for Ecommerce site
I am working on an e-commerce application in Django. It allows for product variations. My first impulse has been to go with multi-table inheritance, where variants have their own table different from the main product table. Both of these inherit an abstract table, so they share common properties. Then in the frontend, implicitly place the main product as the first variation in the variation list. The thing I am struggling with deciding whether to duplicate main product as variant like in the Amazon custom implementations of variations, as shown in this image: The primary main product always seems to be the first expected product. But clicking on that, you see that the circled label(color) in the above image, also changes, in this case 01-black. My question is, is Amazon duplicating the main product as a variation too? Which means, it will have it's specific features like the color name. That would mean duplication. If in case then that Amazon is implicitly displaying the main product as the first variation, how come it has unique property values like the color name ````01-black``? -
Django TypeError: Field.__init__() got an unexpected keyword argument 'id'
model.py from django.db import models class User(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, null=True, default="") password = models.CharField(max_length=255) def __init__(self, name, password, *args, **kwargs): super().__init__(*args, **kwargs) self.id = id self.name = name self.password = password serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'name', 'password') def __init__(self, name, password, *args, **kwargs): super().__init__(*args, **kwargs) self.id = id self.name = name self.password = password views.py def find_user(request): if request.method == 'GET': data = json.loads(request.body) id = data['id'] user = User.objects.get(id=id) user_serializer = UserSerializer(id=user.id, name=user.name, password=user.password) return HttpResponse(user_serializer.data) Why TypeError: Field.init() got an unexpected keyword argument 'id' ? I tried a lot of things ㅠㅠ -
Django REST API login give server error if i set cookie
I'm currently working on a Django web application that involves user authentication. However, I've encountered an issue where the user's login information gets lost whenever I refresh the browser. To address this problem, I decided to implement cookie-based authentication to allow the browser to remember the user's login status. Despite my efforts, I'm facing difficulties in getting this functionality to work correctly. i changed my code this,, class CustomUserRegistrationView(APIView): permission_classes = (AllowAny,) def post(self, request): serializer = CustomUserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() refresh = RefreshToken.for_user(user) response_data = { 'refresh': str(refresh), 'access': str(refresh.access_token), 'message': 'User registered successfully.' } return Response(response_data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class CustomUserLoginView(APIView): permission_classes = (AllowAny,) def post(self, request): if request.user.is_authenticated: return Response({"message": "You are already logged in"}, status=status.HTTP_400_BAD_REQUEST) mobile_number = request.data.get('mobile_number') password = request.data.get('password') if mobile_number is None or password is None: return Response({'error': 'Please provide both mobile number and password'}, status=status.HTTP_400_BAD_REQUEST) try: user = CustomUser.objects.get(mobile_number=mobile_number) except CustomUser.DoesNotExist: return Response({'message': 'Invalid mobile number or password.'}, status=status.HTTP_401_UNAUTHORIZED) if not user.check_password(password): return Response({'message': 'Invalid mobile number or password.'}, status=status.HTTP_401_UNAUTHORIZED) serializer = CustomUserLoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = authenticate( mobile_number=serializer.validated_data['mobile_number'], password=serializer.validated_data['password'] ) if user is None: return Response({"error": "Invalid login credentials"}, status=status.HTTP_400_BAD_REQUEST) if not user.is_active: return Response({'error': 'User account is disabled'}, … -
AxiosError (Request failed with status code 400)
I have been following a React-Django tutorial. In addition to tutorial I was trying to store image using a post request via axios but getting a axios error 400. Iam trying to make a post request using an action Add_lead() in my reducers. This is my front-end. import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { addLead } from '../../actions/leads'; class Form extends Component { //initial state state = { name: '', email: '', message: '', gender: '', image: null, }; static propTypes = { addLead: PropTypes.func.isRequired, }; onChange = (e) => { if (e.target.name === 'image') { this.setState({ [e.target.name]: e.target.files[0] }); // Handle file input } else { this.setState({ [e.target.name]: e.target.value }); } }; onSubmit = (e) => { e.preventDefault(); const { name, email, message, gender, image } = this.state; const lead = { name, email, message, gender, image }; this.props.addLead(lead); this.setState({ name: '', email: '', message: '', gender: '', image: null, }); alert('Form submitted.'); }; render(){ const { name, email, message, gender, image } = this.state; return ( <div className="card card-body mt-4 mb-4"> <h2>Add Lead</h2> <form onSubmit={this.onSubmit} encType="multipart/form-data"> <div className="form-group"> <label>Name</label> <input className="form-control" type="text" name="name" onChange={this.onChange} value={name} required … -
How a child serializer can access a respective field value from its parent serializer initalized with many=True?
In case we want to initialize the parent serializer with many=True, then how can the child serializer can access a respective field value from its parent serializer? class ChildSerializer(serializers.Serializer): field1 = serializers.CharField() def validate(self, data): # How to get the value of batch_key from the parent serializer (here self.batch_key)? if not self.batch_key == data['field1']: raise serializers.ValidationError('invalid field1') return data class ParentSerializer(serializers.Serializer): child = ChildSerializer(many=True) batch_key = serializers.CharField() class MyAPIView(APIView): def post(self, request): serializer = ParentSerializer(data=request.data, many=True) serializer.is_valid(raise_exception=True) return request data is as follows: [ { "batch_key":"batch_key_value_1", "child":[ { "field1":"value1" }, { "field1":"value2" }, { "field1":"value3" } ] }, { "batch_key":"batch_key_value_2", "child":[ { "field1":"value4" }, { "field1":"value5" }, { "field1":"value6" } ] } ] -
Nginx returns html instead of json in Django
I'm trying to deploy an Angluar and Django web site on an Nginx server. The frontend works properly, but when i make a call to the backend, Django returns me an html response instead of a json response. I searched online, but i can't came out with a solution. This is the nginx configuration: server { server_name sub.domain.net www.sub.domain.net; root /var/www/projectfolder/frontend; index index.html; # Handles proxying to Angular App location / { add_header Access-Control-Allow-Origin *; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'Access-Control-Allow-Origin, XMLHttpRequest, Accept, Authorization, Cache-Control, Content-Type, DNT, If-Modified-Since, Keep-Alive, Origin, User-Agent, X-Mx-ReqToken, X-Requested-With'; try_files $uri $uri/ /index.html; } # Handles proxying to Django API location ~* /api { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_http_version 1.1; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/sub.domain.net/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/sub.domain.net/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } This is the Django code: def get(self, request, format=None): news = News.objects.all().values().order_by('-date') return Response(news) To this endpoint: /getnews/ The server response is: Accept-Ranges: bytes Access-Control-Allow-Credentials: true Access-Control-Allow-Headers: Access-Control-Allow-Origin, XMLHttpRequest, Accept, Authorization, Cache-Control, Content-Type, DNT, If-Modified-Since, Keep-Alive, Origin, User-Agent, X-Mx-ReqToken, … -
Google Cloud Run Gunicorn Multi-Threaded Django Request Blocked on Cold Start
I have a Django application deployed on Google Cloud Run using a Gunicorn server. There is a daily task triggered by Google Cloud Scheduler. The task job involves patching a Microsoft subscription. For this patch to complete successfully, Microsoft makes a call to another API endpoint on the same Django application to validate a token. The Gunicorn server is running with multiple threads. When the task is triggered and the container has a cold start, the validation request is blocked, the patch request fails and the container only responds to it after the patch failure. However, if the container is warm, the task completes successfully and the additional thread is able to respond to the validation check. Any idea why this is occurring and how it can be addressed? This was working previously but started encountering this error in recent weeks. Have tried setting multiple workers and more threads on the Gunicorn server as well as enabling CPU boost on Cloud Run but neither of these worked. -
Is It Possible with Python creating Remote Control Desktop Which will work On Different Network?
There are online resources, GitHub repositories, and YouTube videos that can guide you in controlling a desktop (including screen sharing, system access, and interaction with different software) within the same network. However, is it feasible to use Python for controlling a desktop that is not on the same network, while minimizing networking adjustments? This implies achieving the goal without resorting to actions like port forwarding, firewall configuration, or the use of a VPN etc. Please share any insights. Thanks. -
Setup a Django in Anaconda environment
I am trying to setup a Django in Anaconda environment. I have created a new environment with the name Django2. After that, I was stuck, unable to move on. What are the actions that should be taken? Please offer some suggestions. enter image description here -
Conditional form according to choice of dropdown list
I need a form to be displayed depending on the option chosen in the dropdown list, which will be selected by the administrator when creating the new candidate. However, the problem is that even if you select any option in the dropdown list, form 2 corresponding to the else of the conditional is displayed. help please. models.py: Here the model is defined as well as functions to be able to rename the files when saving them cc= ( ('1','Quebrada Blanca'), ('2','Lo Pinto'), ('3','Oficina Central'), ('4','Carbonato'), ('5','Toconao'), ('6','Centinela'), ('7','Spence'), ('8','La Negra'), def create_path(instance, filename, file_type): ext = filename.split('.')[-1] new_filename = "DSR_%s_%s_%s_0.%s" % (instance.rut, instance.nombre, file_type, ext) return os.path.join('uploads',new_filename) def imagen_upload_path(instance, filename): return create_path(instance, filename, 'imagen') def certificado_antecedentes_upload_path(instance, filename): return create_path(instance, filename, 'certificado_antecedentes') def hoja_de_vida_conductor_upload_path(instance, filename): return create_path(instance, filename, 'hoja_de_vida_conductor') def certificado_residencia_upload_path(instance, filename): return create_path(instance, filename, 'certificado_residencia') def certificado_afiliacion_afp_upload_path(instance, filename): return create_path(instance, filename, 'certificado_afiliacion_afp') def certificado_afiliacion_salud_upload_path(instance, filename): return create_path(instance, filename, 'certificado_afiliacion_salud') def fotocopia_cedula_identidad_upload_path(instance, filename): return create_path(instance, filename, 'fotocopia_cedula_identidad') def fotocopia_licencia_conducir_upload_path(instance, filename): return create_path(instance, filename, 'fotocopia_licencia_conducir') class Candidato(models.Model): nombre = models.CharField(max_length = 70, null=True, blank=True) rut = models.CharField(max_length = 10, primary_key=True) correo = models.EmailField(null=True, blank=True) centro_de_costo =models.CharField(null=True, blank=True, max_length =30, choices = cc) estado = models.IntegerField(null=True, blank=True) imagen = models.ImageField(upload_to=imagen_upload_path, null=True, blank=True) certificado_antecedentes … -
update the 'div' after ajax request
This is my first project in django. I'm new to Django, ajax, javascript. I have to send the data to jinja template after making ajax request. My index.html is {% if data %} <p>{{data.title}}</p> <p>{{data.price}}</p> {% endif %} My javascript is <script> $.ajax({ type: "POST", url: "/", // Replace with the actual URL of your view data: { input_value: "test", csrfmiddlewaretoken: "{{ csrf_token }}" }, success: function(response) { title = response // after request, response be like { "data" : {"title":"t1", "price":20} } }, error: function() { console.log("Error") } }); <script> I don't know this is possible. Some using element.innerHTML to update, but i need to send to jinja format. Thanks -
How to get a value from the context dictionary without looping through it
I have to list the products belonging to a particular category and also above the products I want to display the name of the category (only once). I can get the name of category when iterating over products but I want to display it only once on the top. My models are follwing: class category(models.Model): title = models.CharField(max_length=30) image = models.ImageField(null=True, blank=True) def __str__(self): return self.title class product(models.Model): name = models.CharField(max_length=50, null=True, blank=True) slug = models.SlugField(null=True, blank=True) description = models.TextField(max_length=500,null=True, blank=True ) category = models.ForeignKey(category, on_delete=models.CASCADE) cost = models.PositiveIntegerField() image = models.ImageField(null=True, blank=True) def save(self, *args, **kwargs): # new self.slug = slugify(self.name) return super().save(*args, **kwargs) def __str__(self): return self.name and the view is: class ProductsListView(ListView): model = product template_name = 'products/productList.html' context_object_name = 'products' def get_queryset(self, *args, **kwargs): return ( super() .get_queryset(*args, **kwargs) .filter(category_id=self.kwargs['cat_id']) ) template code: {% extends 'products/base.html' %} {% load static %} {% block content %} <h1>Product PAGE!!</h1> <!-- I want to display the category name here --> {% for product in products %} <img src="{{ product.image.url }}" alt="{{ product.name }}" width="10%"> <h2>{{product.name}} </h2> <h2>{{product.cost}} </h2> <h2>{{product.description}} </h2> {% endfor %} {% endblock %} I tried it using the key method "products[category] but it doesn't work. -
What is the Bettery way Django Tags with DRF
I'm developing a Blog project with Django. I have thoughts on 'tag'. What should be the best approach? What I want is a tag system like here(stackoverflow) class Post(models.Model): title = subtitle = category = FK author = FK content = tags = ManyToMany class Tag(models.Model): name = slug = -
How to organize containers if they use each other?
I use the dependency injection method in my Django web-application. I have a containers.py file with 3 instances of containers.DeclarativeContainer: BoardContainer, ColumnContainer and LabelContainer. Each of containers has repository layer, service layer and interactor layer. class BoardContainer(containers.DeclarativeContainer): repository = providers.Factory(BoardRepository, converter=ConvertorsContainer.from_queryset_to_dto) service = providers.Factory(BoardService, repository=repository) interactor = providers.Factory(BoardInteractor, service=service) class ColumnContainer(containers.DeclarativeContainer): repository = providers.Factory(ColumnRepository, converter=ConvertorsContainer.from_queryset_to_dto) service = providers.Factory(ColumnService, repository=repository) interactor = providers.Factory(ColumnInteractor, service=service, board_service=BoardContainer.service) class LabelContainer(containers.DeclarativeContainer): repository = providers.Factory(LabelRepository, converter=ConvertorsContainer.from_queryset_to_dto) service = providers.Factory(LabelService, repository=repository) interactor = providers.Factory(LabelInteractor, service=service, board_service=BoardContainer.service) But i need to use LabelContainer.service and ColumnContainer.service in BoardContainer.interactor. And it turns out that a two-way dependency is created. So far I have solved this problem in this definitely a bad way: class ColumnContainer(containers.DeclarativeContainer): repository = providers.Factory(ColumnRepository, converter=ConvertorsContainer.from_queryset_to_dto) service = providers.Factory(ColumnService, repository=repository) interactor = providers.Factory(ColumnInteractor, service=service) # without board_service class LabelContainer(containers.DeclarativeContainer): repository = providers.Factory(LabelRepository, converter=ConvertorsContainer.from_queryset_to_dto) service = providers.Factory(LabelService, repository=repository) interactor = providers.Factory(LabelInteractor, service=service) # without board_service class BoardContainer(containers.DeclarativeContainer): repository = providers.Factory(BoardRepository, converter=ConvertorsContainer.from_queryset_to_dto) service = providers.Factory(BoardService, repository=repository) interactor = providers.Factory(BoardInteractor, service=service, column_service=ColumnContainer.service, label_service=LabelContainer.service) class ColumnContainer(containers.DeclarativeContainer): repository = providers.Factory(ColumnRepository, converter=ConvertorsContainer.from_queryset_to_dto) service = providers.Factory(ColumnService, repository=repository) interactor = providers.Factory(ColumnInteractor, service=service, board_service=BoardContainer.service) class LabelContainer(containers.DeclarativeContainer): repository = providers.Factory(LabelRepository, converter=ConvertorsContainer.from_queryset_to_dto) service = providers.Factory(LabelService, repository=repository) interactor = providers.Factory(LabelInteractor, service=service, board_service=BoardContainer.service) How i should fix this problem? -
How to handle timezones in FCM
I'm in the process of developing an API backend using Django Rest Framework. Currently, I have a requirement to send notifications to mobile devices, which I've implemented using FCM (Firebase Cloud Messaging). However, I'm facing an issue: I need to send notifications at specific times according to different timezones, and I have access to the timezones of each user. I'm considering implementing a cron job to check if the designated time has arrived. Is this approach ideal for my requirements? -
How to call celery task in Django from Fastapi app
I have two apps (Django and FastApi) that use Celery to do some background task. Now, I need to communicate the two applications and I have thought about reusing the queues that celery uses (I don't really know if it is the best way to do it).The two apps are using the same broker and all are in Docker containers. I wolud like to execute a task that is in the django app when calling a route in the FastApi app. Django app celery.py app = Celery("app_1") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) settings.py ... CELERY_TASK_DEFAULT_QUEUE = "app_1" CELERY_TASK_CREATE_MISSING_QUEUES = False CELERY_TASK_QUEUES = ( Queue("default"), Queue("app_1"), ) def route_task(name, args, kwargs, options, task=None, **kw): if ":" in name: queue, _ = name.split(":") return {"queue": queue} return {"queue": "default"} CELERY_TASK_ROUTES = (route_task,) ... tasks.py @shared_task( name="app_1:test", bind=True, base=BaseTaskRetry ) def test() -> None: print('Result') FastApi app create_celery.py def create_celery(): celery_app = Celery("app_2") celery_app.config_from_object(settings, namespace="CELERY") celery_app.autodiscover_tasks(["Infraestructure.Celery.tasks"]) return celery_app celery_app = create_celery() config_celery.py (In this case I have tried without defining the django exchange and defining it, but I've got the same result) ... django_exchange = Exchange('app_1', type='direct') settings = { ... 'CELERY_TASK_DEFAULT_QUEUE' : "app_2", 'CELERY_TASK_CREATE_MISSING_QUEUES' : False, 'CELERY_TASK_QUEUES' : ( Queue("app_2"), Queue('app_1', exchange=django_exchange), ), … -
Django: Configuration for serving static files on IIS server
I have a django application deployed on an AWS IIS server. Static fils are served just fine via 'runserver', but not via the IIS server. I have done everything right but it doesn't work. i even tried adding a static folder virtual directory but it didnt work. this is my webconfig: <?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <!-- Required settings --> <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()" /> <!-- Your django path --> <add key="PYTHONPATH" value="C:\myvenv2\NutMIS" /> <!-- Your djangoname.settings --> <add key="DJANGO_SETTINGS_MODULE" value="NutMIS.settings" /> </appSettings> <system.webServer> <handlers> <!-- Remove duplicate entries --> <remove name="NutMIS" /> <remove name="StaticFiles" /> <remove name="StaticFile" /> <!-- Add handler for StaticFiles --> <add name="StaticFile" path="*" verb="*" modules="StaticFileModule" resourceType="Unspecified" requireAccess="Read" /> <!-- Add your custom NutMIS handler --> <add name="NutMIS" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Users\Administrator\AppData\Local\Programs\Python\Python311\python.exe|C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> <staticContent> <mimeMap fileExtension=".*" mimeType="application/octet-stream" /> </staticContent> </system.webServer> </configuration> this is my settings: STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / "static" The static files feature is installed in my IIS. My 'static' folder is placed in the app folder and it works just fine via runserver but not via the public IP over IIS. Please i need help with this. i also tried adding this web.config to to my static file folder … -
Python Django Framework - How to make up ownername and password in Models as login authentication?
This is my class models. I wish to use the ownername and vehicle_password in class Vehicle for owner login. #this is my models.py. class AbstractOwnerInfo(models.Model): ownername = models.CharField(max_length=100) vehicle_password = models.CharField(max_length=100) class Meta: abstract = True #this is my class Vehicle. class Vehicle(models.Model): id = models.AutoField(primary_key=True) parkingnumber = models.CharField(max_length=20) ownercontact = models.CharField(max_length=100) ownername = models.CharField(max_length=100) vehicle_password = models.CharField(max_length=100) IC = models.CharField(max_length=14) regno = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) vehiclecompany = models.CharField(max_length=50) pdate = models.DateField() intime = models.CharField(max_length=50, default='default_value') outtime = models.CharField(max_length=50) parkingcharge = models.CharField(max_length=50) remark = models.CharField(max_length=500) status = models.CharField(max_length=20) def __str__(self): return self.parkingnumber And then I defined the classess, I wish to use the ownername and vehicle_password in class Vehicles as login credentials. This is my defined member_login request and member_home request. def member_login(request): if request.method == 'POST': ownername = request.POST.get('ownername') password = request.POST.get('vehicle_password') if ownername and password: user = authenticate(username=ownername, password=password) if user is not None: login(request, user) messages.success(request, "Logged in successfully.") return redirect('member_home') else: messages.error(request, "Invalid login credentials. Please try again.") return render(request, 'member_login.html') def member_home(request): return render(request, 'member_home.html') And this is my member_login.html page. {% csrf_token %} <label for="ownername"><b>Ownername</b></label> <input type="text" name="ownername" class="form-control" required> <label for="vehicle_password"><b>Password</b></label> <input type="password" name="vehicle_password" class="form-control" required> <br> <input type="submit" value="Login" class="btn … -
AttributeError: 'NoneType' object has no attribute 'cursor'
I have a code that populates data to DB every time I run a script and this data gets displayed on a webpage. But I'm getting the error as : File "/xyz/dept/triangulation/work_dir/db.py", line 124, in populateSpecificRecord cur = conn.cursor() AttributeError: 'NoneType' object has no attribute 'cursor' def populateSpecificRecord(self, jobid, runid, run_label, table_name, input_dict): """Populate database where jobid and runid both exists""" if bool(input_dict) == True: inputStrList = [] logging.debug(f'Updating to db jobid {jobid}, runlabel {run_label}') for key in input_dict: elem = f"{key}='{input_dict[key]}'" inputStrList.append(elem) inputStr = ','.join(inputStrList) sql = f"UPDATE {table_name} SET {inputStr} WHERE jobid='{jobid}' AND runid={runid} AND pca_run_label='{run_label}'" conn = self.createConnection() cur = conn.cursor() cur.execute(sql) cur.close() conn.commit() conn.close() else: print("Inputed dictionary with no data, DB not updated") How to resolve this issue? I just need that it should populate each Record in the database. -
IntegrityError at /add_emp FOREIGN KEY constraint failed Django problem
while adding a user data in db through a form i create i got this error intergrityerror at \add_emp and it says foreign key constraint failed i tried delete dbsqlite3 files pycache files but that didnt work plzz tell where i am wrong its my first time getting this error. **This is Models.py code ** from django.db import models # Create your models here. class Department(models.Model): name = models.CharField(max_length=100,null=True) location = models.CharField(max_length=100) def __str__(self): return self.name class Role(models.Model): name = models.CharField(max_length=100, null=True) def __str__(self): return self.name class Employee(models.Model): first_name = models.CharField(max_length=100, null=False) last_name = models.CharField(max_length=100,null=True) dept = models.ForeignKey(Department, on_delete=models.CASCADE) salary = models.IntegerField(default=0,null=True) bonus = models.IntegerField(default=0,null=True) role = models.ForeignKey(Role, on_delete=models.CASCADE) phone = models.IntegerField(default=0,null=True) hire_date = models.DateField(null=True) def __str__(self): return "%s %s %s" %(self.first_name, self.last_name, self.phone) **Thats views.py code ** from django.shortcuts import render,HttpResponse from .models import* from datetime import datetime # Create your views here. def index (request): return render(request,"index.html") def all_emp (request): context={"emps":Employee.objects.all(),"roles":Role.objects.all(),"departments":Department.objects.all()} return render(request,"all_emp.html",context) def add_emp(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] salary = int(request.POST['salary']) bonus = int(request.POST['bonus']) phone = int(request.POST['phone']) dept = int(request.POST['dept']) role = int(request.POST['role']) new_emp = Employee(first_name= first_name, last_name=last_name, salary=salary, bonus=bonus, phone=phone, dept_id=dept,role_id=role,hire_date = datetime.now()) new_emp.save() return HttpResponse ("Employee added sucessfully") elif … -
Django register form validation for javascript
In django i followed form method is model form i not validate in backend only validate frontend using javascript but if click the submit button the data is not store to database how to fix I tried to submit the data in database but if I click data is validate but not store to database -
Forget Password using Email Django Send Email
I am working on the function of forgetting password then sending email to user to retrieve password using Django programming language. I have the following problem: When I run the server, it shows the link (1) and then I click send email, it shows the link (3) and I check the mail, it doesn't send an email forgot the password to the user even though the system says it has been sent successful email. Please help me. It took me 2 days to fix this function. I hope to be able to send forgotten password emails to users in Django. It took me a total of 2 days to work over and over again, but the result was that I couldn't do it. Very butt get help from everyone. I would like to thank all of you for helping me -
How to make Django Rest Framework Serializers to work different with GET and POST request
Actually, I have am creating the API for Bookmark manager, where I will be having CRUD operations on Bookmark, Collection and Tags Here I am using the BookmarkSerializer for serialization, class BookmarkSerializer(serializers.ModelSerializer): class Meta: model = Bookmark fields = "__all__" def create(self, validated_data): tags_data = validated_data.pop('tags', []) bookmark = Bookmark.objects.create(**validated_data) for tag_data in tags_data: bookmark.tags.add(tag_data) return bookmark and Bookmark model is like class Bookmark(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) url = models.URLField() thumbnail_url = models.URLField(blank=True, default="https://site.image.jpg") title = models.CharField(max_length=512, blank=True) description = models.TextField(blank=True) note = models.TextField(blank=True) tags = models.ManyToManyField("Tag", blank=True) is_favorite = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) collection = models.ForeignKey("Collection", on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.title My requirement is that, when GET request comes in I will return all information, and when POST request comes in I will create the new instance of Bookmark model. Here everything works well, but in the response the primary keys (id) of user, tags and collections are sent, which I don't want. I want it to be string representation. Like { "id": 1, "url": "https://www.flipkart.com/", "title": "Exiting website", "description": "", "note": "Shopping website", "is_favorite": false, "created_at": "2023-08-14T20:41:32.033584Z", "user": "john2000", "collection": "Shopping", "tags": [ "buy", "great_ui"] } but result's are, { "id": 1, "url": "https://www.flipkart.com/", "title": …