Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Multi-Model Inheritance
I have a custom User-Model Inheriting from AbstractUser. Everything worked fine, but then I tried to inherit from another Model aswell, allowing Soft-Deletion: from django.db import models from django.db.models.query import QuerySet from django.utils import timezone class SoftDeletionQuerySet(QuerySet): def delete(self): return super(SoftDeletionQuerySet, self).update(deleted_at=timezone.now()) def revive(self): return super(SoftDeletionQuerySet, self).update(deleted_at=None) def hard_delete(self): return super(SoftDeletionQuerySet, self).delete() def alive(self): return self.filter(deleted_at=None) def dead(self): return self.exclude(deleted_at=None) class SoftDeletionManager(models.Manager): use_for_related_fields = True def __init__(self, *args, **kwargs): self.status = kwargs.pop("status", "all") super(SoftDeletionManager, self).__init__(*args, **kwargs) def alive(self): return SoftDeletionQuerySet(self.model).filter(deleted_at=None) def dead(self): return SoftDeletionQuerySet(self.model).exclude(deleted_at=None) def get_queryset(self): if self.status == "alive": print("TEST") return SoftDeletionQuerySet(self.model).filter(deleted_at=None) elif self.status == "dead": return SoftDeletionQuerySet(self.model).exclude(deleted_at=None) else: return SoftDeletionQuerySet(self.model) def hard_delete(self): return self.get_queryset().hard_delete() class SoftDeletionModel(models.Model): deleted_at = models.DateTimeField(blank=True, null=True) objects = SoftDeletionManager(status="alive") dead_objects = SoftDeletionManager(status="dead") all_objects = SoftDeletionManager() class Meta: abstract = True def delete(self): self.deleted_at = timezone.now() self.save() def revive(self): self.deleted_at = None self.save() def hard_delete(self): super(SoftDeletionModel, self).delete() The Model: class User(AbstractUser, SoftDeletionModel): email = models.EmailField(unique=True) email_confir med = models.BooleanField(default=False) The View: User.dead_objects.filter(deleted_at_`_gte=(now - timezone.timedelta(hours=US_EXP_DATE))).hard_delete()` But now, from a View, I cant access the hard-delete function from a given User-Queryset (see The View). It gives the following Error: AttributeError: 'QuerySet' object has no attribute 'hard_delete' I guess the BaseUser is somehow shadowing it, since the Soft-Delete-Model … -
django fixtures with default value in
Can I use default value in django fixtures? I want to change primary_key to uuid_key class hogeModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) name = models.CharField(max_length=256) [ { "model": "app.hogeModel", "pk": "", "fields": { "name": "hogehoge" } } ] It's hard to make uuid every time. Can't I fixtures without making a primary_key? Waiting for your answer!! -
Is the server running on host "localhost" Djanog and PostgreSQL Connection?
I am trying to run migrate command in Django on MAC. python3 manage.py migrate But, I stuck in an error. The error says : Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? I am using PgAdmin4 and it is running on the web. I downloaded the postgresql and pgadmin4 and installed it. 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'dj_learning', 'USER': 'postgres', 'PASSWORD': '1234', 'HOST': 'localhost', 'PORT': '5432', } -
Python Django login URLS and Views - Security Approach
I have this login practice in my app, it's up and running but my concerns goes to securing this login approach. My App URLS: urlpatterns = [ path('', views.index, name='index'), path('accounts/login/', views.login_view, name='login'), path('logout/', views.logout_view, name='logout'), path('dashboard/', views.dashboard, name='dashboard'), ] My App Views: def index(request): if not request.user: return redirect(login_view) return redirect(dashboard) def login_view(request): form = LoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(request, username=username, password=password) login(request, user) if request.GET.get('next'): return redirect(request.GET.get('next')) return redirect(dashboard) context = { 'form': form, } return render(request, 'index.html', context) def logout_view(request): logout(request) return redirect(index) in my views.py index(request), I believe it may be vulnerable because if someone could make it and change the request and set a fake user it may go through ?. I know security concepts but not expert on Django appliance approaches. Is there a better way to do this or I don't have to change this and it's secured practice already? -
django-rules: trouble making it work as expected in templates
Disclaimer: I'm new to django and django-rules. I have defined my model. The Model has 2 foreign keys to the user table. Creator and supervisor. Instances should be changeable/updated by staff, creator or supervisor. I have defined predicates for is_creator and is_supervisor and made a rule: @rules.predicate def is_creator(user, mymodel): return mymodel.creator == user @rules.predicate def is_supervisor(user, mymodel): return mymodel.supervisor == user can_edit = is_supervisor | is_creator | rules.is_staff And in the models meta class I added: rules_permissions = { 'change': can_edit } In my view I then want to show an edit button that links to edit form based on these permissions. {% block content %} {% has_perm 'mymodel.change_mymodel' user instance as can_edit %} {% if can_edit %} <button type="button" class="btn btn-warning"><h6>Edit</h6></button> {% endif %} {% endblock %} When I log in as superuser, the button is displayed as expected. When I user a test user that should be able to edit a specific instance, the button is not displayed at all. So there are certain checks made but not as expected. I have a second similar functionality for the index page. Showing only actions the users has the privilege for. Again, the superuser sees it all but the … -
Celery revoked task still executes
I am trying to cancel/revoke a task planned with apply_async. Once I revoke it using the revoke function (revoke(celery_task_id)) celery shows me that the task has been flagged as revoked [2020-04-02 17:37:06,131: INFO/MainProcess] Tasks flagged as revoked: 5bca7db0-8d35-43f0-a900-6c8d94787265 However the task only gets discarded if the eta time has passed. If I restart my celery worker before that time the task is, strangely enough, not seen as revoked anymore and still executes at the specified eta time. When I restart it, celery says that it received a task, which is the task I revoked. [2020-04-02 17:39:47,077: INFO/MainProcess] Received task: testproject.taskapp.celery_tasks.celery_test[5bca7db0-8d35-43f0-a900-6c8d94787265] eta:[2020-04-02 17:42:56.206297+02:00] For the queue I use redis 2.10.5 the celery version is 3.1.25 does anyone know what is going wrong here and how I can get revoked tasks to not be executed? -
How to display an uploaded image manipulated with PIL without saving to file Django
I am pulling a image from a database to be used as a background and placing a user uploaded image on top of the background using PIL. I would like to display this image to the html page after the transformation is complete without saving to the file system. I have looked at many similar questions, but I am doing something different here. I have tried to craft some code based on the other answers, but I can't get the image to display on the screen after the user submits their photo. How can I get this to work? Here is my code: from django.core.files.storage import FileSystemStorage from PIL import Image from io import BytesIO import base64 import io from .models import Samplecards def imageUpload(request): if request.method == 'POST': selection = request.POST['selection'] sample = getImage() theImage = io.BytesIO(sample.image) print("DONE") uploaded_image = request.FILES['img'] foreground = Image.open(uploaded_image).convert("RGBA") background = Image.open(theImage).convert("RGBA") background.paste(foreground, (440, 190), foreground) buffered = BytesIO() background.save(buffered, format="png") b64_img = base64.b64encode(buffered.getvalue()) return render(request, 'uploadpage.html', {"image": b64_img}) def getImage(): img = Samplecards.objects.get(image_id=1) return img In my html file, I try to display the image like this: <img src="data:image/png;base64,{{image}}"> -
CSS not working while in deployment in django
This is my file structure Project asgi.py . . . main admin.py . . static css files templates users admin.py . . static files static (created after collectstatic) db.sqlite3 manage.py Static url and root STATIC_URL = "/STATIC/" STATIC_ROOT = OS.PATH.JOIN(BASE_DIR, 'static') I did collectstatic and it works properly all files are coped to /static/ folder now this all works fine with running with debug = true but when I set debug false none of the css loads. example of a css in html <link rel="stylesheet" href="{% static 'main/style.css' %}"> this is happening only with any templates inside "main" app, for "users" app all the css is loading properly -
Django Apache 2.4.18 Ubuntu 403
I am trying to configure my django app with Apache 2.4.18.. I am using Django 3.0.5 and Python 3.8.2., on Ubunu 16.04. Everything works fine in runserver mode. Forbidden You don't have permission to access this resource. This is my apache config gile Listen 80 <VirtualHost *:80> ServerAdmin xxx@xxx.com ServerName servername.net DocumentRoot /srv Alias /static /srv/tacdb/mysite/static <Directory "srv/tacdb/mysite/static"> Require all granted </Directory> Alias /media /srv/tacdb/mysite/media <Directory "srv/tacdb/mysite/media"> Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/portal_error.log CustomLog ${APACHE_LOG_DIR}/portal_access.log combined WSGIDaemonProcess mysite python-home=/srv/tacdb/virtualenvironment/project_1 python-path=/srv/tacdb WSGIProcessGroup mysite WSGIScriptAlias / /srv/tacdb/mysite/wsgi.py <Directory /srv/tacdb/mysite> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> configtest is ok and server status is ok. root@test-tools:~/srv# systemctl status apache2.service ● apache2.service - LSB: Apache2 web server Loaded: loaded (/etc/init.d/apache2; bad; vendor preset: enabled) Drop-In: /lib/systemd/system/apache2.service.d └─apache2-systemd.conf Active: active (running) since Thu 2020-04-02 15:18:20 UTC; 5min ago Docs: man:systemd-sysv-generator(8) Process: 26327 ExecStop=/etc/init.d/apache2 stop (code=exited, status=0/SUCCESS) Process: 25036 ExecReload=/etc/init.d/apache2 reload (code=exited, status=0/SUCCESS) Process: 26356 ExecStart=/etc/init.d/apache2 start (code=exited, status=0/SUCCESS) CGroup: /system.slice/apache2.service ├─26372 /usr/sbin/apache2 -k start ├─26375 /usr/sbin/apache2 -k start ├─26376 /usr/sbin/apache2 -k start └─26377 /usr/sbin/apache2 -k start Apr 02 15:18:19 test-tools systemd[1]: Stopped LSB: Apache2 web server. Apr 02 15:18:19 test-tools systemd[1]: Starting LSB: Apache2 web server... Apr 02 15:18:19 test-tools apache2[26356]: * Starting Apache … -
SQL Lite to PostgreSQL migration ERROR Django 3.0
Situation I am guessing that the problem relates to that I may have incorrectly altered my SQL lite database to PostgreSQL. After the migration I have cutted out my Login fully and created and used a simple register and login. But than I brought back the whole app where I have written the sql lite. Previously I did not asked for the user to give email address as well and now in the new version I do. Registration and login works because if I log in that is when I get the error message otherwise works. Homepage also works perfectly even if I am logged in. ERRORS localenvironmenthome/accounts Confirm Form ResubmissionThis webpage requires data that you entered earlier in order to be properly displayed. You can send this data again, but by doing so you will repeat any action this page previously performed. Press the reload button to resubmit the data needed to load the page. ERR_CACHE_MISS Than after the reload localenvironmenthome/accounts gave the following error message ValueError at /accounts/ The view accounts.decorators.wrapper_function didn't return an HttpResponse object. It returned None instead. Request Method: GET Request URL: http://localhost/accounts/ Django Version: 3.0 Exception Type: ValueError Exception Value: The view accounts.decorators.wrapper_function didn't … -
SessionId cookie not set on Chrome (Django App)
I am having problems accessing some third-party cookies on Chrome. Chrome version is 80.0.3987.100 (Official Build) (64-bit) and I suppose this already have the new implementation of SameSite cookies set to Lax. However, in the Django settings I have added the following: SESSION_COOKIE_SECURE = True SESSION_COOKIE_SAMESITE = None CSRF_COOKIE_SAMESITE = None with no luck. You can see there are no Cookies in the Request header above I have tried the request I am having troubles executing from Chrome on Postman. I get exactly the same result until I pass Cookie: sessionid: <some_id>. It probably is worth mentioning that this whole things works with no problems on Firefox (where I can see the Cookie set properly in the request Headers). If anyone has any ideas it would be greatly appreciated. -
Publish Django project with gunicorn and NGINX
Im trying to publish my Django project with NGINX and gunicorn, but I get permission denied from gunicorn. My last steps what I did. mkdir /home/sama/websites cd /home/sama/websites mkdir test_project cd test_project create Virtualenvirement for this project virtualenv --python=/usr/bin/python3.8 venv Virtualenvirement activate source venv/bin/activate Gunicorn & Django install pip3 install gunicorn pip3 install django create project cd .. django-admin startproject config test_project allow firewall to port 8000 sudo ufw allow 8000 run first test python manage.py runserver 0.0.0.0:8000 open my server ip on webbrowser myIP:8000 I can see Django basic page stop server CTRL + C testGunicorn gunicorn --bind 0.0.0.0:8000 config.wsgi testagain on webbrowser Again I can see Djangos page Server stop CTRL + C exit virtualenvirement deactivate config Gunicorn create 2 files in /etc/systemd/system/ gunicorn.socket and gunicorn.service edit this files sudo nano /etc/systemd/system/gunicorn_test_project.socket /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn daemon [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sama Group=www-data WorkingDirectory=/home/sama/websites/test_project ExecStart=/home/sama/websites/test_project/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock config.wsgi:application [Install] WantedBy=multi-user.target test socket sudo systemctl start gunicorn.socket sudo systemctl enable gunicorn.socket systemlink created, check it file /run/gunicorn.sock Output: /run/gunicorn.sock: socket curl --unix-socket /run/gunicorn.sock localhost And now I get permission denied I already set permission for the folder test_project to … -
How to retrieve data from a form in Django
I am working on a weather app where the client will be entering the name of the city in a search bar, and the name will be used to gain weather data from an API. To get the name of the city from the form, I have created this condition in view: if request.method == 'POST': city = request.data print(city) however when being printed, this error occurs: 'WSGIRequest' object has no attribute 'data' What am I doing wrong? Or is there a completely different way to do this? Edit: I have added the code suggested, by using the name. Now i get the data obtained as 'None' Here is the form: <form method="POST" name="data">{% csrf_token %} <div class="field has-addons"> <div class="control is-expanded"> <input class="input" type="text" placeholder="City Name"> </div> <div class="control"> <button class="button is-info" type="submit"> Search City </button> </div> </div> </form> -
how to disable password after inheriting AbstractUser to make a custom user
I followed what django docs said about inheriting AbstractUser to make a custom user for easy future changes https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project Anyway, I have it now on the admin menu as a different page, it now looks like this I basically want to disable that input (and others as well). How do I do that? -
django filter by datetime range using a datetimepicker
i am doing an eCommerce project and this is my analytics view : def analytics(request): orders = None total = 0 predicate = request.POST # or request.data for POST if predicate.get('from_date', None) is not None : orders = Order.objects.filter(timestamp__gte=predicate['from_date']) total = orders.aggregate(total_price=Sum('total')) context= { 'orders': orders, 'total' : total } return render(request,'analytics.html', context) it's pretty simple : i am letting the user chose a date with jquery datetimepicker and iam filtering the Order model based on that date to get all order starting that chosen date (period) it works fine but what i really want to do is let's say the user chose a 5 days period , i want to get is a list of orders in each day during that 5 day period : something like this : day 1: 3 orders day 2: 2 orders day 3: 5 orders day 4: 1 orders day 5: 8 orders and calculate total orders price for each day so i can graph that data using Chart.js -
CSS doesn't load properly with django
For a project, i try to make a website with django. I think I've set everything up right but when I go to my website, the css sheet doesn't load. When I go to my website, I have this. Here's my folders Installed apps : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig' Main urls.py : from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')) ] Home urls.py : from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] CSS File : html{ background-color: red; } HTLM File : {% load static %} <!DOCTYPE html> <html> <head> <title>Chasse au trésor du lycée Renoir</title> <link rel="stylesheet" type="text/css" href="{% static 'css/index.css' %}"> </head> <body> <h1>Hello World</h1> </body> </html> -
How to display post in two columns in one row using bootstrap 4.0 with the backend django
Two get the two columns in single row using Bootstrap 4.0, We can achieve this using the following code. <div class="container"> <div class="row"> <div class="col">Column</div> <div class="col">Column</div> <div class="w-100"></div> <div class="col">Column</div> <div class="col">Column</div> </div> </div> How do I apply the same in the following code when the data is iterating using for loop? Here is my html file. <div class="container"> <div class="row"> <div class="col-md-8 mt-3 left"> {% for post in medicine_list %} <div class="col"> <div class="card mb-4"> <div class="card-body"> <h6 class="card-title"><a href="{% url 'medicine_detail' post.slug %}"> {{ post.title }}</a></h6> </div> </div> </div> {% endfor %} </div> {% block sidebar %} {% include 'sidebar.html' %} {% endblock sidebar %} </div> </div> I'm getting confuse because of the for loop and the <div class="w-100"></div> tag. Any help would be really appreciable. Thanks. -
django-haystack with solr index multiple models but only one indexed
I had two SearchIndexes with exactly same fields such as: class TopicIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True, template_name="topic_template.txt") id = indexes.IntegerField(model_attr='id') title = indexes.CharField(model_attr='title') extra_info = indexes.CharField() type = indexes.CharField(default="topic") def get_model(self): return Topic def index_queryset(self, using="default"): return self.get_model().objects.all() def prepare_extra_info(self, obj): return "/media/" + str(obj.cover) class ReviewIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True, template_name="review_template.txt") id = indexes.IntegerField(model_attr='id') title = indexes.CharField() extra_info = indexes.CharField() type = indexes.CharField(default="review") def get_model(self): return Review def index_queryset(self, using="default"): return self.get_model().objects.all() def prepare_title(self, obj): return obj.topic.title def prepare_extra_info(self, obj): return obj.reviewer.name One is related to the other one. And I am trying to index them two into one solr core with schema like: <fields> <field name="id" type="string" indexed="true" stored="true" multiValued="false" required="true"/> <field name="django_ct" type="string" indexed="true" stored="true" multiValued="false"/> <field name="django_id" type="string" indexed="true" stored="true" multiValued="false"/> <field name="text" type="edge_ngram" indexed="true" stored="true" multiValued="false" /> <field name="title" type="text_en" indexed="true" stored="true" multiValued="false" /> <field name="extra_info" type="text_en" indexed="true" stored="true" multiValued="false" /> <field name="type" type="text_en" indexed="true" stored="true" multiValued="false" /> <uniqueKey>id</uniqueKey> </fields> However, every time I did either rebuild_index or update_index, it indexes both models: Removing all documents from your index because you said so. All documents removed. Indexing 9 topics Indexing 19 reviews Solr only has second model indexes in its documents as I … -
Add confirm password field in modelform in django only with one password field
I want to add the confirm password field in django modelform and validate both password and confirm password. After entering the details through template that data will be stored in database. But only three fields will be added to database such as firstname,lastname and email. so, i want to add the all fields data into database. Here is my model: class Register(models.Model): first_name = models.CharField(max_length=30, blank=False) last_name = models.CharField(max_length=30, blank=False) email = models.EmailField(max_length=50, blank=False) password = models.CharField(max_length=12, blank=False) Here is my modelform : class SignUpForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) password_confirm = forms.CharField(widget=forms.PasswordInput()) class Meta: model = Register fields = ['first_name', 'last_name', 'email','password'] def clean(self): cleaned_data = super(SignUpForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("password_confirm") if password != confirm_password: raise forms.ValidationError( "password and confirm_password does not match" ) Here is my view.py file : def auth_register(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() return HttpResponse('data has been saved...!!') else: form = SignUpForm() return render(request, 'auth-register.html', {'form': form}) Here is template code: <form method="post" action="">{%csrf_token%} <div class="row"> <div class="form-group col-6"> <label for="first_name">First Name : </label> <input id="first_name" type="text" class="form-control" name="first_name" autofocus=""> </div> <div class="form-group col-6"> <label for="last_name">Last Name : </label> <input id="last_name" type="text" class="form-control" name="last_name"> </div> </div> <div class="form-group "> … -
How to perform calculations in abstract models in Django
I'm using an abstract base class to perform simple calculations in my models as below: class Base(models.Model): name = models.CharField(max_length=100, null=True) width = models.DecimalField(max_digits=10, decimal_places=2, default=1, validators=[MinValueValidator(1)]) length = models.DecimalField(max_digits=10, decimal_places=2, default=1, validators=[MinValueValidator(1)]) # I'm sure that this part is not correct, I have copied it # from a regular model thinking that this would work, but it didn't def save(self, *args, **kwargs): self.building_area = self.room_area + self.hall_area super().save(*args, **kwargs) class Meta: abstract = True class Room(Base): room_area = models.DecimalField(max_digits=10, decimal_places=2, default=1, validators=[MinValueValidator(1)]) def save(self, *args, **kwargs): self.room_area = self.length*self.width super().save(*args, **kwargs) def __str__(self): return self.name class Hall(Base): hall_area = models.DecimalField(max_digits=10, decimal_places=2, default=1, validators=[MinValueValidator(1)]) def save(self, *args, **kwargs): self.hall_area = self.length*self.width super().save(*args, **kwargs) def __str__(self): return self.name Can someone suggest how to implement such kind of calculations? -
How to import request.user into TemplateVew in djnago
I need to know how I can check if a user is authenticated user the TemplateView methods of rendering pages. i have added this into my context processors: TEMPLATE_CONTEXT_PROCESSORS = [ 'django.contrib.auth.context_processors.auth', ] my views.py currently looks like : from django.shortcuts import render from CreateVuln.forms import * from django.views.generic import TemplateView from django.template import RequestContext from pages.decorators import * vulnform = vulnform class Dashboard(TemplateView): template_name = 'vuln_pages/Create_Vuln.html' def get(self, request): Outform = { 'vulnform': vulnform, } return render(request, self.template_name, Outform) def post(self, request): forminput = vulnform(request.POST or None) if forminput.is_valid(): forminput.save() forminput = vulnform() inoutform = { 'vulnform': forminput, } return render(request, self.template_name, inoutform, ) else: inoutform = { 'vulnform': vulnform, } return render(request, self.template_name,inoutform ) # Create your views here. class ViewVulns(TemplateView): template_name = 'vuln_pages/Create_Vuln.html' def get(self, request): return render(request, self.template_name) I want to make it so the page cannot be viewed with either a GET request and cannot be updated with a POST request. i've tried using RequestContext. but the documentation seems convoluted and i cannot seem to understand how to use it. -
django: app not found when trying to import in urls
I am using Django 3. I have the following project structure: I am trying to import from my app "users" the "views" file as "users_view" in the main "urls.py" in django_devel_app from users import views as users_views the app is added in my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', #Core authentication framework and its default models. 'django.contrib.contenttypes', #Django content type system (allows permissions to be associated with models). 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'projects.apps.ProjectsConfig', 'users.apps.UsersConfig', Nevertheless I am not able to do that in pycharm. It does not find the app "users and underlines "users" in urls.py saying "unresolved reference"? -
how to create a nested API (CRUD) using Django?
i have a problem and i got very tired. i have a Service Model and it has a lot of relation with other models! This is my model: class Service(models.Model): user_iduser = models.ForeignKey(User, models.DO_NOTHING, db_column='User_idUser') # Field name made lowercase. request_date = models.DateTimeField(blank=True, null=True) country = CountryField(blank_label='(إختر الدولة)') # ++++++++++++++++++ insurance = models.OneToOneField(Insurance, models.DO_NOTHING, blank=True, null=True) omra = models.OneToOneField(Omra, models.DO_NOTHING, blank=True, null=True) organized_journey = models.OneToOneField(OrganizedJourney, models.DO_NOTHING) other = models.OneToOneField(Other, models.DO_NOTHING, blank=True, null=True) temp_hotel_reservation = models.OneToOneField('TempHotelReservation', models.DO_NOTHING, blank=True, null=True) temp_ticket = models.BooleanField(blank=True, null=True) ticket = models.OneToOneField('Ticket', models.DO_NOTHING, blank=True, null=True) travel_hotel_reservation = models.OneToOneField('TravelHotelReservation', models.DO_NOTHING, blank=True, null=True) visa = models.OneToOneField('Visa', models.DO_NOTHING, blank=True, null=True) visa_rdv = models.BooleanField(blank=True, null=True) visa_request_form = models.BooleanField(blank=True, null=True) client = models.ManyToManyField("Client") is_active = models.BooleanField(default=True) class Meta: managed = True db_table = 'service' unique_together = (('id', 'user_iduser'),) def __str__(self): return f'service to client {self.country}' the problem is: i want to create an API for this model and it will contains a nested APIs of other model like this: { clients: [ { firstName_ar, lastName_ar, firstName_fr, lastName_fr, passport_id, phone, email_fb, date_birth place_birth }, { firstName_ar, lastName_ar, firstName_fr, lastName_fr, passport_id, phone, email_fb, date_birth place_birth } ] country: 'DZ', insurance: { number: 1245454, } || False, omra:{ food: true, duration: 15, start_date: '2020-04-05', hotel_name: … -
Django ValueError: Field 'id' expected a number but got ' '
I keep having a problem with Django. In my website I've got a simple form for adding new items to the database. I'd like the items and the user who added them to be related just as with a post and its author. The first one (AddInfo) let the user add, through a form, the items. Signup let the user authenticate first. class AddInfo(CreateView): model = Info fields = '__all__' success_url = reverse_lazy('home') def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = UserCreationForm() return render(request, 'search/signup.html', {'form': form}) In my models.py I've got this, where 'utente' (the last field), should be the user who added the item. But when I try to migrate I've got this error: ValueError: Field 'id' expected a number but got ' '. class Info(models.Model): band = models.CharField(max_length=200) disco = models.CharField(max_length=200) etichetta_p = models.CharField(max_length=200) etichetta_d = models.CharField(max_length=200) matrice = models.CharField(max_length=200) anno = models.PositiveIntegerField(default=0) cover = models.ImageField(upload_to='images/') utente = models.ForeignKey(User, on_delete=models.CASCADE) -
uwsgi --http-timeout and django
I have an issue with uwsgi handling requests for django application. uwsgi is started with the follwing parameters: uwsgi --http :8000 --wsgi-file djangoapp/wsgi.py --http-timeout 10 There 2 issues that I have. 1) There is not error message generated by uwsgi when the timeout is reached and connection is cut 2) Django processing continues I reviewed all configuration options and didn't find a way to configure the desired behaviour. Any suggestions?