Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework: use create with primary key in URL
I can't apply the @action decorator to create function within a standard views.Viewset subclass. @action(detail=True) # This fails. def create(self, request, pk=None): return Response(etc...) On other methods, adding that decorator allows me to create URLs easily with <pk> within the URL. For example, I can send a POST request to http://main_url.com/do_something_to_user_with_id/7/, with do_something_to_user_with_id being some random function within the viewset and 7 being the user id/primary key. Is there any way I can do this with create? -
how to inherit slug form one class to other in django models
my models.py file is: class Product(models.Model): title = models.CharField(max_length=110) slug = models.SlugField(blank=True, unique=True) price = models.DecimalField(decimal_places=2, max_digits=6) discount_price=models.FloatField(blank=True, null=True) size = models.CharField(choices=SIZE_CHOICES, max_length=20) color = models.CharField(max_length=20, blank=True, null=True) image = models.ImageField(upload_to=upload_image_path) description = models.CharField(max_length=1000) featured = models.BooleanField(default=False) author = models.ForeignKey(User, on_delete=models.CASCADE) time_stamp = models.DateTimeField(auto_now_add=True) objects=ProductManager() def get_absolute_url(self):#i use this in product_list.html to go to detail page #return "/product/{slug}".format(slug=self.slug) return reverse("products:detail", kwargs={"slug" : self.slug}) def __str__(self): return str(self.title) @property def name(self): #sometime in html i say name istead of title so to make it work i wrote this return self.title def product_pre_save_reciever(sender, instance, *args, **kwargs):#i inherit unique slug generator from utils to here so when i create aa new instance it slug automatically generate. and i i create two t shirts it give a random straing to tshirt 2nd slug if not instance.slug: instance.slug=unique_slug_generator(instance) pre_save.connect(product_pre_save_reciever, sender=Product) class Comment(models.Model): product=models.ForeignKey(Product , related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=255) body=models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s'%(self.product.title, self.name) i want the slug field to inherit it into comments because the comments must me on their specific post . when i run the server and post comment it is posting comment on specific post but gave me the error that Comment has no attribute … -
I can't display data in django template
So, i can't display data from my model in this template. In base.html it works great, but in this template is not working. I see too much posts on this site and i cant solve my problem. I write the render in too many ways but don't work and i'dont understand Stack overflow don't let me send this post because i don't write too much text so the next random text is for fill the post and send it: ldgnsldngasilhhhhhhhhhhhhhhhhhhandñvkjasnaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaarkjasbgkjbdkjgvbsrkhbgusenvgkrhgkuasdngkjasdkudsgnkasduglaiuskgblksadubgaskudgbsakudgbsadkugbksaudgbsakugasiudbgusbdguasidbguksakuksudliuabgkusbligubrsuguraegnfskudhbrsauibgasurghasidongusadghsidlgnsudghsidlgnsdlñailsdgnuahñilnebwureñgbsegbuksdghesngukrsgbs2gbsyiughbsebgruighbesabguiwghndslgksurghsidlngkuwehaneslgbaksugnsdjkbsaekgsuegblseskuegsbgkubue views.py from django.http import HttpResponse from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post, PostView, Like, Comment class PostListView(ListView): model = Post class PostDetailView(DetailView): model = Post class PostCreateView(CreateView): model = Post class PostUpdateView(UpdateView): model = Post class PostDeleteView(DeleteView): model = Post def change_view(request): todo = Post.objects.all context = { 'todo': todo } return render(request, "index.html", context) models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.shortcuts import reverse from ckeditor.fields import RichTextField class User(AbstractUser): pass def __str__(self): return self.username class Post (models.Model): title = models.CharField(max_length=100) content = RichTextField(blank=True, null=True) thumbnail = models.ImageField() publish_date = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField() def __str__(self): return self.title return render(request, … -
Why I need Docker Compose? and For what i use it in web development?
I have searched these questions in the internet, unfortunately I am not satisfied with the results. And the last question what is the docker container? -
Import function from another file in same folder
I know this question has been asked many times in other posts, but I can't to solve it with the answers provided. I am creating a Django app in which I have a .py file with some functions that I want to import in another file and use them. This is the code of the function to import (in helpers.py): from requests.exceptions import HTTPError def cargar_api(url): for url in [url]: try: response = requests.get(url) response.raise_for_status() except HTTPError as http_err: print(f"Ocurrió un error HTTP: {http_err}") except Exception as err: print(f"Ocurrió otro error: {err}") else: print("API cargada") data = response.json() return data And this is the code where I want to import it, the file (service.py) is in the same folder and helpers.py: import requests from requests.exceptions import HTTPError import os from .helpers import cargar_api WEATHER_API_KEY = os.environ.get("WEATHER_API_KEY") # funcion que da todos los datos del clima segun las coordenadas # adicionalmente agrega un key "recomendacion" para alertar al usuario de precauciones a tomar antes de salir # informacion de cada dato de la API: https://www.weatherbit.io/api/weather-current # diferentes opciones de descripciones y logos aqui: https://www.weatherbit.io/api/codes def info_clima(latitud, longitud): url_clima = f"https://api.weatherbit.io/v2.0/current?lat={latitud}&lon={longitud}&key={WEATHER_API_KEY}" info_clima = cargar_api(url_clima)["data"][0] descripcion_clima = info_clima["weather"]["description"] if ( "Thunderstorm" in descripcion_clima … -
Profile fails to get created for a New Registered User in Django
I'm working on a new Django project to get students registered and to get a profile created for each student after the registration. I get an error when the user register. ERRO ValueError at /students/register/ Cannot force both insert and updating in model saving. Below are my code snippets: models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png', upload_to='students/profile_pics') bio = models.TextField(null=True, blank=True, verbose_name='biography') def __str__(self): return f'{self.user.username} Profile' 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) views.py def register_student(request): if request.method == 'POST': form = StudentRegistrationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('student_course_list') else: form = StudentRegistrationForm() return render(request, 'students/student/registration.html', {'form': form}) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class StudentRegistrationForm(UserCreationForm): email = forms.EmailField(help_text='Enter a valid email address') class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] urls.py from .views import register_student urlpatterns = [ ### path('register/', register_student, name='student_registration'), ] signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile … -
How do link a file user uploaded to Database?
This is how I was saving user uploaded Files: f = request.FILES[x] s = File(file=f, user=curUser) s.save() This worked great but it took a lot of bandwidth on my server so I decided to use pre-signed urls. Now users upload directly to s3 Bucket, however it's not linked to Database. I tried this which runs after user successfully uploads to S3: f = default_storage.open(userID + "/" + fileName) curUser = User.objects.get(userID=userID) s = File(file=f, user=curUser) s.save() f.close() However, this is just creating a new folder on users directory and uploading it there. my Models: class User(models.Model): userID = models.CharField(max_length=101,primary_key=True) class File(models.Model): user = models.ForeignKey(to=User, on_delete=models.CASCADE) file = models.FileField(max_length=255, upload_to=user_directory_path) def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> path = instance.user.userID + "/" + filename return path -
ValueError: source code string cannot contain null bytes django
Whenever I try to run the server these error is popping up. Yesterday it was working fine. Tried for a long but don't get any solution for that. If anybody has any idea regarding this error this, Please let me know. Thankyou in advance, It will be kindful if you could do the needful. -
URL keeps on getting added after editing the form (Django)
I have got a problem while redirecting to the edit form. SO what I am doing is that whenever user clicks on edit button it redirects to "editadmin/{{admin.id}}" using form action = "editadmin/{{admin.id}}" in HTML. URL path is path("editadmin/<int:id>", views.editadmin, name="editadmin") path("updateadmin/<int:id>", views.updateadmin, name="updateadmin") Views.py @csrf_exempt def editadmin(request, id): admin = Admin.objects.get(id=id) return render(request, "editadmin.html", {"admin": admin}) @csrf_exempt def updateadmin(request, id): if request.method == "POST": admin_id = request.POST["admin_id"] admin_id = str(admin_id).strip().upper() name = request.POST["name"] name = str(name).strip() if db_name equals to name: messages.error(request, "Admin name already exists") return redirect("editadmin/" + str(id)) editadmin.html <form method="post" class="post-form" action="/update/{{admin.id}}"> <input type="hidden" name="id" id="id" required maxlength="20" value="{{ admin.id }}"/> {% csrf_token %} <div class="form-group row"> <label class="col-sm-3 col-form-label"><h4 style="margin-left:40px">Admin ID : </h4></label> <div class="col-sm-4"> <input type="text" name="admin_id" required style="margin-left:20px; height:38px; width:300px; border-radius: 5px" id="admin_id" value="{{ admin.admin_id }}"/> </div> </div> <div class="form-group row"> <label class="col-sm-3 col-form-label"><h4 style="margin-left:40px">Name : </h4></label> <div class="col-sm-4"> <input type="text" name="name" style="margin-left:20px; height:38px; border-radius: 5px; width:300px" required id="name" value="{{ admin.name }}"/> </div> </div> <div class="form-group row"> <label class="col-sm-1 col-form-label"></label> <div class="col-sm-4"> <button type="submit" class="btn btn-success" style="margin-left:210px">Submit</button> </div> </div> So what I want is that Whenever user submits invalid name in editadmin.html (URL - editadmin/1 ), it should redirect to the same URL … -
How to display particular stuff of the registered person in profile page - Django
I have a member table, I want to fetch and display some of the fieldsets like fullname , email and phone number in the profile page. i had tried some of the codes using object.all() as well as using primary keys but i don't get the desired output . Thank you in advance i will we kindful if you could do the needful -
Give access to Django Admin (staff status) by adding to Group
To give a user the ability to login to the Django Admin, we set their staff flag. Is there a way to make a "staff" Group where everyone put into it gains access to the admin page without manually setting staff status? -
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration is applied before its dependency accounts.0001_initial on database 'default'
I'm trying to migrate my coustom user model but when i run makemigrations command that makes new models for migration. But when i run migrate command it throws error : django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on database 'default'. traceback Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\AHMED\anaconda3\envs\dotesrow\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\AHMED\anaconda3\envs\dotesrow\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\AHMED\anaconda3\envs\dotesrow\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\AHMED\anaconda3\envs\dotesrow\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Users\AHMED\anaconda3\envs\dotesrow\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\AHMED\anaconda3\envs\dotesrow\lib\site-packages\django\core\management\commands\migrate.py", line 95, in handle executor.loader.check_consistent_history(connection) File "C:\Users\AHMED\anaconda3\envs\dotesrow\lib\site-packages\django\db\migrations\loader.py", line 302, in check_consistent_history raise InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on database 'default'. models.py class User(auth.models.AbstractUser): current_balance = models.IntegerField(("current balance"),default=0,blank=True) age = models.IntegerField(("age"),null=True) gender = models.CharField(("gender"), max_length=50,choices=GENDER_CHOICES,null=True) nationality = models.CharField(("nationality"), max_length=50,null=True) def __str__(self): return "@{}".format(self.username) I just mentioned user model in this question but still if more code is require then tell me i'll update my question with that information . Thank you -
ESP8266 with localhost
I have a django server running on localhost (127.0.0.1:8000), and I have trying to post sensor data to this url using ESP8266 but I can't connect with localhost keep getting connection failed message this is the code iam using in arduino #include <ESP8266WiFi.h> //#include <WiFiClient.h> //#include <ESP8266WebServer.h> const char* ssid = "ssid"; const char* password = "password"; const char* host = "127.0.0.1"; //String page = ""; double data; void setup(void){ pinMode(A0, INPUT); delay(1000); Serial.begin(115200); WiFi.begin(ssid, password); Serial.println(""); while (WiFi.status() != WL_CONNECTED){ delay(500); Serial.print("."); } Serial.println(""); Serial.print("Connected to"); Serial.println(ssid); Serial.print("IP address: "); Serial.println(WiFi.localIP()); } void loop(void){ WiFiClient client; const int httpPort = 8000; if (!client.connect(host, httpPort)) { Serial.println("connection failed"); delay(1000); return; } data = analogRead(A0); Serial.print("Requesting POST: "); // Send request to the server: client.println("POST / HTTP/1.1"); client.println("Host: server_name"); client.println("Accept: */*"); client.println("Content-Type: application/x-www-form-urlencoded"); client.print("Content-Length: "); client.println(String(data).length()); client.println(); client.print(data); delay(500); if (client.connected()){ client.stop(); } Serial.println(); Serial.println("closing connection"); delay(5000); } -
can I use input search in django form as as variable for a regular expression? not working now
def get_search(request,search, list): str1 = " " entries = str1.join(list) pattern = re.compile(r'{}.*.format(search)', re.IGNORECASE) matches = pattern.finditer(entries) -
Authentication problem while login with Custom User Model in Django
I created a custom user Model, that uses the Email field as the username. Also I had to create a Custom backend to validate as Case Insensitive the email field. The Registration page works perfectly fine, but when I try to login with a user that is not created I get this error: Environment: Request Method: POST Request URL: http://localhost:8000/members/login/ Django Version: 3.1.4 Python Version: 3.8.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', 'projects', 'about', 'blog', 'contact', 'members', 'ckeditor', 'django_bleach'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/daniel/MEGA/my-git/github/Developer-Road-Website/Developer-road-website/DeveloperRoad/members/backends.py", line 14, in authenticate user = UserModel._default_manager.get(**{case_insensitive_user_name_field: username}) File "/home/daniel/MEGA/my-git/github/Developer-Road-Website/Developer-road-website/venv/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/daniel/MEGA/my-git/github/Developer-Road-Website/Developer-road-website/venv/lib/python3.8/site-packages/django/db/models/query.py", line 429, in get raise self.model.DoesNotExist( During handling of the above exception (BlogUser matching query does not exist.), another exception occurred: File "/home/daniel/MEGA/my-git/github/Developer-Road-Website/Developer-road-website/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/daniel/MEGA/my-git/github/Developer-Road-Website/Developer-road-website/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/daniel/MEGA/my-git/github/Developer-Road-Website/Developer-road-website/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/daniel/MEGA/my-git/github/Developer-Road-Website/Developer-road-website/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/daniel/MEGA/my-git/github/Developer-Road-Website/Developer-road-website/venv/lib/python3.8/site-packages/django/views/decorators/debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/home/daniel/MEGA/my-git/github/Developer-Road-Website/Developer-road-website/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/daniel/MEGA/my-git/github/Developer-Road-Website/Developer-road-website/venv/lib/python3.8/site-packages/django/utils/decorators.py", line … -
Delete User from db Django Rest_framework View function
I am pretty new to the django_restframework. I want to be able to delete users from the database when a DELETE request comes in. Here is my Views: class RetrieveUsersView(generics.ListCreateAPIView): """Retrieves all Users""" serializer_class = UserSerializer authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) queryset = get_user_model().objects.all() Here is my Serializer: class UserSerializer(serializers.ModelSerializer): """Serializer for the users object""" class Meta: model = get_user_model() fields = ('email', 'password', 'name') extra_kwargs = {'password': {'write_only': True, 'min_length': 5}} def create(self, validated_data): """Create a new user with encrypted password and return it""" return get_user_model().objects.create_user(**validated_data) def update(self, instance, validated_data): """Update a user, setting the password correctly and return it""" password = validated_data.pop('password', None) user = super().update(instance, validated_data) if password: user.set_password(password) user.save() return user Here is my Urls: urlpatterns = [ path('create/', views.CreateUserView.as_view(), name='create'), path('token/', views.CreateTokenView.as_view(), name='token'), path('me/', views.ManageUserView.as_view(), name='me'), path('all_users/', views.RetrieveUsersView.as_view(), name='all_users') ] From my understanding Django rest has built in classes that allow DELETE requests. However when I view the api on the local host I am only able to view all the registered users based on my RetrieveUsersView class. I would expect the url to be something like /api/users/all_users/1 Then delete that one. I am bit confused on how to get that functionality. -
How to query on OneToOne relation of a related_name object in django
I have this model: class ProgramRequirement(Model): program = OneToOneField(Program, related_name='program_requirement') prereq_program = ForeignKey(Program, related_name='prereq_program_requirement') is_english_required = BooleanField() and this model class Program(Model): field_1 = ... field_3 = ... I need to write a query that would return the primary key of the programs of which is_english_required of the prereq_program is True. I tried this but it seems to be a wrong query: ProgramRequirement.objects.filter(prereq_program__prereq_program_requirement__is_english_required =True).values_list('program__pk', flat=True) However, it is not returning the correct result. Any idea how to do this/ -
How do I make a User Profile form using OnetoOneField extending the User Model?
I would like to make a form that extends the User Model using OnetoOneField. It would basically be a form in which a user can add/update their information after they have registered. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) username = models.CharField(max_length=120) name = models.CharField(max_length=120) # max_length = required email = models.EmailField(max_length=120) paypal_id = models.CharField(max_length=120) bio = models.TextField(max_length=500, blank=True) def __str__(self): return self.user.username forms.py class UserProfileForm(forms.ModelForm): class Meta: model = Profile fields = ["username", "name", "email", "paypal_id", "bio"] views.py def userprofile_view(request): if request.method == 'POST': profile_form = UserProfileForm(request.POST) if profile_form.is_valid(): profile = profile_form.save(commit=False) profile.save() return redirect('account') else: profile_form = UserProfileForm() context = {'profile_form': profile_form} return render(request, 'accounts/account_create.html', context) template.html {% extends 'base.html' %} {% block content %} <form action="." method="POST"> {% csrf_token %} {{ profile_form.as_p }} <input type="submit" value="Save"/> </form> {% endblock %} I keep getting this error when I hit Save: (1048, "Column 'user_id' cannot be null") Is there any fix for this? -
loading instance of django model into modelform
after a long time of being able to always find my answers on here, I now need to actually ask my first question... I'm working on a form which takes an instance of a modal, loads it in there (is what it should do) after which the user can edit the contents and resave the thing. I have been trying for hours now to load this initial instance into my form. This form is a customized Modelform originating from the Child model, which can be found using the following url: path('register/child/add', ChildReg, name="Child_Reg"), : from django import forms from django.forms import ModelForm from django.forms.widgets import Select from django.db.models import Q from django.utils.translation import gettext_lazy as _ import datetime import re from apps.childreg.models import Parents, Child, Child_Reg_Info, Child class Child(models.Model): male = "MAN" female = "WOMAN" SEXES=[(male, _('male')),(female, _('female'))] id = models.AutoField(primary_key=True) ExternalId = models.IntegerField(blank=True, null=True) ChildId = models.IntegerField(null=True, blank=True) FirstName = models.CharField(_('childs first name'), max_length=50, blank=True, null=True) LastName = models.CharField(_('childs last name'), max_length=50, blank=True, null=True) FullName = models.CharField(_('childs full name'), max_length=100, blank=True, null=True) DateOfBirth = models.DateField(_('date of birth'), blank=True, null=True) Location = models.ForeignKey(Location, verbose_name=_('location of registration'), on_delete=models.CASCADE) Nation = models.ForeignKey(Nation, verbose_name=_('country of registration'), on_delete=models.CASCADE) Parents = models.ForeignKey(Parents, verbose_name=_('parents of the … -
Unsure why object being passed through as string
I have an autocomplete dropdown list that uses the list of cities from my database. I am using django-cities. I want to be able to display it as (city.name , city.country.name) in my HTML. But it says that city is a string. Could someone explain to me why in my destination_form.html that {{ city }} is a string and not a city object views.py def add_destination(request,trip_id): city_list = City.objects.all() dict = { 'city_list':city_list, 'trip_id':trip_id, } if request.method=="POST": print("Resquest: ") print(request.POST) city = request.POST['city'] print(city.country) return render(request,'trips/destination_form.html',dict) destination_form.html {% extends "trips/trip_base.html" %} {% load bootstrap3 %} {% block trip_content %} <h4>Add Destination!</h4> <form method="POST" id='destinanationForm' action="{% url 'trips:add_destination' trip_id=trip_id%}"> {% csrf_token %} <label for="city">City: </label> <input id="city" list="city_list" placeholder="Search City..." class="form-control" style="width:300px" name="city"> <datalist id="city_list"> {% for city in city_list %} <option value="{{ city }}" >{{city.name}} , {{ city.country.name }}</option> {% endfor %} </datalist> <label for="start_date">Start Date: </label> <input id="start_date" type="date" name="start_date" value="{{ start_date }}"> <label for="end_date">End Date: </label> <input id="end_date" type="date" name="end_date" value="{{ end_date }}"> <input type="submit" class="btn btn-primary btn-large" value="Create"> </form> {% endblock %} urls.py path('single_trip/<str:trip_id>/add_destination',views.add_destination,name='add_destination'), -
Posting to DB using django serializers
I am learning django rest framework and I seem to have a problem with my ForeignKey models and serializers. I have two models and two serializers Models class Clients(models.Model): client_public_key = models.CharField(max_length=100, default=generate_client_public_key, unique=True) client_name = models.CharField(max_length=100, unique=True, null=False) client_name_abbr = models.CharField(max_length=100, unique=True, null=True) created_by = models.IntegerField(default=1, null=False) #Has to be changed to foreign key created_at = models.DateTimeField(auto_now_add=True, null=False) class Meta: ordering = ["client_name"] class Users(models.Model): client = models.ForeignKey(Clients, on_delete=models.CASCADE) user_public_key = models.CharField(max_length=100, null=False, default=generate_client_public_key, unique=True) first_name = models.CharField(max_length=100, null=False) last_name = models.CharField(max_length=100, null=False) email = models.CharField(max_length=100, null=False, unique=True) cell = models.IntegerField( null=True) support_department = models.CharField(max_length=50, null=False) password = models.CharField(max_length=150, null=False) user_status = models.IntegerField(null=False) password_changed = models.IntegerField(default=0, null=False) last_login = models.DateTimeField(null=True) created_by = models.IntegerField(default=1, null=False) #Has to be changed to foreign key created_at = models.DateTimeField(auto_now_add=True, null=False) class Meta: ordering = ["first_name"] Serializers class ClientSerializer(serializers.ModelSerializer): class Meta: model = Clients fields = '__all__' read_only_fields = ('id','client_public_key') class UserSerializer(serializers.ModelSerializer): # client = ClientSerializer() # client = serializers.StringRelatedField() class Meta: model = Users depth = 1 fields = '__all__' read_only_fields = ('id','user_public_key') The problem is when I add depth=1 in my UserSerializer I get (1048, "Column 'client_id' cannot be null") error when posting data. What am I doing wrong? -
KeyError at /admin/login/ 'token'
After deploying my Django Application to Heroku I have found the following error: KeyError at /admin/login/ 'token' with the following trace: Environment: Request Method: POST Request URL: https://decide-picaro-authentication.herokuapp.com/admin/login/?next=/admin/ Django Version: 2.0 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'django_filters', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_swagger', 'gateway', 'authentication', 'base', 'booth', 'census', 'mixnet', 'postproc', 'store', 'visualizer', 'voting', 'social_django'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware') Traceback: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/contrib/admin/sites.py" in login 398. return LoginView.as_view(**defaults)(request) File "/app/.heroku/python/lib/python3.8/site-packages/django/views/generic/base.py" in view 69. return self.dispatch(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/decorators.py" in _wrapper 62. return bound_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/decorators.py" in bound_func 58. return func.__get__(self, type(self))(*args2, **kwargs2) File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/decorators.py" in _wrapper 62. return bound_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/decorators.py" in bound_func 58. return func.__get__(self, type(self))(*args2, **kwargs2) File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/decorators.py" in _wrapper 62. return bound_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/decorators.py" in bound_func 58. … -
Django + Gunicorn + Kubernetes: Website down few minutes on new deployment
I am having this issue with Django + Gunicorn + Kubernetes. When I deploy a new release to Kubernetes, 2 containers start up with my current image. Once Kubernetes registers them as ready, which they are since the logs show that gunicorn is receiveing requests, the website is down for several minutes. It just times out for roughly 7-10 minutes, until it's fully available again: The logs show requests, that are coming in and returning 200 responses, but when I try to open the website through the browser, it times out. Also health checkers like AWS Route53 notify me, that the website is not reachable for a few minutes. I have tried to many things, playing around with gunicorn workers/threads, etc. But I just can't get it working to switch to a new deployment without downtime. Here are my configurations (just the parts I think are relevant): Requirements django-cms==3.7.4 # https://pypi.org/project/django-cms/ django==2.2.16 # https://pypi.org/project/Django/ gevent==20.9.0 # https://pypi.org/project/gevent/ gunicorn==20.0.4 # https://pypi.org/project/gunicorn/ Gunicorn config /usr/local/bin/gunicorn config.wsgi \ -b 0.0.0.0:5000 \ -w 1 \ --threads 3 \ --timeout 300 \ --graceful-timeout 300 \ --chdir=/app \ --access-logfile - Kubernetes Config livenessProbe: path: "/health/" initialDelaySeconds: 60 timeoutSeconds: 600 scheme: "HTTP" probeType: "httpGet" readinessProbe: path: "/health/" … -
how to get current email in Django email template
in my code emails are sent to a group of email addresses with a link in html template and when user login into his email and click on the link i need to send the current email address via the this url to the function in views.py how can i do that? Thanks in advance! -
django sessions remember me
I am new to django and have not found a question corresponding to my entry level. And I just can't figure out how to work with sessions. I want to make a checkbox on login to remember me. After I registered in settings SESSION_EXPIRE_AT_BROWSER_CLOSE = True, you need to enter your username and password after closing the browser. How do I change this parameter using the "remember me" checkbox? Thank you views.py def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return redirect('/') else: messages.info(request, 'invalid credentials') return redirect('login') else: return render(request, 'prof/login.html') login.html <body> <div class="text-center mt-5"> <form style="max-width: 480px; margin: auto" method="post"> {% csrf_token %} <img src="https://logodix.com/logo/1713894.jpg" alt="" width="120" height="90" class="d-inline-block mt-4 mb-4" /> <p class="hint-text mb-3">Please sign in</p> <label class="sr-only" for="username"></label> <input type="login" name="username" class="form-control" placeholder="username" required autofocus /> <label for="password" class="sr-only"></label> <input type="password" name="password" class="form-control mt-2" placeholder="password" /> <div class="checkbox"> <label for="checkbox"> <input type="checkbox" name="checkbox" value="remember-me" /> remember me </label> </div> <div class="d-grid gap-2 mt-4"> <input type="Submit" class="btn btn-primary" value="sign in" /> </div> </form> <div class="messages"> {% for message in messages %} <h3>{{message}}</h3> {% endfor %} </div>