Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have an issue with i18n and custom error handling in Django
I am implementing custom error handling in Django, and I have an issue with the '404 Not Found' error. Essentially, when I access http://localhost:8000, I am redirected to the 404 error page. However, if I type http://localhost:8000/en/, I am redirected to the homepage. What I want to achieve is to be redirected to the homepage even by simply typing http://localhost:8000. In the main urls.py I've defined the urlpatterns in the following way: urlpatters = i18n_patterns( ... ) and handler404 = "baseApp.views.error_404" Do you have any suggestion? I tried changing LANGUAGE_CODE from "en-us" to "en" but it didn't work -
Sorting Many to Many relationship in django doesn't work
I've been trying to implement a sorting solution for so long and nothing has worked so far. I have a Email list and email model. There is a many to many relationship between them. Here's my model and serializer. Model.py from django.db import models from django_extensions.db.models import TimeStampedModel from users.models import User class Email(models.Model): email = models.EmailField(unique=True) first_name = models.CharField(max_length=50, blank=True) last_name = models.CharField(max_length=50, blank=True) def __str__(self): return self.email class EmailList(TimeStampedModel): user = models.OneToOneField(User, on_delete=models.CASCADE) emails = models.ManyToManyField(Email, related_name='email_lists') def __str__(self): return self.user.username Serializers.py class EmailSerializer(serializers.ModelSerializer): class Meta: model = Email fields = ('email', 'first_name', 'last_name',) class EmailListRetrieveSerializer(serializers.ModelSerializer): emails = EmailSerializer(many=True) class Meta: model = EmailList fields = ('emails', 'id') I tried to use OrderingFilter but it didn't work. I tried annotation. Same result. I used ChatGPT to come up with a solution he also couldn't give me the solution. Same solution would work on one to many relationship but not on many to many. Please help me figure out a view for this. Thanks a lot. -
post method not allowed in HitCountDetailView
Adding a Comment Form to Django Blog Post: Encountering "Method Not Allowed (POST)" Error this is my view class BlogDetailView(HitCountDetailView): http_method_names = ['get', 'post'] model = BlogModel context_object_name = 'blog_detail' template_name = 'main/single.html' count_hit = True # for show all post in the sidebar def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) blog = self.get_object() # Get the current blog post # Get the comments related to the current blog post comments = CommentModel.objects.filter(blog=blog,active = True) context['comments'] = comments context['blogposts'] = BlogModel.objects.filter(status = 'p')[:3] # Get blog posts for the sidebar # Pass the comment form to the context context['comment_form'] = CommentForm() return context def post(self, request, *args, **kwargs): blog_post = self.get_object() comment_form = CommentForm(request.POST) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.blog = blog_post comment.save() return redirect('app:mag_detail', slug=blog_post.slug) context = self.get_context_data(**kwargs) context['comment_form'] = comment_form return self.render_to_response(context) and this is template <h1>comment </h1> <form method="post" action="{% url 'app:mag_detail' slug=mag_detail.slug %}"> {% csrf_token %} {{ comment_form.as_p }} <button type="submit">Submit Comment</button> </form> how can i solve that? thanks I'm currently working on integrating a comment form into my Django blog post using a class-based view. My goal is to allow users to submit comments on each blog post. While the form is displayed correctly on the … -
Django admin login csrf error only on https
My django application is working fine both on locally and on server with http. But when I am enabling https for my domain it stops working and giving me csrf error. Once again. The problem is not happening on http. Only on https. My django application is dockarized. Also I am using nginxproxymanager as an alternative to nginx. Because it gives an easy gui to manage sites and handle ssl. I am using cloudflare to manage my dns. Here is my settings.py: CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = ["https://api.mailgrass.com", "http://api.mailgrass.com"] CORS_ALLOWED_ORIGINS = ["https://api.mailgrass.com", "http://api.mailgrass.com"] SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") Please help me solve this issue. I am pulling my hair for the last couple of days. -
SIgning users in Django through Google OAuth and using that data to access their Gmail
While signing users in through Google in Django is pretty conventional, I can't seem to figure out how to use that user data that I get upon login to get access to the user's Gmail. In case i need another authentication step, how do i make it so i remember their Gmail authentication for next time. Essentially, I need to log in users in my Django app through their Google account and then feed them their Gmail emails on their dashboard. Tried django allauth and played around but with no results. -
ModuleNotFoundError: No module named 'django.conf.urls.defaults' - django compat for background tasks
I'm trying to use background tasks in Django, but It requires django-compat, and the problem is that django-compat has some problems with my django version, so is there a way to fix the problem with compat or do I have to start looking for another way to use background tasks? error: \lib\site-packages\compat\__init__.py", line 48, in <module> from django.conf.urls.defaults import url, include, handler404, handler500 # pyflakes:ignore ModuleNotFoundError: No module named 'django.conf.urls.defaults' -
DRF Create list of objects even when some of them not valid
I'm currently working on a DRF project where I'm dealing with a scenario where I receive a list of objects through a POST request. The challenge I'm facing is that this list might contain some objects that are not valid according to certain criteria. However, I need to go ahead and create all the valid objects, and then perform a bulk creation of all these valid objects in one go. I've tried a few approaches, but I'm running into issues with properly validating and handling the objects, especially when using a many=True, if one of the items are not valid than no items created at all. Has anyone encountered a similar situation or can provide insights on how to approach this? Any guidance on how to correctly structure the validation, filtering, and bulk creation process would be greatly appreciated! Thank you in advance. Here is the code I've managed to write, but it doesn't look right to iterate over objects in the view: @action(methods=['post'], detail=False, url_path='custom_method') def custom_method(self, request): created = [] for item in request.data: serializer = self.get_serializer(data=item) try: serializer.is_valid(raise_exception=True) except ValidationError: # ... make log continue self.perform_create(serializer) created.append(serializer.data.get('id')) # custom action for created objects ... return Response(...) -
pythonanywhere admin site css is broken in django
when I deployed a django site on pythonanywhere, the admin site css got broken. It works fine on locally but on pythonanywhere it appears like this: enter image description here I read the documentation on static files, ran collectstatic successfully, ran findstatic (the program finds the base.css correctly), however, I still cannot see the proper styling of the admin site. -
404 Error When Verifying Email in Dj-Rest-Auth API for Mobile App
I'm developing an authentication API for a mobile app using dj-rest-auth in Django. After a user registers an account, a verification email is sent to the user with an activation key. However, when I try to verify the email by sending a POST request to the verification endpoint, I receive a 404 Not Found error. I'm unsure where the issue lies. # main project urls.py urlpatterns = [ # Other URL patterns... path('register/', include('dj_rest_auth.registration.urls')), # ... ] Settings ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_CONFIRM_EMAIL_ON_GET = True #ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = '' #ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '' SITE_ID = 1 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'myEmail' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 EMAIL_CONFIRMATION_EXPIRE_DAYS = 7 #EMAIL_HOST_USER = os.environ.get("EMAIL_USER") #EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_PASSWORD") REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ] } SIMPLE_JWT = { 'USER_ID_FIELD': 'email', 'ACCESS_TOKEN_LIFETIME': datetime.timedelta(minutes=15), 'REFRESH_TOKEN_LIFETIME': datetime.timedelta(days=10), 'ROTATE_REFRESH_TOKENS': True, } LOGIN_URL = 'https://localhost:8000/login/' REST_AUTH = { 'USER_DETAILS_SERIALIZER' : 'users.serializers.CustomUserDetailsSerializer', 'REGISTER_SERIALIZER': 'users.serializers.UserRegisterSerializer', 'USE_JWT': True, 'JWT_AUTH_COOKIE': 'my-app-auth', 'JWT_AUTH_REFRESH_COOKIE': 'my-refresh-token', 'JWT_AUTH_HTTPONLY':False, } AUTHENTICATION_BACKENDS = [ 'allauth.account.auth_backends.AuthenticationBackend', 'django.contrib.auth.backends.ModelBackend', ] Issue: When I try to verify the email by sending a POST request to the /register/account-confirm-email/ endpoint with the activation … -
how to make celery able to handle custom import
hello every one how do i make celery able to handle custom models, i have a model i want to perform some tasks on i tried importing it but i keeps throwing errors, below is the code. the error tend to be based on the registered apps, please how can i resolve the issue? i have my celery instance defined in my asgi.py all is set including redis setup CELERY.PY from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab from ecoperative.tasks import savings_increment from django.conf import settings from .load_env import load_env load_env() # set the default Django settings module for the 'celery' program. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "agric360.settings") app = Celery("agric360") app.config_from_object("django.conf:settings", namespace="CELERY") app.conf.beat_schedule={ 'increment':{ 'task':savings_increment(), 'schedule':crontab(minute=1) } } app.autodiscover_tasks() TASKS.PY from __future__ import absolute_import, unicode_literals from app.models import User from wallet.models import Wallet import datetime from celery import shared_task from celery.utils.log import get_task_logger # logger=get_task_logger(__name__) # # @shared_task # # def print_hello(): # # print('hello') @shared_task def savings_increment(): # print('hello') wallets=Wallet.objects.all() for wallet in wallets: date_range=datetime.datetime.now().second-wallet.savings_timestamp.second if wallet.savings != 0: if wallet.savings_timestamp is not None: if date_range >= 30: wallet.savings+=2 wallet.save() else: pass else: pass The error encountered is indicated below Traceback (most recent call last): … -
How to set an image as a background in div?
How can I insert an image into url(): <div class="panel active" style="background-image: url();"> <h3>Business Session</h3> </div> I tried template tag with this {% load static %} and also absolute path but it does not work. My image is in the static directory. -
ModuleNotFoundError: No module named '_sqlite3' when i wanted to create django app
I had a new mechine (PC), I want to use pipenv to work on my django app. It keeps on returning an error "ModuleNotFoundError: No module named '_sqlite3'" each time I try "python manage.py startapp " its really giving me issues and I dont know why. I tried updating python and the pipenv. I also tried installing sqlite3 using "apt-get". Ieven deleted the venv and downladed it again yet same error. I was able to install django and did "django-admin startproject ." and it ran smoothly. Except when I run "python manage.py startapp " it throws an error. -
Current Logged in user can't be found after filtering primary key in django application using REST framework
After filtering the user objects, I can see the current logged in user in json format when I go to this url 'http://127.0.0.1:8000/user_profile_info/', but when I do 'print(userData)' it prints this empty json '{'user': []}', but it should print the current logged in user in json format. Logged in user in json format: {'user': [{'id': 1, 'username': 'JerryTaylor13', 'email': 'JerryTaylor13@gmail.com', 'password': 'f49fidaf#', 'settings': {}}]} views.py @api_view(['GET', 'POST']) def user_profile_info(request): user = User.objects.filter(id=request.user.id) serializer = UserSerializer(user, many=True) return JsonResponse({"user": serializer.data}, safe=False) @login_required def profile(request): response = requests.get('http://127.0.0.1:8000/user_profile_info/') userData = response.json() print(userData) return render(request, 'profile.html') models.py from django.db import models #from django.contrib.auth.models import User #authentication system class User(models.Model): id = models.AutoField(primary_key=True) username = models.CharField(max_length=50) email = models.EmailField(max_length=100) password = models.CharField(max_length=128) # Hashed password settings = models.JSONField(default=dict) Serializers.py from rest_framework import serializers from .models import User, Subject, Project, Task, FocusSession, Tally, Badge, Streak, Reflection class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' The user models and its fields are shown on the django admin site but not in the tables of my postgresSQL db. Any guidance would be appreciated. -
HyperlinkedModelSerializer and ModelViewSet, could not resolve URL
# models.py class Test(models.Model): name = models.CharField(default="yolo", max_length=100) # serializers.py class TestSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Test fields = '__all__' # views.py class TestViewSet(viewsets.ModelViewSet): queryset = Test.objects.all() serializer_class = TestSerializer # urls.py router.register(r'test', TestViewSet) # generated routes: ^test/$ [name='test-list'] ^test\.(?P<format>[a-z0-9]+)/?$ [name='test-list'] ^test/(?P<pk>[^/.]+)/$ [name='test-detail'] ^test/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='test-detail'] Error: File "\rest_framework\serializers.py", line 522, in to_representation ret[field.field_name] = field.to_representation(attribute) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "\rest_framework\relations.py", line 416, in to_representation raise ImproperlyConfigured(msg % self.view_name) django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "test-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. I did include the related model in the serializer's meta, and I didn't touch lookup_field either in the view or in the serializer (not that setting it manually seems to have any curative effect). What am I missing? -
Can't make gunicorn systemd service recognize change in code only by rebooting my linux computer
I have deployed a simple Django app locally on my ubuntu machine using systemd. I have created two files gunicorn.socket and gunicorn.service according to many tutorials on the web. When I change my app's python code, the only way to see the change on the browser is to reboot the computer. I have tried doing different combination of the following commands without success: systemctl daemon-reload systemctl restart gunicorn.service systemctl restart gunicorn.socket I get the message: Failed to restart gunicorn.service: Unit gunicorn.socket not found. although the file gunicorn.socket exists as usual Excerpt from my nginx config file: location /static/ { root /root/djdeploy/demo/static; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } my gunicorn.socket file: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target My gunicorn.service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=nad Group=www-data WorkingDirectory=/home/nad/djdeploy/demo ExecStart=/home/nad/djdeploy/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ demo.wsgi:application [Install] WantedBy=multi-user.target -
Custom response decorator for model view set in django
I am trying to customize my response in CollectionViewSet for each http method. response would be different message and status code Problem, list, create, update method are identical to it's parent except delete method which has some extra logic # Working V-1 class CollectionViewSet(ModelViewSet): queryset = Collection.objects.annotate( products_count=Count('products')).all() serializer_class = CollectionSerializer def generate_response(self, message, status_code, data=[]): response_data = { 'message': message, 'status': status_code, 'data': data } return Response(response_data, status=status_code) def list(self, request, *args, **kwargs): collections = self.get_queryset() serializer = self.get_serializer(collections, many=True) return self.generate_response('Data fetched successfully', status.HTTP_200_OK, serializer.data) # no special logic it's identical to (super().create()) method def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return self.generate_response('Data created successfully', status.HTTP_201_CREATED, serializer.data) def update(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance, data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return self.generate_response('Data updated successfully', status.HTTP_202_ACCEPTED, serializer.data) def destroy(self, request, pk): collection = get_object_or_404(Collection, pk=pk) if collection.products.count() > 0: return self.generate_response('collection cannot be deleted because it includes one or more products.', status.HTTP_405_METHOD_NOT_ALLOWED) collection.delete() return self.generate_response('Data deleted successfully', status.HTTP_204_NO_CONTENT) I am trying to have some way to decorate the CollectionViewSet class so that I can utilize full feature of ModelViewSet and able to get response as before @generate_custom_response class CollectionViewSet(ModelViewSet): queryset = Collection.objects.annotate( products_count=Count('products')).all() serializer_class = … -
django-nvd3 not showing the chart
Recently I tried to make a dynamic website to show different charts of different types in one single html page, the following is my code views.py from django.shortcuts import render from dashboard.models import Data # Create your views here. def dashboard(request): data = Data.objects.all() piechart = pieChart() context = {'data':data, 'piechart': piechart} return render(request, 'dashboard/dashboard.html', context) def pieChart(): xdata = ["Apple", "Apricot", "Avocado", "Banana", "Boysenberries", "Blueberries", "Dates", "Grapefruit", "Kiwi", "Lemon"] ydata = [52, 48, 160, 94, 75, 71, 490, 82, 46, 17] chartdata = {'x': xdata, 'y': ydata} charttype = "pieChart" chartcontainer = 'piechart_container' data = { 'charttype': charttype, 'chartdata': chartdata, 'chartcontainer': chartcontainer, 'extra': { 'x_is_date': False, 'x_axis_format': '', 'tag_script_js': True, 'jquery_on_ready': False, } } return data and the html file is as follows {% load static %} <script type="text/javascript" src='{% static 'jquery/dist/jquery.js' %}'></script> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dashboard</title> </head> <body> <h1> Dashboard </h1> <h1>Fruits vs Calories</h1> {% load nvd3_tags %} {% include_chart_jscss %} <script> {% load_chart charttype chartdata chartcontainer extra %} </script> {% include_container chartcontainer %} </body> </html> Why is it not working? I' m trying to make a chart in different function n give it a call in dashboard so that … -
Docker & Django: Django is looking for a DB table before running migrations
When I run docker-compose, all containers start without errors except "catering-django-1". As I understand it, django looks for the "myapp_menu" table in the DB before running the migrations. However, everything works for me locally. That is, when I write "python3 manage.py migrate" in the console - everything works flawlessly. I can't figure out what the problem is for a long time and I hope for your help. Thank you! Docker-compose logs: Attaching to catering-django-1, catering-nginx-1, catering-postgres-1, catering-redis-1, catering-redis-commander-1, catering-worker-1 catering-redis-1 | 1:C 26 Aug 2023 17:55:06.942 # WARNING Memory overcommit must be enabled! Without it, a background save or replication may fail under low memory condition. Being disabled, it can also cause failures without low memory condition, see https://github.com/jemalloc/jemalloc/issues/1328. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect. catering-redis-1 | 1:C 26 Aug 2023 17:55:06.942 * oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo catering-redis-1 | 1:C 26 Aug 2023 17:55:06.942 * Redis version=7.2.0, bits=64, commit=00000000, modified=0, pid=1, just started catering-redis-1 | 1:C 26 Aug 2023 17:55:06.942 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf catering-redis-1 … -
Django celery is not processing the task
I am trying to tigger a process that runs in the background. I am calling this process using ajax call. I have setup celery/rabbitmq/flower to achieve this. In my app ->views.py def sync_now(request,sync_id): sync_obj=Sync.objects.get(id=sync_id) synchronize_data.apply_async(args=[sync_id]) result = synchronize_data.apply_async(args=[sync_id]) # Get the task ID task_id = result.id print("task id") return render something Tasks.py app = Celery('sync', broker='pyamqp://xxx:xxxx@localhost:5672/myvhost') @shared_task def synchronize_data(sync_id): try: sync_obj = Sync.objects.get(id=sync_id) # Your synchronization logic goes here sync_data(sync_id, sync_obj) return 'Success' # Return a result to indicate success except Exception as e: return str(e) # Return an error message in case of failure When I run this command - celery -A ipass worker -l info --pool=solo -- it appears like all the queued process gets triggered and sync_data is called multiple times. I had to manually kill the cmd But when I trigger this from the template I get only [2023-08-26 23:08:26,320: INFO/MainProcess] Task sync.tasks.synchronize_data[0c72b00b-acf1-48d2-ab44-6ddb678d62e8] received [2023-08-26 23:08:26,320: INFO/MainProcess] Task sync.tasks.synchronize_data[7c2c018f-cd6b-4dae-8cab-b18a572a5c92] received [2023-08-26 23:08:26,887: INFO/SpawnPoolWorker-32] child process 10588 calling self.run() [2023-08-26 23:08:26,888: INFO/SpawnPoolWorker-33] child process 11024 calling self.run() I am unable to debug, what is missing here ? Please let me know if you need more information. -
How to implement a time slot system in django?
# we need tuple for integer choices in django timeslot_weekday = ( (0, '9:00 - 10:00'), (1, '10:00 - 11:00') ) timeslot_weekend = ( (0, '10:00 - 11:00'), (1, '11:00 - 12:00') ) user_date = date(2023,1,15) if user_date.weekday() == 5 or user_date.weekday == 6: print(timeslot_weekend) else: print(timeslot_weekday) This code works as I am trying to understand how to implement an integer choice using a tuple that has the corresponding time slots. How do I go about this in the Django project? The one thing is I would need the user to select the date first in order to adjust the time slots of that particular time of the week. I hope this makes sense. -
NGINX redirect https://www.example.com to https://example.com
I want to redirect my https://www.example.com to my https://example.com domain. I managed it to make a redirect without the SSL https:// but when I add it to my domain an 400 error gets thrown. This is my sites-available: server { error_log /var/log/nginx/error.log debug; root /var/www/project; index index.html; server_name example.ch; location / { try_files $uri $uri/ =404;} listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.ch/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.ch/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 = example.ch) { return 301 https://$host$request_uri; } # managed by Certbot server_name example.ch; listen 80; return 404; # managed by Certbot } server { server_name www.example.ch; return 301 $scheme://example.ch$request_uri; } -
django form validation using "raise forms.ValidationError()"
I'm using a CustomLoginForm for login. In that form, I have created function level validation in forms.py file using forms.ValidationError(). But forms.ValidationError() not even works. I don't know what is the reason. But i'm using django messages, it pop up the messages. please help me why the form validation function not works forms.py class CustomLoginForm(forms.Form): email = forms.EmailField( label='Email', max_length=254, widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Enter your email'}), ) password = forms.CharField( label='Password', widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Enter your password'}), ) def clean(self): cleaned_data = super().clean() email = cleaned_data.get('email') password = cleaned_data.get('password') if email and password: user = authenticate(email=email, password=password) if user is None: raise forms.ValidationError("Invalid email or password. Please try again.") return cleaned_data views.py def login(request): if request.method == "POST": form = CustomLoginForm(request.POST) if form.is_valid(): user_email = request.POST.get("email") user_password = request.POST.get("password") user = authenticate(request, email = user_email, password=user_password) if user is not None: auth_login(request, user) messages.info(request, f"you are now logged in {user_email}") return redirect("home") else: messages.error(request, "invalid email or password or user not exist") else: messages.error(request, "invalid email or password or user not exist") form = CustomLoginForm() context = { "login_form" : form } return render(request=request, template_name="account/login.html", context=context) login.html {% load static %} {% load crispy_forms_tags %} {% block content %} <!--Login--> … -
ValueError at /register/ The view authenticate.views.register_user didn't return an HttpResponse object. It returned None instead
I not able to fix this problem this problem everytime showing views.register_user didn't return an httpresponse. Also registering of user not happening properly, everytime showing this. Yesterday it was showing fine but today showing error. So, fix this error and how solve this problem. I have posted my detail code, please look up. Also I have applied in stackoverflow answers but nothing happening. Below my code: views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate,login,logout from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from .forms import SignUpForm def register_user(request): if request.method == 'POST': form=SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(request, username=username, password = password) login(request,user) messages.success(request,('You Have Been Registered!')) return redirect('home') else: form = SignUpForm() context = {'form': form} return render(request,'authenticate/register.html',context) register.html {% extends 'authenticate/base.html' %} {% block content %} <h2 class="text-center">Register</h2> <div class="col-md-6 offset-md-3"> <form method="POST" action ="{% url 'register' %}"> {% csrf_token %} {% if form.errors %} <p>Your Form Has Errors.....</p> {% endif %} {{ form.as_p }} <input type="submit" value="Register" class="btn btn-secondary"> </form> </div> <br/><br/> {% endblock %} forms.py from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class SignUpForm(UserCreationForm): email = forms.EmailField(label="",widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Email Address'})) first_name = forms.CharField(label="",max_length=100, widget=forms.TextInput(attrs={'class':'form-control','placeholder':'First … -
Django Membership model registration
i have some issues with the following code. I have an authentication system that works fine. After user registers the account, django send a email with token for account confirmation. it works fine. now i want to add some code to save automatically free membership parameter when user click on activation link. there is something of wrong in my code: MEMBERSHIP_CHOICES = (('Premium', 'PREMIUM'), ('Free', 'FREE') ) class Membership(models.Model): slug = models.SlugField(null=True, blank=True) # name = models.CharField(max_length=100) description = models.TextField() membership_type = models.CharField(choices=MEMBERSHIP_CHOICES, default='Free',max_length=30) price = models.DecimalField(default=0.00, max_digits=5, decimal_places=2) def __str__(self): return self.membership_type def account_activate(request, uidb64, token): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = Customer.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, user.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() # Create a free membership free_membership = Membership.objects.get(membership_type='Free') # Convert the Membership object to string # free_membership_str = str(free_membership) print(free_membership) # Create a new UserMembership # user_membership = UserMembership.objects.create(user=user, membership=free_membership.membership_type) user_membership = UserMembership.objects.create(user=user, membership=free_membership) # user_membership = UserMembership.objects.create(user=user, membership=self.free_membership) user_membership.save() # # Creating a new UserSubscription # user_subscription = Subscription.objects.create(user_membership=user_membership) # # user_subscription = Subscription() # # user_subscription.user_membership = user_membership # user_subscription.save() # # return user login(request, user) return redirect("homepage:homepage") else: return render(request, "account/registration/activation_invalid.html") if i … -
How can i get filter value to the particular view?
I want to get the filter value and pass it to the view to display it on another template, enter image description here this is the view I want the filter value in, is there a way I can get the filter value or get the filtered data whenever the filter is applied in the admin panel I want the filtered data or the filter name which I would apply to filter the model