Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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> -
Django forms widgets Textarea is directly set to type hidden but need it visible
My problem is i set a form from a model to change the value of the field "description" of this model : Model : class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) birth_date = models.DateField(null=True, blank=True) profile_img = models.ForeignKey(Image,on_delete=models.CASCADE,related_name='images',null=True) description = models.TextField() Form : class ChangeUserDescription(ModelForm): class Meta: model = Profile fields = ['description'] widgets = { 'description': forms.Textarea() } labels = { 'description':'Description' } But in result of this code I obtain this : <input type="hidden" name="csrfmiddlewaretoken" value="brsd4oO0qhMw2K8PyCIgSgEMqy7QFvEjTHaR6wTJmyWffJaCX5XyOMDLrGldZ3ji"> <button type="submit">Save changes</button> The issue is that i get : type="hidden" in the input whereas i want it to be visible and i do not specified in the widgets that it must be hidden. -
Trying to add a comment section form to my Django app
I get 2 different errors the first one is Django Model IntegrityError: NOT NULL constraint failed: I checked the solution for this, people said I've to make my FK attributes null = true and blank = true so this solved that. The second error I got after that was in my views.py 'CommentForm' object has no attribute 'cleaned_data' My Views.py file: def project(request, pk): form = CommentForm() project = ProjectModel.objects.get(id=pk) contextt ={ "project": project, "form":form, } if request.method == "POST": form.save() return redirect(request, "/dashboard") else: return render(request, "projects.html", contextt) and my Models.py: class ProjectModel(models.Model): caption = models.CharField(max_length=100) video = models.FileField(upload_to="video/%y", validators=[file_size]) ProjectName = models.CharField(max_length=50, ) ProjectDescription = models.TextField(max_length=1000,) Project_Background_picture = models.ImageField( upload_to=settings.MEDIA_ROOT, default='/static/img/default.png') Approved = models.BooleanField(default=False) Finished = models.BooleanField(default=False) Goal = models.DecimalField( decimal_places=3, max_digits=6, blank=True, null=True) Pledges = models.DecimalField( decimal_places=3, max_digits=6, blank=True, null=True) Number_of_investors = models.IntegerField(blank=True, null=True) FirstReward = models.TextField(max_length=1000, default=' 10$ ') SecondReward = models.TextField(max_length=1000, default=' 25$') ThirdReward = models.TextField(max_length=1000, default='50$') FourthReward = models.TextField(max_length=1000, default='100$ +s') def __str__(self): return self.caption class comment(models.Model): ProjectModel = models.ForeignKey( ProjectModel, related_name='comments', on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=255) CommentBody = models.TextField(default='comment here!', max_length=1000 ) date_added = models.DateTimeField(auto_now_add=True) def _str_(self): return '%s - %s' % (self.ProjectModel.caption, self.name) -
NoReverseMatch at / Reverse for 'profile' with arguments '('',)' not found. 1 pattern(s) tried: ['profile/(?P<name>[^/]+)/$']
I am a beginner in learning code and am working on making a simple django site where users can write comments but I keep getting this error My urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("profile/<str:name>/", views.profile, name="profile") ] views.py class NewPostForm(forms.Form): title = forms.CharField(label="Title") description = forms.CharField(widget=forms.Textarea) def index(request): if request.method == "POST": form = NewPostForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] description = form.cleaned_data['description'] author = request.user post = NewPost(title=title, description=description, author=author) post.save() return HttpResponseRedirect(reverse("index")) else: return render(request, "network/index.html", { "form": form }) return render(request, "network/index.html", { "form": NewPostForm(), "posts": NewPost.objects.all() }) models.py from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class NewPost(models.Model): title = models.CharField(max_length=32) description = models.CharField(max_length=256) author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) and my index.html {% extends "network/layout.html" %} {% load static %} {% load crispy_forms_tags %} {% block body %} <div class="form-group"> <form method="post" action="{% url 'index' %}"> {% csrf_token %} {{form | crispy}} <button class="btn btn-primary"> Post </button> </form> </div> {% for post in posts %} <div class="card"> <div class="card-body"> Title: {{post.title}} </div> <div class="card-body"> Description: {{post.description}}</div> <p> {{post.author.username}} </p> <div class="card-body"> <a href="{% url … -
Group by column Django orm
I have a database table users that consists of 4 columns id,name,country,state I will like to run an sql query like SELECT id,name,state,country FROM users GROUP BY country please how do i accomplish this using Django ORM -
Django app RANDOMLY losing connection to Postgresql database
I've been looking everywhere but cannot seem to find anyone with my same problem. Here's my situation... Django App: Running on Centos7 Vagrant guest 10.0.0.2 connecting to DB Postgresql-10 DB: Running on Centos7 Vagrant guest 10.0.0.1 serving the Django app, also has pgAdmin4 running on it When I bring these vagrant machines up they are able to initially connect. I notice when I leave them idle for periods of time then the Django app cannot connect any longer to the DB. Even weirder, most of the time, but not all the time, I simply needed to restart the postgresql database service and it would be able to connect again. Right now that's not even the case so I can no longer ignore this problem by just restarting the DB service. Any ideas on what could be going on here? I've tried a couple things but nothing seems to work. My feeling is it's something on the database machine causing issues since like I said usually this just required a simple restart of the DB service to fix. I'm completely confused by how it just loses connection sometimes randomly. -
Django multi tenant database error on generic models
My current application is multi tenant, so I manage one schema by user, There are many parts on my app where the user can add comments, so I decided to use a generic model, something like this: class Comment(models.Model): date = models.DateTimeField( _('Date'), blank=False, auto_now=True, db_index=False ) comment = models.TextField( _('Comment'), blank=False, null=False ) user = models.ForeignKey( 'security.User', related_name='comments', verbose_name=_('User'), on_delete=models.CASCADE, ) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() It works well with a single user/schema it saves the comments correctly, but when I logged-in with a different user and tried to save a comment throw me the next error: Traceback (most recent call last): File "/home/jsalvad0r/.pyenv/versions/mytaskpanel/lib/python3.6/site-packages/django/db/backends/utils.py", line 87, in _execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: insert or update on table "generic_comment" violates foreign key constraint "generic_comment_content_type_id_068f197c_fk_django_co" DETAIL: Key (content_type_id)=(2) is not present in table "django_content_type". The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/jsalvad0r/.pyenv/versions/mytaskpanel/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/jsalvad0r/.pyenv/versions/mytaskpanel/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/jsalvad0r/.pyenv/versions/mytaskpanel/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/jsalvad0r/.pyenv/versions/mytaskpanel/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/jsalvad0r/.pyenv/versions/mytaskpanel/lib/python3.6/site-packages/rest_framework/viewsets.py", line 116, in view return … -
Trigger javascript function from Django server
I am working on IPN's. Whenever I receive an IPN in this url: https://www.mywebsitename.com/notifications, I would like to run a simple JavaScript function that displays some html content. I manage the IPN's from the server side, as follows: @csrf_exempt def notifications(request): if request.method == "POST": #some code I would like to trigger my JS function inside that block of code, but I can't come up with any way of doing this. Also I don't really know wether what I am asking is really possible or not, maybe there is another approach that I can't figure out by myself. -
How to iterate through Django model items in a ManyToManyField
Brand new to Django/Python and thought I'd start by building a simple blog app. I would like the User to be able to post book references that include the book name and a link to the book. My current References class in my models.py looks like this: class References(models.Model): link = models.URLField(max_length=150, default=False) title = models.CharField(max_length=100, default=False) def __str__(self): return self.title and my Post class looks like this: class Post(models.Model): title = models.CharField(max_length=31) content = models.TextField() thumbnail = models.ImageField() displayed_author = models.CharField(max_length=25, default=True) shortquote = models.TextField() reference_title = models.ManyToManyField(References) 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 def get_absolute_url(self): return reverse("detail", kwargs={ 'slug': self.slug }) def get_love_url(self): return reverse("love", kwargs={ 'slug': self.slug }) @property def comments(self): return self.comment_set.all() @property def get_comment_count(self): return self.comment_set.all().count() @property def get_view_count(self): return self.postview_set.all().count() @property def get_love_count(self): return self.love_set.all().count() I understand that i'm only returning the title in my References class, I've tried returning self.title + self.linkbut this gives me both the title and link together when being called in the template. My template calling the references class looks like this: {% for title in post.reference_title.all %} <a href="{{ link }}"> <li>{{ title }}</li> </a> {% endfor … -
django registration and login on the same page
i would like to have both my login form and my registration form on the same page within the same template, so i would like to have them under one view function but i am not too sure on how i can do that, here is my views file #views.py def register(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, ' Account was created for ' + username) return redirect('login') context = {'form': form} return render(request, 'register.html', context) @unauthenticated_user def loginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('index') else: messages.info(request, 'username or password is incorrect') context = {} return render(request, 'login.html', context) -
Unknown command: 'auth' Type 'manage.py help' for usage
I'm using django 3.1 and I'm unable to fix this issue. I'm running following command heroku run python manage.py auth zero. and getting this in return : Running python manage.py auth zero on ⬢ dotescrow... up, run.1867 (Free) Unknown command: 'auth' Type 'manage.py help' for usage. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'django_countries', 'bootstrap3', # 'wallets', # 'frontend', ] -
python Django db utils programming error (1064)
django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'json NOT NULL, category_json json NOT NULL)' at line 1") occurs during the database migrations in python sharehosting -
Does Django use case sensitive filenames for FileField with MySQL backend?
I'm using Django 3.1.3 and have a model with a FileField field. When I upload a file with same name, but different case, the logic I have is reporting that it is a duplicate. For example: Files <QuerySet ['92/565/20191222_152213.jpg', '92/565/cs_731__DSC8110.jpg', '92/565/ADs-2.MP4']>, this 92/565/ADS-2.mp4 The logic is... other_pieces_in_room = Piece.objects.filter(room__id=self.room_id) other_files_in_room = other_pieces_in_room.values_list('file', flat=True) mylog.debug("Files {}, this {}".format(other_files_in_room, file.name)) if file.name in other_files_in_room: raise forms.ValidationError("...") Model (relevant fields) is: class Piece(models.Model): file = models.FileField(upload_to=media_location) room = models.ForeignKey(Room, on_delete=models.CASCADE) Any thoughts as to what is going on? -
sqlite3.OperationalError: no such table: django_site__old
I'm trying to make a webpage using python and mezzanine as its cms. but I got this error after successfully creating Superuser: Superuser created successfully. Traceback (most recent call last): File "C:\Python39\lib\site-packages\django\db\backends\utils.py", line 62, in execute return self.cursor.execute(sql) File "C:\Python39\lib\site-packages\django\db\backends\sqlite3\base.py", line 326, in execute return Database.Cursor.execute(self, query) sqlite3.OperationalError: no such table: django_site__old The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\annie\Documents\DMCproject\manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "C:\Python39\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Python39\lib\site-packages\django\core\management\__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python39\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python39\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Python39\lib\site-packages\mezzanine\core\management\commands\createdb.py", line 61, in handle func() File "C:\Python39\lib\site-packages\mezzanine\core\management\commands\createdb.py", line 109, in create_pages call_command("loaddata", "mezzanine_required.json") File "C:\Python39\lib\site-packages\django\core\management\__init__.py", line 131, in call_command return command.execute(*args, **defaults) File "C:\Python39\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Python39\lib\site-packages\django\core\management\commands\loaddata.py", line 69, in handle self.loaddata(fixture_labels) File "C:\Python39\lib\site-packages\django\core\management\commands\loaddata.py", line 115, in loaddata connection.check_constraints(table_names=table_names) File "C:\Python39\lib\site-packages\django\db\backends\sqlite3\base.py", line 276, in check_constraints cursor.execute( File "C:\Python39\lib\site-packages\django\db\backends\utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "C:\Python39\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Python39\lib\site-packages\django\db\utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "C:\Python39\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Python39\lib\site-packages\django\db\backends\utils.py", …