Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 4.2: Formset "This field is required"
Basic idea: Have a custom database table with only 2 text fields. It will never be updated by the user! Allow the user to select records via checkboxes. The selected records only influence the file that is being served later by the server. This is my models.py: class Person(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) I've created a custom non-model-form, derived from forms.Form only, because I will never use the user input to update the database table. All I need is some boolean information from the user. Here's forms.py: class PersonForm(forms.Form): first_name = forms.CharField() last_name = forms.CharField() selected = forms.BooleanField() PersonFormset = forms.formset_factory(PersonForm, extra=0) When the user calls the GET-view, he will see all people in the table and can select some via the checkboxes (notice: form has an additional boolean field). This is the GET-part of my views.py: obj = Person.objects.all().values() forms = PersonFormset(initial=obj) return render(request, 'myapp/mytemplate.html', {'formset': forms}) Everything works fine and displays correctly inside my HTML table. But then the POST fails. Here's the POST-part of my views.py: forms = PersonFormset(request.POST) The forms.is_valid() function returns false and all the error messages state 'This field is required' for all fields of all forms. For example forms[0]['first_name'].value() is None … -
django orm - annotate / aggregation (avg) in subquery
I have this model: class UserMovieRel(models.Model): user = models.ForeignKey("register.User", on_delete=models.CASCADE) movie = models.ForeignKey("Movie", on_delete=models.CASCADE, related_name="users") rating = models.PositiveIntegerField( validators=[MinValueValidator(1), MaxValueValidator(10)], null=True, blank=True ) advice = models.CharField(max_length=500, null=True, blank=True) objects = UserMovieRelManager() def __str__(self) -> str: return f"{self.user} - {self.movie} (rating: {self.rating or 'n/a'})" class Meta: constraints = [ models.UniqueConstraint(fields=["user", "movie"], name="user_movie_unique"), ] I'm trying to get the avg rating for each movie in this way: avg_ratings = UserMovieRel.objects.filter(movie_id=OuterRef("movie_id")).exclude(rating__isnull=True).annotate(avg_rating=Avg("rating")) UserMovieRel.objects.annotate(avg_rating=Subquery(avg_ratings[0])) but it fails: ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. I've tried also with aggregation: UserMovieRel.objects.annotate( avg_rating=Subquery( UserMovieRel.objects.filter( movie_id=OuterRef("movie_id") ).aggregate( avg_rating=Avg("rating") )["avg_rating"] ) ) but I've got the same error. any help on this? Thanks -
next-auth and django rest framework - how should I fetch user data after JWT authentication?
I'm building an app that uses django rest framework and simplejwt to authorize the users. I'm having trouble understanding what should be the optimal way of fetching user data after the user logs in and JWT is provided. Let's say I'd want to display the user name and email on the navigation bar. Should I: a) add the user name and email to the JWT response (not encoded)? b) after getting the JWT, use it to fetch the user data? As of now, my JWT (/api/auth/) endpoint response looks something like this: { "refresh": "refresh_token", "access": "access_token" } And here's an example of the decoded access token: decoded access token I thought that perhaps next-auth decodes the JWT response and pulls the user data from there. -
I am facing this error: cannot convert dictionary update sequence element #0 to a sequence (Django)
I am trying to edit some preregistered user details, I can see the user id is printed when I do it via the template and am Trying to det a default value for the username in this form (because I want it to be the logged in user) The code is as follows: views.py from django.shortcuts import render,redirect from django.http import HttpResponse from django.forms import inlineformset_factory from django.forms import modelformset_factory from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth import authenticate, login,logout from .models import * from .forms import * def udetail(request): userid = request.user.id user = account.objects.get(pk=userid) form=updateuser(initial={'username'== user}) if request.method == 'POST': form = updateuser(request.POST) if form.is_valid(): form.save() context = {'form':form} return render(request, 'main/udetail.html', context) Forms.py from django.forms import ModelForm from django.forms import BaseInlineFormSet from django.forms import BaseModelFormSet from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User from .models import * class updateuser(ModelForm): class Meta: model = account fields = ['username','dob','height','weight','extype','gender'] models.py from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractBaseUser, BaseUserManager GENDER_CHOICES = [ ("Male", "Male "), ("Female", "Female "), ] EX_CHOICES = [ ("70", "0-30 minutes "), ("250", "30-90 minutes "), ("600", "More than 90 minutes "), ] class … -
Django : redirect to previous url
its possible to create a thing which redirect me to previous url hi im learning django and thats one freaking me out i want create a button in my project which redirect user to url came form e.g. user from profile goes to followings and want get back to profile To be more precise a button like this little thing up here enter image description here which i can use it in entire project i tried everything came to my mind or i found in my searches with no results:) -
How do I stop Django from logging PermissionDenied exceptions?
My custom middleware raises a PermissionDenied exception in certain cases to return a 403 response to the client. I believe this is the "correct" way to do this. Unfortunately it also logs the exception with a traceback every time this happens, even with DEBUG set to False. 2023-05-08 10:27:25,293 WARNING django.request Forbidden (Permission denied): / Traceback (most recent call last): File "/opt/project/env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/opt/project/myapp/middleware.py", line 112, in call raise PermissionDenied django.core.exceptions.PermissionDenied I don't care about these exceptions. Is there a simple way to prevent them from being logged? -
I can't connect to another server using SSH tunnel in Django when containerizing it with Docker
I set up a SSH Tunnel for a MySQL instance in another server in my Django settings. Something like this: ssh_tunnel = SSHTunnelForwarder( os.environ['MYSQL_SERVER_IP'], ssh_username=os.environ['MYSQL_SERVER_USERNAME'], ssh_password=os.environ['MYSQL_SERVER_PASSWORD'], remote_bind_address=('localhost', 3306), ) ssh_tunnel.start() The package used is https://github.com/pahaz/sshtunnel When I start the app in local it works perfect, but when it's inside a container via docker-compose it throws Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 64590689ab386fb7f27ad7ca, topology_type: Unknown, servers: [<ServerDescription ('127.0.0.1', 27017) The docker-compose of this part of the service is this one: web: restart: always build: context: . dockerfile: ./Dockerfile ports: - "8000:8000" expose: - "8000" - "27017" links: - postgres:postgres volumes: - static_volume:/usr/src/app/static - media_volume:/web/media/ env_file: .env environment: DEBUG: 'true' command: python manage.py runserver 0.0.0.0:8000 networks: - web And this is the Dockerfile related to it FROM python:3.9-slim-buster RUN apt-get update && apt-get install -y gcc python3-dev RUN apt-get install libeccodes-dev -y RUN python -m pip install --upgrade pip COPY requirements.txt requirements.txt RUN python -m pip install -r requirements.txt COPY . . What am I doing wrong? Thanks! I tried exposing the port mentioned in the error (27017) and installing the ssh package in the docker instance. -
Removing url prefixes in django
Here is my localhost url localhost: 127.0.0.1:/8000/searches/?q=css I want to get rid of these: '?q=' I tried removing the name attributes from my html. <input type="text"> -
Unable to redirect non-www to www in django Nginx project on Digital Ocean
Hello I would be grateful if someone could please help with the following Nginx configuration: /etc/nginx/sites-available/example server { server_name example.com *.example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/admin/pyapps/example/example/static/; } location /static/admin/ { alias /home/admin/pyapps/example/example/static/admin/; } location /media/ { root /home/admin/pyapps/example; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/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 } server { if ($host = admin.example.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = backoffice.example.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = www.example.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name example.com *.example.com; return 404; # managed by Certbot } I would like to create a redirection for example.com to https://www.example.com. Note that I am using django-hosts. My configuration for django-hosts below: settings.py ROOT_URLCONF = 'example.urls' ROOT_HOSTCONF = 'example.hosts' DEFAULT_HOST = 'www' # DEFAULT_REDIRECT_URL = "http://www.example.com:8000" DEFAULT_REDIRECT_URL = "http://www.example.com" PARENT_HOST = 'example.com' # HOST_PORT = '8000' MIDDLEWARE = [ 'django_hosts.middleware.HostsRequestMiddleware', .... 'django_hosts.middleware.HostsResponseMiddleware', ] hosts.py from django.conf import settings from … -
Converting django app to windows exe using pyinstaller
I converted a django application into a windows application using pyinstaller. I created a seperate file runserver.py where I'm running the server in a thread and then opening webbrowser using web browser module. I'm getting error as No python at 'path' . It is taking my path on other computers too. It's not taking the path of env i created within django How can I activate the env of django so when people click on exe it should use the dependencies of env created within django app. -
Django doubling values in queryDict ... help please
I create some cascade models, double forms, and set of HTML-s with double views.py in django. When i want to save data i get doubling of data that has hidden input attribute. this is from my forms.py `class TaskContentForm(forms.ModelForm): task = forms.ModelChoiceField(queryset=Task.objects.all(), label="Task", widget=forms.HiddenInput(), required=True ) position_label = forms.CharField(label="Position Label", widget=forms.TextInput(attrs={'class': 'form-control task_content'}), required=True ) position_name = forms.CharField(label="Position Name", widget=forms.TextInput(attrs={'class': 'form-control task'}), required=True ) . . .` my models.py `class Task(models.Model): . . . class TaskContent(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE) position_label = models.CharField(max_length=100) position_name = models.CharField(max_length=100) . . . ` and my edit_content.html `<div class="row item-row"> <div class="col-12"> <div class="card card-body bg-white border-light shadow-sm mb-4"> <h2 class="h5 mb-4">Transaction information</h2> <form action="{% url 'task_contents' task=task.id pk=task_content.id %}" method="post"> {% csrf_token %} {% if task.id %} <input type="hidden" name="task" value="{{ task.id }}"> {% endif %} <div class="row"> {% for field in form %} <div class="col-md-6 mb-3"> <div>{{ field.label_tag }}{{ field }}</div> </div> {% endfor %} </div> <div class="mt-3"> <a class="btn btn-danger delete_item" data-href="{% url 'task_contents' task=task.id pk=task_content.id action='single' %}">Delete</a> <button type="submit" class="btn btn-primary">Save</button> </div> </form> </div> </div> </div>` When i press submit, i get terminal output: `{'_state': <django.db.models.base.ModelState object at 0x00000203DFEC5A20>, 'id': 8, 'task_id': 4, 'position_label': '1032', 'position_name': 'Kvaka', 'material': 'Silumin', 'material_supplier': … -
How to call an a callbacks when I take an a type of autorization?
I have got a project, which have an autorization by vk and google. I need to call funcitions like vk_callback or google_callback when i make autorization by this types. Hoe can i do it? views.py: def home(request): return HttpResponse('Home Page') def vk_callback(request): user_info_getter = UserInfoGetter(request.user, 'vk-oauth2') take_info = user_info_getter.get_user_info_vk() if take_info: name, last_name, photo = take_info print(name, last_name, photo, sep='\n') return redirect(home) def google_callback(request): user_info_getter = UserInfoGetter(request.user, 'google-oauth2') take_info = user_info_getter.get_user_info_google() if take_info: name, last_name, photo = take_info print(name, last_name, photo, sep='\n') return redirect(home) I try to make it by url-address, but it doesn't work: urls.py: urlpatterns = [ path('vk/callback/', views.vk_callback, name='vk_callback'), path('google/callback/', views.google_callback, name='google_callback') ] After successful authorization takes info from server: "GET /complete/google-oauth2/?state=Qw2iyDHL9w6ueu4aKU8cfx7lC4VKjEgN&code=4%2F0AbUR2VMMND7R2atmHBSbfGxtlbRBzTwiMnsiSpcYAmLI2cQeKuK7D1b_iUJ6uc2Pgp863w&scope=email+profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.ema il+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&authuser=0&prompt=none HTTP/1.1" 302 0 -
Django-Huey 'NoneType' object is not callable
I keep getting an error each time I run Django-Huey queue. I have set up DJANGO_HUEY using greenlet worker. ##django sttings.py DJANGO_HUEY = { 'default': 'files', #this name must match with any of the queues defined below. 'queues': { 'files': {#this name will be used in decorators below 'huey_class': 'huey.RedisHuey', 'name': 'files_tasks', 'immediate': False, 'consumer': { 'workers': 50, 'worker_type': 'greenlet', }, }, } ##tesk @db_task(queue='files') def process_file(): #... file processing #error venv\Lib\site-packages\huey\consumer.py", line 210, in get_stop_flag return GreenEvent() TypeError: 'NoneType' object is not callable. How can I fix this error. -
Django - insert model reference in static location
I am working on a new Django-application and wanted to insert a reference to staticfiles from the model I've created. Model: url=testname I want to insert this name into an image url through static: {% static 'folder/testname.png' %} Is there any way I can insert this, like inserting model.url? -
Not being able to Migrate new app because 'Migration admin.0001_initial is applied before its dependency userSocial.0001_initial on database 'default'
I created a Django root, where I created one app to access my database and created all the necessary models, serializers, views and urls to access it as an API on my web app. After finishing that Django App with a PostgreSQL DB and a Web App. I wanted to create 2 new Apps in the same root to access the same database but for a different use scenario and a different Web App. The first one has the ability to do everything View, Delete and Update my database, this next two apps are for creating Users and creating a small Social Media with posts and comments. However after getting the UserModel ready and set up the models for the Social Media App, I am getting this error: PS C:\codeacademy\O_lar\o_lar_db> python manage.py migrate Traceback (most recent call last): File "C:\codeacademy\O_lar\o_lar_db\manage.py", line 22, in <module> main() File "C:\codeacademy\O_lar\o_lar_db\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\rodil\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\rodil\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\rodil\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\rodil\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rodil\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\base.py", line 106, in wrapper res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\rodil\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\migrate.py", line 120, … -
Django template variables rendered after 403
I have an HTML template which will render button depending on context variable. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post"> {% csrf_token %} <button type="submit">{{ number }}</button> </form> </body> </html> After passing "if" check for numbers greater than 400, the function should return response 403 and stop. But in my case it only ignores a template and still renders a context variable. def run_script(request, number): if number > 400: return HttpResponseForbidden() context = {'number': number} return render(request, "mainapp/number.html", context) The only solution I found is so set the rendered value to null in the "if" statement if number > 400: number = None return HttpResponseForbidden() This way I get proper response 403, but I dont like this method since it requires changing every variable, when multiple provided and doesn't look like a proper implementation. Any suggestion how to properly stop execution on response 403? -
Django ModelForm is_valid method always false
i'am getting an error using Django ModelForm. The method form.is_valid is always false and i don't understand why. After have put all the values in the form it doesn't enter inside the method and then nothing happens when i press the submit button. This is my code. ** models.py ** class Product(models.Model): image= models.ImageField(blank=True, null=True) name= models.CharField(max_length=200) type=models.CharField(max_length=30) product_code=models.CharField(max_length=20, unique=True) productor= models.CharField(max_length=50) color= models.CharField(max_length=40) size=models.CharField(max_length=100) weight=models.FloatField(default=0) full_price= models.FloatField(default=0) discount=models.PositiveIntegerField(default=0) final_price=models.FloatField(default=0) quantity= models.PositiveIntegerField(default=0) supplier= models.ForeignKey(User,on_delete=models.CASCADE) #Utente staff che ha inserito il prodotto recensioni = models.ManyToManyField(Recensione) def __str__(self): return self.nameclass Computer(Product): display_size= models.FloatField(default=0) display_resolution= models.CharField(max_length=20) cpu= models.CharField(max_length=50) ram= models.PositiveIntegerField(default=0) disk_size= models.FloatField(default=0) disk_type= models.CharField(max_length=20) operating_system= models.CharField(max_length=100) graphic_card= models.CharField(max_length=50) battery_autonomy= models.FloatField(default=0) additional_function= models.CharField(max_length=1000) ** forms.py ** class ComputerForm(forms.ModelForm): class Meta: model=Computer fields=['image','name','product_code','productor','color','size','weight','full_price','discount','quantity', 'display_size', 'display_resolution', 'cpu', 'ram', 'disk_size', 'operating_system', 'graphic_card', 'battery_autonomy', 'additional_function'] ** views.py ** #Aggiunta nuovo Prodotto @login_required def add_product(request,category): templ="products/product_form.html" form=ComputerForm() if request.method == "POST": form=ComputerForm(request.POST, request.FILES ) #Controllo campi form siano validi if form.is_valid(): print("Valid") form.save() return redirect("products:all_products") return render(request,template_name=templ,context={"form":form}) ** product_form.html ** <div class="col-4" style= "width:30%;right:+20px;"> <h3> <b> Dati prodotto: </b> </h3> <form method='POST'> {% csrf_token %} {% crispy form %} <br> <input type="submit" class="btn btn primary" style="background-color:blue;color:white;" value="Aggiungi Prodotto"> </form> </div> -
Django admin showing a white box instead of toggle theme icon
As I open Django admin page, a wide white box appears instead of the theme icon (using Django 4.2.1). While testing on Docker container, everything seems ok. I have been looking at the documentation on overriding admin/base.html, but I'm not sure this is the issue. Checking the log after deployment (on EC cloud), nothing comes to my attention. I am letting serve the static content by nginx (1.23). python manage.py collectstatic --noinput Overall, all static files are working properly on the rest of the site. I tried inspecting the element <button class="theme-toggle">. Nothing anomalous. Everything looks normal to me. Apart from this, production looks identical to the Docker container. -
Session storage Django, form parameters
I have two pages, my main index.html where I've put a call to action button to let the user to enter some text. When submitting it, I want the user to be redirected to the remaining part of the form, which is basically another form including the first parameter in the background. So, two different forms, but the second one sum up everything together and sends it to my Django server. Therefore, I need the information from my main form, to be communicated to my second form. In php it would be easy with links, how should I process with Django ? I've seen server session storage but I'm sure there is a more efficient way like with JS ? I just need to communicate the information from the first page form, to the second page so it can send it to my server as a whole. index.html <div class="form-container"> <form method="POST" action="form.html" class="form-post"> <input type="text" name="link" id="link" placeholder="Paste your link here" class="input-text"> <input type="submit" value="Submit" class="input-submit"> </form> </div> form.html how to retrieve the information id="link" from the index.html ? -
Привязка поста к user [closed]
У меня есть задача создать посты и привязывать их к модели текущего user. для это я создал модель поста: class Post(models.Model): title = models.CharField(max_length=100) text = models.TextField(null=True, blank=True) image = models.ImageField(upload_to='photos/%Y/%m/%d', null=True, blank=True) cat = models.ForeignKey(Category, on_delete=models.DO_NOTHING, default='test') user = models.ForeignKey(User, on_delete=models.DO_NOTHING) def __str__(self): return self.title мне нужно в форме вводить title, text, image, а user должен подставляться сам. То есть текущий пользователь. Как это сделать? Я создал форму: class PostF(forms.Form): user = forms.IntegerField(label='user', required=False) title = forms.CharField(max_length=100) text = forms.CharField(widget=forms.Textarea()) image = forms.ImageField() И Views: def PostV(request): form = PostF data = { 'user': User.objects.get(pk=request.user.pk), 'title': request.POST.get('title'), 'text': request.POST.get('text'), 'image': request.POST.get('image') } form = PostF(data) if form.is_valid(): Post.objects.create(**form.cleaned_data) return redirect('home') return render(request, 'main/createpost.html', {'form': form}) Но это не сработало. -
Pagination not using correct values when using order by in Django Rest Framework
I have a very simple ListAPIView: class MyListView(ListAPIView): pagination_class = QueryParamPagination serializer_class = MyListSerializer queryset = MyObject.objects.all() with a simple class to define the pagination: class QueryParamPagination(PageNumberPagination): page_size = 2 page_size_query_param = "page_size" max_page_size = 27 However in this scenario I will get a warning, because the result is not ordered: inconsistent results with an unordered object_list: <class 'models.MyObject'> MultilingualSoftDeleteQuerySet. Which is fine ... Now changing the last line to queryset = MyObject.objects.order_by('name').all() gets rid of the warning, however now my pagination is not working anymore. Django now uses some super defaults, all values in QueryParamPaginationare ignored, but also my global settings REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 2, } I have no idea why this is happening ... anyone with any insights? Thanks! -
NoReverseMatch at /abampdb/get/ in django
i am encountering a problem Exception Type: NoReverseMatch Exception Value: Reverse for 'show-protein' not found. 'show-protein' is not a valid view function or pattern name. <form method="GET" action=""> 74 <label for="q">Search:</label> 75 <input type="text" name="q" value="{{ request.GET.q }}" placeholder="Enter search keyword"> 76 <button type="submit">Search</button> {{ form.as_p }} 77 78 <input type="text" name="q" placeholder="Search..."> 79 <tbody> 80 {% for protein in protein_list %} 81 82 <tr> 83 <td><a href="{% url 'show-protein' %}">{{ protein }}</a></td> 84 <td>{{ protein.weight }}</td> 85 <td>{{ protein.hydroph }}</td> 86 <td><input type="radio" name="name" value="{{ protein.name }}"></td> 87 <td>{{ protein.name }}</td> 88 {% endfor %} urls.py from django.contrib import admin from django.urls import path from .import views from .views import * app_name = "abampdb" urlpatterns = [ path('get/', views.get_search_results, name='get-list'), path('show_protein/<protein_id>', views.show_protein, name='show-protein'), ] -
Modelform 'bool' object is not iterable
I am trying to save a boolean field in a model form. I get the type error 'bool' object is not iterable and I'm not quite sure why. I stupidly assumed django just handled the fact that the boolean value is saved as a string in the database(PostgreSQL) because it did successfully after a signal saved it initially after a new user signed up. After a bit of research and trial and error, I'm at loss here. Any advice would be appreciated. class SundayBoolAvailable(models.Model): teacher_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, default='', related_name='teacher_bool_available_id') sunday_bool = models.BooleanField(null=False, default=True) class SundayTime(models.Model): teacher_id_time = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, default='', related_name='teacher_time_available_id') sun_from_hour = models.TimeField(choices=HOUR_CHOICES, null=True, blank=True) sun_to_hour = models.TimeField(choices=HOUR_CHOICES, null=True, blank=True) def __str__(self): return str(self.teacher_id) class SundayBoolForm(forms.ModelForm): sunday_bool = forms.BooleanField(required=False) class Meta: model = SundayBoolAvailable fields = ['sunday_bool', ] # widgets = { # 'sunday': forms.HiddenInput(), # } def __init__(self, *args, **kwargs): super(SundayBoolForm, self).__init__(*args, **kwargs) self.fields['sunday_bool'].required = False class SundayTimeForm(forms.ModelForm): class Meta: model = SundayTime fields = ['sun_to_hour', 'sun_from_hour'] # widgets = { # 'sunday': forms.HiddenInput(), # } SundayInlineFormSet = inlineformset_factory(MyUser, SundayTime, form=SundayTimeForm, extra=0, can_delete=True, min_num=0, validate_min=True, max_num=3, validate_max=True, fields=['sun_to_hour', 'sun_from_hour']) @login_required() @teacher_required def availability_update_view(request, pk, *args, **kwargs): sun_obj = get_object_or_404(MyUser, id=pk) if request.method == … -
getting length error when i try to migrate in django
` File "C:\Users\akash\Desktop\django project\Cactus\Cactusenv\Lib\site-packages\django\db\utils.py", line 91, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\akash\Desktop\django project\Cactus\Cactusenv\Lib\site-packages\django\db\backends\utils.py", line 87, in _execute return self.cursor.execute(sql) ^^^^^^^^^^^^^^^^^^^^^^^^ django.db.utils.DataError: value too long for type character varying(30) ` -
Django 3-table join orm
`Model Ship address = models.ForeignKey(Address, related_name='builtship') Model Photos ship = models.ForeignKey(Ship, related_name="photoship" ` While I can easily join ship with the Address model, as it has its related name inside ship, I can't join it with Photos because it doesn't have it. So, to join with Address I did: q1= ship.objects.select_related('address') but I have tried for the entire Sunday and I couldn't write it orm style. I wrote it in 2 minutes in raw SQL but I want to know how to link ship with photos too in one query so that I can fetch all of the values and list them in a table. Naturally I can't place the foreign key to photos in ship because every ship has many possible pictures, so it has to go from photos to ship. I have already written what I tried