Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get user's site field auto-assigned while creating an user Instance depending upon the domain name it came through? (Django)
My user class is an extension of AbstractBaseUser and which has site field as a ForeignKey field from the Django Site Framework which I have made null and blank True for time-being. ## MyUser Model import uuid from django.contrib.sites.managers import CurrentSiteManager from django.utils import timezone from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from phonenumber_field.modelfields import PhoneNumberField from django.contrib.sites.models import Site from django.contrib.sites.shortcuts import get_current_site from django.contrib.auth.models import User # Create your models here. class MyUser(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, editable=False,unique=True, default=uuid.uuid4) email = models.EmailField(max_length=350, unique=True) phone = PhoneNumberField(null=True, blank=True) date_of_birth = models.DateTimeField(blank=True, null=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_Te = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) site = models.ForeignKey(Site, on_delete=models.CASCADE, null=True, blank=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] # by default username field and password objects = MyUserManager() on_site = CurrentSiteManager() def __str__(self): return self.email class Meta: unique_together = ('site', 'email') @property def is_admin(self): return self.is_superuser My question is, how do I write code such that any user instance trying to get created will have site field auto-assigned depending on the domain-name it came through ?? For.eg if the user was created from http://127.0.0.1:8000/admin/user/myuser/ assign the user's site field to "1" (by my current setting) … -
How to accept a WebSocket extension in Django channels?
I am trying to add compression support to my django-channels consumer using WebSocket extensions. from channels.generic.websocket import WebsocketConsumer class MyConsumer(WebsocketConsumer): def connect(self): self.accept() def receive(self, text_data=None, bytes_data=None): self.send(text_data="Hello world!") The problem is that I cannot find a way to inform client that compression extension was accepted. If a client provides 'Sec-WebSocket-Extensions: permessage-deflate' header the server should respond with the same header, however it seems that django-channels doesn't have a way to provide it, because accept() implementation is as follows: def accept(self, subprotocol=None): """ Accepts an incoming socket """ super().send({"type": "websocket.accept", "subprotocol": subprotocol}) I guess one option is to use HTTP response start to add headers to the response, but I am not sure if this is the right path. -
NameError: name 'ForeignKey' is not defined in my Django code
I am getiing an error Foreign Key not defined task_name=ForeignKey(Task_List, on_delete=models.SET_NULL, null=True) NameError: name 'ForeignKey' is not defined models.py: class Task_List(models.Model): task_name=models.CharField(max_length=100, default="NOT SPECIFIED") c1=models.CharField(max_length=30, default="OTHER") c2=models.CharField(max_length=30, default="OTHER") c3=models.CharField(max_length=30, default="OTHER") time_esc=models.IntegerField(default=1) def __str__(self): return self.title class Task_manager(models.Manager): def create_Task(self, title): Task1 = self.create(title=title) # do something with the book return Task1 class Task(models.Model): task_name=ForeignKey(Task_List, on_delete=models.SET_NULL, null=True) title=models.CharField(max_length=30,default="Other", blank=Ture) created=models.DateTimeField(auto_now_add=True) objects=Task_manager() class Meta: ordering = [ '-created'] def __str__(self): return self.title -
How can I complete the to do app list task?
I have just started to learn django, and my first project is ToDo app list(from a tutorial). I want to add more features on the project by adding a checkbox in update_task tamplet, so the user after he had finish his task can be completed. This is update_task.html <div class="center-column"> <!---h3>Update Task</h3---> <div class="item-row"> <h3>Update Task</h3> <form method="POST" action=""> {% csrf_token %} {{form.title}} <input class="btn btn-primary" type="submit" name="Update Task"> <a type="button" class="btn btn-secondary" href="{% url 'todo:index' %}">Cancel</a> <div class="item-row1"> <h5 class="text-dark font-weight-bold">Is this task complete?</h5> <div class="regular-checkbox"> {% if task.complete == True %} <input type="hidden" class="taskCheckbox" name="done" id="{{ task.id }}" value="on"> <label for="{{ task.id }}" class="text-dark">Complete<strike>{{ task }}</strike></label> {% endif %} </div> </div> This is index.html <div class="center-column"> <form method="POST" action="/"> {% csrf_token %} {{form.title}} <input class="btn btn-info" type="submit" name="Create task"> </form> <div class="todo-index"> {% for task in tasks %} <div class="item-row"> <a class="btn btn-sm btn-info" href="{% url 'todo:update_task' task.id %}">Update</a> <a class="btn btn-sm btn-danger" href="{% url 'todo:delete' task.id %}">Delete</a> <span>{{task}}</span> </div> {% endfor %} This is view.py def index(request): tasks = todo.objects.all() form = todoForm() if request.method == "POST": form = todoForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'tasks':tasks, 'form':form} return render(request, 'todo/index.html', context) def updateTask(request, pk): task … -
Django import export has error "Tablib has no format 'None' or it is not registered"
I am trying to implement csv import in my application and I have this error, Tablib has no format 'None' or it is not registered. I am using python 3.5 and Django 2.2. I tried the same code with python 2.7 with Django 1.8 and it worked well. Is there any problem with my code? My model: class Stock(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True) item_name = models.CharField(max_length=50, blank=True, null=True) quantity = models.IntegerField(default='0', blank=False, null=True) receive_quantity = models.IntegerField(default='0', blank=True, null=True) receive_by = models.CharField(max_length=50, blank=True, null=True) issue_quantity = models.IntegerField(default='0', blank=True, null=True) issue_by = models.CharField(max_length=50, blank=True, null=True) issue_to = models.CharField(max_length=50, blank=True, null=True) phone_number = models.CharField(max_length=50, blank=True, null=True) created_by = models.CharField(max_length=50, blank=True, null=True) reorder_level = models.IntegerField(default='0', blank=True, null=True) last_updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return self.item_name Resources.py from import_export import resources from .models import Stock, Person class StockResource(resources.ModelResource): class Meta: model = Stock Views.py: from .resources import StockResource def upload(request): if request.method == 'POST': stock_resource = StockResource() dataset = Dataset() new_stock = request.FILES['myfile'] imported_data = dataset.load(new_stock.read()) result = stock_resource.import_data(dataset, dry_run=True) # Test data import if not result.has_errors(): stock_resource.import_data(dataset, dry_run=False) # Run import return render(request, 'csv_import.html') csv_import.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"><br><br> <button type="submit">Upload</button> </form> csv_import.csv 1,phone,1,0,9,0,9,9,9,,ssaine,0,2020-06-11, 2,computer,2,0,9,0,9,9,9,9,ssaine,0,2020-08-11, -
int() argument must be a string, a bytes-like object or a number, not 'NoneType' Django Form
I have a issue when i submit a form on my checkout view. first of i have a form on my main view where i ask for quantity of an item. I post the data to my checkout view to make a summary on my front-end. On my Checkout view i have another form where i ask for email and name, when i try to submit the checkout form i have a typeError. int() argument must be a string, a bytes-like object or a number, not 'NoneType' Here is my checkout view # My view @login_required(login_url='login') def checkout(request): data = request.POST.copy() region = data.get('region-select') plateform = data.get('plateform-select') quantity = data.get('quantity-field') quantity = int(quantity) price = quantity * 3.99 context = { 'region':region, 'plateform':plateform, 'quantity':quantity, 'price':price } return render(request, 'main/checkout.html', context) I don't understand why this occurs because the data get rendered in my template <h1 class="title is-5" style="margin-bottom:5px;"> {{price|floatformat:2}} EUR </h1> -
sending multiple input with same name drf django
i have a simple form and an api with drf and in form i have add field button from that i am cloning the fields with ajax and i want to submit the data from cloned field also with same api models.py: class Sample(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) serializers.py: class SampleSerializer(serializers.ModelSerializer): class Meta: model = Sample fields = '__all__' views.py: class SampleViewSet(ModelViewSet): queryset = Sample.objects.all() serializer_class = SampleSerializer html page: <form method="post" id="sampleform" action="#"> {% csrf_token %} <div class="input_fields" style="text-align:center"> <input type="text" name="first_name" id="first_name" placeholder="first name"/> <input type="text" name="last_name[]" id="last_name" placeholder="Last Name"/> <button class="add_button">Add More Fields</button> <button type="submit">Submit</button> </div> </div> </form> script: <script> $(document).ready(function() { var max_fields = 10; var wrapper = $(".input_fields"); var add_button = $(".add_button"); var x = 1; $(add_button).click(function(e){ e.preventDefault(); if(x < max_fields){ x++; $(wrapper).append( '<div class="form-group" style="margin-top:5px"><input type="text" name="first_name[]" placeholder="first name" required/><input type="text" name="last_name[]" placeholder="last name" required/><a href="#" class="remove_field">Remove</a></div>' ); } }); $(wrapper).on("click",".remove_field", function(e){ e.preventDefault(); $(this).parent('div').remove(); x--; }) }); </script> <script> $('#sampleform').submit(function(e){ e.preventDefault(); var form = $(this); $.ajax({ url:"http://localhost:8000/api/", type:"post", data: { //data:form.serialize(), first_name: $('#first_name').val(), last_name:$('#last_name').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, //dataType:'json', success: function(data){ console.log(data) }, }); }); </script> as you can see i am creating 10 row with two fields and i'm getting the value of … -
i cant add an email to any user i created using the the django admin
here is my problem i have a website with multiple users,but i divided the users into 2,Doctor and Patient,the Doctor has higher authority than the Patient,but whenever i add a user.doctor,i wont get their email address, but only the email address can be used to login,meanwhile i set every sign up any user do to create a patient automatically,so i can upgrade them using the admin panel,but if i create any user directly i wont get their email just the rest of the info those email address shown are the ones i created using the website or the createsuperuser here are my code models.py class CustomUser(AbstractUser): is_doctor = models.BooleanField(default=False) def __str__(self): return self.email class Status(models.Model): title= models.CharField(max_length=5) def __str__(self): return self.title class Doctor(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, null=True, related_name="doctor") image = models.ImageField(default='jazeera.jpg', upload_to='profile_pics') bio = models.TextField() speciality = models.CharField(max_length=300) describtion = models.CharField(max_length=100) status = models.ManyToManyField(Status) def __str__(self): return f'{self.user.username}' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) class Patient(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, null=True, related_name="patient") subscribe = models.BooleanField(default=False) def __str__(self): return f'{self.user.username}' @receiver(post_save, sender=CustomUser) def create_user_profile(sender, instance, created, **kwargs): print("****", created) if instance.is_doctor: Doctor.objects.get_or_create(user=instance) else: … -
Trouble installing django with pipenv
I'm following the steps in this tutorial here: https://djangoforbeginners.com/initial-setup/ I installed pipenv and then went to install Django but was unable to. Any help would be very much appreciated. I'm running Windows 10 and have Python 3.8. Also I'm using Powershell. Collecting pipenv Downloading pipenv-2020.6.2-py2.py3-none-any.whl (3.9 MB) |████████████████████████████████| 3.9 MB 930 kB/s Collecting certifi Downloading certifi-2020.4.5.2-py2.py3-none-any.whl (157 kB) |████████████████████████████████| 157 kB 2.2 MB/s Requirement already satisfied: pip>=18.0 in c:\python38\lib\site-packages (from pipenv) (20.1.1) Requirement already satisfied: virtualenv in c:\python38\lib\site-packages (from pipenv) (20.0.21) Collecting virtualenv-clone>=0.2.5 Downloading virtualenv_clone-0.5.4-py2.py3-none-any.whl (6.6 kB) Requirement already satisfied: setuptools>=36.2.1 in c:\python38\lib\site-packages (from pipenv) (41.2.0) Requirement already satisfied: distlib<1,>=0.3.0 in c:\python38\lib\site-packages (from virtualenv->pipenv) (0.3.0) Requirement already satisfied: appdirs<2,>=1.4.3 in c:\python38\lib\site-packages (from virtualenv->pipenv) (1.4.4) Requirement already satisfied: six<2,>=1.9.0 in c:\python38\lib\site-packages (from virtualenv->pipenv) (1.15.0) Requirement already satisfied: filelock<4,>=3.0.0 in c:\python38\lib\site-packages (from virtualenv->pipenv) (3.0.12) Installing collected packages: certifi, virtualenv-clone, pipenv Successfully installed certifi-2020.4.5.2 pipenv-2020.6.2 virtualenv-clone-0.5.4 PS C:\Users\travi\desktop> mkdir django Directory: C:\Users\travi\desktop Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 2020-06-16 9:15 AM django PS C:\Users\travi\desktop> cd django PS C:\Users\travi\desktop\django> pipenv install django==3.0 Traceback (most recent call last): File "c:\python38\lib\runpy.py", line 194, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\python38\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Python38\Scripts\pipenv.exe\__main__.py", line 7, in <module> … -
502 Bad Gateway Error Displayed, Timeout Occurs
I am currently having some issues with my nginx and gunicorn setup. Once I have both of them enabled and go to the IP address established by digitalocean, it takes 5 minutes to show me 502 Bad Gateway Nginx. Afterwards I get a sentry error that reads: "OperationalError could not connect to server: Connection timed out Is the server running on host "myproject-postgres-staging-db-do-user-6482921-0.db.ondigitalocean.com" (64.225.42.160) and accepting TCP/IP connections on port 25060?" I have been trying all sorts of different things with my nginx and gunicorn configs as well as the settings.py file, but to no avail. I'm not sure if I did something wrong in relation to those methods hence why I didn't get any results, but I am out of ideas. Here's my code for reference. Nginx config: # You should look at the following URL's in order to grasp a solid understanding # of Nginx configuration files in order to fully unleash the power of Nginx. # https://www.nginx.com/resources/wiki/start/ # https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/ # https://wiki.debian.org/Nginx/DirectoryStructure # server { listen 80 default_server; listen [::]:80 default_server; server_name myproject.app www.myproject.app IP ADDRESS; error_log /home/myuser/nginxError.log warn; access_log /home/myuser/nginx.log ; server_tokens off; add_header X-Frame-Options SAMEORIGIN; add_header X-Content-Type-Options nosniff; add_header X-XSS-Protection "1; mode=block"; add_header Strict-Transport-Security "max-age=31536000; includeSubdomains; … -
can not create PointField() in GeoDjango
I can not create my database from this sample models.py. from django.contrib.gis.db import models class Subscriber(models.Model): id = models.IntegerField(primary_key=True) login = models.CharField(max_length=200, unique=True) email = models.CharField(max_length=200, unique=True) country = models.CharField(max_length=200) def __str__(self): return self.email class Localisation(models.Model): name = models.CharField(max_length=100) point = models.PointField() address = models.CharField(max_length=100) city = models.CharField(max_length=50) class Video(models.Model): id = models.IntegerField(primary_key=True) video_title = models.CharField(max_length=200) video_url = models.CharField(max_length=255, unique=True) video_file = models.CharField(max_length=50) video_date = models.DateTimeField('date published') video_user = models.ForeignKey(Subscriber, on_delete=models.CASCADE) loc = models.ForeignKey(Localisation, on_delete=models.CASCADE) def __str__(self): return self.video_title + " / " + self.video_file I get this error whatever I try (tried Stackoverflow and Google in vain) : File "/usr/lib/python3.8/site-packages/django/contrib/gis/db/models/fields.py", line 188, in get_prep_value raise ValueError("Couldn't create spatial object from lookup value '%s'." % obj) ValueError: Couldn't create spatial object from lookup value 'POINT(12.4604, 43.9420)'. I do not know where the value POINT((12.4604, 43.9420). I've never typed it. I guess I need to add a default value, which I tried also, by modifying the point = models.PointField() in: point = models.PointField(default='POINT(0 0) but the errors still occurs... -
Problem with user hierarchy mapping for Sales Team management app - Django
I need your help/guidance as 'm new to django-python web development and i'm stuck at one of my project. Below are the explained scenario for your reference. Project : Sales team management webapp platform : Django- python This app has multiple users Ie. customer, dealer, sales manager, regional manager and admins. So i need to create account for all of them with respective privileges. All of the user should be mapped to each other Ie. customer Upper user can see data of their mapped lower user. **What i have done: I have created models for all of the users and able to get them registered using views. Where i'm stucK: Unable to map the users to each other Also wants to show the upper hierarchy as selection dropdown while registration. which im unable to do.** Please help me. Thanks in advance. -
Getting Response 475 on making XHR Requests
I am making XHR Request to the Hotstar API, https://api.hotstar.com/s/v1/scout?q={movie_name}&perPage=50. The headers I am using are, headers = { 'x-country-code': 'IN', 'x-platform-code': 'PCTV', 'hotstarauth': 'st=1591731250~exp=1591737250~acl=/*~hmac=30e290968fac98e02d39b937ec556c42d1692d6493d0ae29e49bcb1723829e23', } Copied everything from the developer tools of the browser The request works fine on my local machine, but gives response 475 on heroku server. I think the problem lies with x-platform-code. Can someone please tell me, if I am correct, than what should I use in place of x-platform-code, or anything else to remove the error. Everything is working as expected on my local machine. -
(Django Templates) HTML page to select CSV fields from dropdowns to choose which Model field each relates to
What I'm trying to do is to build a simple HTML interface to Upload CSV, then select CSV fields related to each Model field. This is an example of csv file. id first_name last_name email gender ip_address app_name 1 Law Lismore llismore0@noaa.gov Male 87.223.253.208 Veribet 2 Phylis Rolfi prolfi1@ycombinator.com Female 205.75.2.218 Rank 3 Millisent Faulkner mfaulkner2@ted.com Female 35.97.69.238 Cardguard 4 Simone Minci sminci3@privacy.gov.au Male 178.6.109.253 Asoka 5 Virge Hadland vhadland4@artisteer.com Male 26.218.62.107 Latlux views.py def upload_csv_file(request): if request.method == 'POST': form = UploadCSVForm(request.POST, request.FILES) if form.is_valid(): file = request.FILES['file'] reader = csv.DictReader(io.StringIO(file.read().decode('utf-8'))) context = { 'fields': reader.fieldnames, ??? } return render(request, 'csv_mapper/field_choices.html', context) else: form = UploadCSVForm() return render(request, 'csv_mapper/index.html', {'form': form}) models.py class CSVMap(models.Model): id_in_doc = models.IntegerField() first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField() How to write field_choices.html with interface like this and receive a dict after Confirm? And how pass reader to the next view which is going to store the data to DB? { id_in_doc: id, first_name: first_name, ... } -
TypeError: unsupported operand type(s) for +: 'float' and 'list' how to solve it in django?
I have a question for you. I have the following class: class StatoPatrimoniale(models.Model): reference_date=models.DateField() income=models.DecimalField() debt=models.DecimalField() After that I have named a new variable last_account_year in th following manner: now=datetime.datetime.now() last_account_year=float(now.year)-1 After that I have created the following code: if StatoPatrimoniale.objects.filter(reference_date__year=last_account_year).count()>0: list_diff = float(StatoPatrimoniale.objects.filter(reference_date__year=last_account_year).values_list('crediti_commerciali')[0][0]) else: list_diff=[0]+list_diff crediti_commerciali = {} crediti_commerciali['Crediti Commerciali'] = list(accumulate(list_diff)) But give me the following error: unsupported operand type(s) for +: 'float' and 'list' How could I solve it? -
Google Maps with Django
i'm trying to link google maps with my location point field rather then leaflet, bacause google maps is having a better functionality at my area. am going to link that with my forms.py to make users be able to select their location and submit it on a model-form. any suggestions on how i could do that with Geo-django ? models.py from django.contrib.gis.db import models class ShippingAddress(models.Model): name = models.CharField(max_length=200, null=False) location = models.PointField() forms.py class AddAddress(forms.ModelForm): location= forms.PointField(label="", widget = ...) name = forms.CharField(label="") class Meta: model = ShippingAddress fields = ('location', 'name') -
Image uploading from Django-template to model is not working
I am trying to upload profile image of user from userprofile.html template but it is not uploading to that model on admin panel. I already configured the static and media settings correctly. #forms.py class ImageUploadForm(forms.ModelForm): class Meta: model = accountUser fields = ['profile_photo',] #views.py def upload_pic(request): if request.method == 'POST': form = ImageUploadForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('success') else: form = ImageUploadForm() return HttpResponseForbidden('allowed only via POST') #user.html <form method = "post" enctype="multipart/form-data"> {% csrf_token %} <p> <input id="id_image" type="file" class="" name="image"> </p> <button type="submit">Choose Picture</button> </form> -
Cannot resolve keyword 'username' into field. Choices are: bio, blog, describtion, id, image, speciality, status, user, user_id
hey i want to create a profile page for my user,in which when people logging to the website they can view the profile of every user,i get the above error anytime i tried to log on to every profile of the user i get it, this is my code below views.py class DoctorDetailView(LoginRequiredMixin, DetailView): model = Doctor fields = ['user', 'email', 'image', 'speciality', 'bio'] template_name = 'pages/doctor_detail.html' def get_queryset(self): user = get_object_or_404(Doctor, username=self.kwargs.get('username')) return Doctor.objects.filter(doctor=user.doctor) urls.py path('doctor/', doctor, name='doctor'), path('doctor/info/<str:username>', user_views.DoctorDetailView.as_view(), name='doctor-detail'), doctor.html <a href="{% url 'doctor-detail' doc.user.username %}"><div class="img-wrap d-flex align-items-stretch"> <div class="img align-self-stretch" style="background-image: url({{ doc.user.doctor.image.url }}"></div> models.py class Doctor(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, null=True, related_name="doctor") image = models.ImageField(default='jazeera.jpg', upload_to='profile_pics') bio = models.TextField() speciality = models.CharField(max_length=300) describtion = models.CharField(max_length=100) status = models.ManyToManyField(Status) def __str__(self): return f'{self.user.username}' -
Django viewset error: 'QuerySet' object has no attribute 'title'
I'm trying to create a ViewSet for the Course model (to simply display all courses), but I'm getting the following error when trying to access it. I'm new to creating ViewSets and Django in general, what am I doing wrong? Error AttributeError: Got AttributeError when attempting to get a value for field `title` on serializer `CourseSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance. Original exception text was: 'QuerySet' object has no attribute 'title'. CourseViewSet class CourseViewSet(viewsets.ModelViewSet): def list(self, request): queryset = Course.objects.all() serializer = CourseSerializer(queryset) return Response(serializer.data) CourseSerializer class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = ( 'id', 'title', 'description', 'active', 'individual_result', 'course_duration', 'video', 'manager_id' ) models/Course class Course(models.Model): title = models.CharField(max_length=255, blank=False, null=False) description = models.CharField(max_length=255, blank=True, null=True) active = models.BooleanField(default=True) individual_result = models.BooleanField(default=False) course_duration = models.CharField(max_length=255, blank=True, null=True) video = models.CharField(max_length=255, blank=True, null=True) manager_id = models.ForeignKey(User, on_delete=models.CASCADE, null=True) def __str__(self): return self.title -
Django Rest Framework - Serialize intermediate model fields (to POST or GET)
I am trying to handle POST and GET requests of my SalesProject model, which has a M2M field to CustomerInformation model, with an intermediate model of ProjectCustomer. I am wondering if there are any ways for me to be able to create a new SalesProject instance, and add the relevant instances of CustomerInformation to that created SalesProject instance, just like how it would have been done before I switched it to an intermediate model. Basically, this is the data that I would want to pass in for the POST request {sales_project_name: "Test Project", customer_information: [1, 2]} where [1,2] is the id of the CustomerInformation instance that I want to link M2M to that particular SalesProject I am creating Here is my models.py class CustomerInformation(models.Model): customer_id = models.AutoField(primary_key=True) customer_name = models.CharField(max_length=100) history = HistoricalRecords() class SalesProject(models.Model): sales_project_id = models.AutoField(primary_key=True) sales_project_name = models.CharField(max_length=100) customer_information = models.ManyToManyField('CustomerInformation', through='Project_Customer') history = HistoricalRecords() class Project_Customer(models.Model): project = models.ForeignKey('SalesProject', on_delete=models.SET_NULL, null=True) customer = models.ForeignKey('CustomerInformation', on_delete=models.SET_NULL, null=True) history = HistoricalRecords() I am new to using intermediate models, so do guide me along if I am mistakened about anything! From what I see, it seems like when I try to create a SalesProject using ModelViewsets, the customer_information field … -
AttributeError: function 'initGEOS_r' not found
Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 122, in populate app_config.ready() File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\admin\apps.py", line 24, in ready self.module.autodiscover() File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\admin\__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\gis\admin\__init__.py", line 5, in <module> from django.contrib.gis.admin.options import GeoModelAdmin, OSMGeoAdmin File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\gis\admin\options.py", line 2, in <module> from django.contrib.gis.admin.widgets import OpenLayersWidget File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\gis\admin\widgets.py", line 4, in <module> from django.contrib.gis.geos import GEOSException, GEOSGeometry File "C:\Users\HP\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\gis\geos\__init__.py", line 5, in <module> from .collections import … -
SQL - Django Movie Booking System
I am currently working on movie booking site that allows user to book movie tickets at different time and date. I have already created the model for theater, seats, movie, and for movie date availability. I am wondering if; for every different time in a day: Example: - 12:30 PM - 3:00 PM - 5:30 PM It means for every theater in that 'time' i will create new seats for booking, just to get track on what seats are still available? Imagine, a theater-1 with capacity of 100 seats, that means that on 12:30 PM, a hundred seats are created. And at 3:00 PM, a different sets of seats are also created. That means that i will have a total of 200 seats, or 200 seats object on my database. Also the same scenarios on different dates, and theater number. Is there any way to reduce the number of data? Or my analyzation is wrong? -
Django aggregate Avg vs for loop with prefetch_related()
I have a Review model that is in one to one relationship with Rating model. A user can give a rating according to six different criteria -- cleanliness, communication, check_in, accuracy, location, and value -- which are defined as fields in the Rating model. class Rating(models.Model): cleanliness = models.PositiveIntegerField() communication = models.PositiveIntegerField() check_in = models.PositiveIntegerField() accuracy = models.PositiveIntegerField() location = models.PositiveIntegerField() value = models.PositiveIntegerField() class Review(models.Model): room = models.ForeignKey('room.Room', on_delete=models.SET_NULL, null=True) host = models.ForeignKey('user.User', on_delete=models.CASCADE, related_name='host_reviews') guest = models.ForeignKey('user.User', on_delete=models.CASCADE, related_name='guest_reviews') rating = models.OneToOneField('Rating', on_delete=models.SET_NULL, null=True) content = models.CharField(max_length=2000) I am thinking of a way to calculate the overall rating, which would be the average of average of each column in the Rating model. One way could be using Django's aggregate() function, and another option could be prefetching all reviews and looping through each review to manually calculate the overall rating. For example, for room in Room.objects.all() ratings_dict = Review.objects.filter(room=room)\ .aggregate(*[Avg(field) for field in ['rating__cleanliness', 'rating__communication', \ 'rating__check_in', 'rating__accuracy', 'rating__location', 'rating__value']]) ratings_sum = 0 for key in ratings_dict.keys(): ratings_sum += ratings_dict[key] if ratings_dict[key] else 0 Or, simply looping through, rooms = Room.objects.prefetch_related('review_set') for room in rooms: reviews = room.review_set.all() ratings = 0 for review in reviews: ratings += (review.rating.cleanliness + … -
I want to filter my Disciplina datas by id but appear this error FieldError at /admin-note/4 Cannot resolve keyword 'id' into field
I know that i must make a foreign key but i dont know how, the student id works, but dont have in my disciplina model and i dont know how i can make a fk in the model and filter by this. ########## view of this route ######### login_required(login_url='adminlogin') @user_passes_test(is_admin) def admin_note(request,pk): student=models.StudentExtra.objects.get(id=pk) user=models.User.objects.get(id=student.user_id) students=models.StudentExtra.objects.all().filter(id=pk) materias= models.Disciplina.objects.all().filter(id=pk) #i want to filter by id here return render(request,'school/admin_note.html', {'students': students, 'materias': materias, 'pk':pk}) ########## models ################# classes=[('maternalzinho','maternalzinho'),('maternal1','maternal1'),('maternal2','maternal2'), ('1periodo','1periodo'),('2periodo','2periodo'),('1ano','1ano'),('2ano','2ano'),('3ano','3ano'),('4ano','4ano'),('5ano','5ano')] class StudentExtra(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) roll = models.CharField(max_length=540) mobile = models.CharField(max_length=40,null=True) fee=models.PositiveIntegerField(null=True) cl= models.CharField(max_length=145,choices=classes,default='maternalzinho') status=models.BooleanField(default=False) respon= models.CharField(max_length=540, null=True) localnasc= models.CharField(max_length=540, null=True) estado = models.CharField(max_length=540, null=True) sexo= models.CharField(max_length=540, null=True) mae= models.CharField(max_length=540, null=True) emailrespon= models.CharField(max_length=200, null=True) cpfrespon= models.CharField(max_length=200, null=True) bairro= models.CharField(max_length=200, null=True) cidade= models.CharField(max_length=200, null=True) datenasc= models.CharField(max_length=540, null=True) @property def get_name(self): return self.user.first_name @property def get_id(self): return self.user.id def __str__(self): return self.user.first_name materia=[('lingua portuguesa','lingua portuguesa'), ('matematica', 'matematica'), ('ciencias', 'ciencias'), ('historia', 'historia'), ('geografia', 'geografia'), ('ingles', 'ingles'), ('artes', 'artes'), ('informatica', 'informatica'), ('recreacao', 'recreacao') ] class Disciplina(models.Model): codisc = models.AutoField(primary_key=True) nome_disc = models.CharField(max_length=540,choices=materia,default='lingua portuguesa') enter image description here -
Django: Reconstructing a form with ModelChoiceField from database
I have a Django form that contains several CharFields and ModelChoiceFields. Once the user has submitted the form, some calculations take place and the information is stored in the database. Since the form contains many fields, I would like to add the functionality that the user can reconstruct the form at a later point, change some settings and resubmit it. In my views.py, I check whether the form has been submitted before. If yes, I fill a dictionary with initial data from the database and then create an instance of the form. initialData = {} initialData['title'] = databaseObject.title ... ... form = myForm(initial = initialData) This works for the CharFields, but it does not work for the ModelChoiceFields. They are just empty. I cannot figure out how to put the queryset and the previously selected choice into the initialData dictionary so that the ModelChoiceFields are correctly populated and the correct choice is selected.