Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cross validation in Django Admin between Parent and Child inline models
I have a Post model, which can contain either images or links to videos, or both. The requirement is that every Post must have at least one image or one link to video. My current problem is I don't know where to place the correct validation to make. I tried to override the functions add_view and change_view in PostAdmin but could not make it work. I also tried to make some validations in ImagenPostAdminFormSet and VideoLinkPostAdminFormSet, but were useless as either of them can be empty, but not both. Following is my code for the models: class Post(models.Model): .... nombre_post = models.CharField('Nombre del Posteo', max_length=255) descripcion = models.CharField('Descripción', max_length=255) .... class ImagenPost(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="imagen_post") imagen_post = ContentTypeRestrictedFileField('Imagen del Posteo', upload_to=media_posteos, help_text='Formatos válidos: jpg, jpeg, gif, png') ... class VideoLinkPost(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="video_link_post") video_link = EmbedVideoField('Link de Video', max_length=150, help_text='Ingresar Link de Video') ... Following the code for Admin: class ImagenPostAdminInline(admin.StackedInline): model = ImagenPost form = ImagenPostAdminForm formset = ImagenPostAdminFormSet extra = 1 class VideoLinkPostAdminInline(admin.StackedInline): model = VideoLinkPost form = VideoLinkPostAdminForm formset = VideoLinkPostAdminFormSet extra = 1 class PostAdmin(admin.ModelAdmin): form = PostAdminForm inlines = [ImagenPostAdminInline, VideoLinkPostAdminInline] As I said, the validation to make is that one … -
How to interpret an SQL Query to Django Queryset
What is the best way to read and interpret a raw SQL query and convert it to Django QuerySet, Im having trouble to understand with the alias and the join For example: select sum(balance_amount) balance_amount from account_balance a join public.account_catalog b on a.account_id=b.id where b.account_type in accounts and a.balance_date in date and bank_id in bank -
Issues with HyperlinkedModelSerializer with recursive model
Overview I'm setting up a new Django application with Django REST Framework (DRF), and this is my first time using the HyperlinkedModelSerializer for the API endpoint. I've overridden the get_queryset() method on the ModelViewSet, so I've also the basename argument to the application router and explicitly defined the url attribute in the serializer as suggested here. This fixed issues that I was having with the model's own url attribute. However, I'm getting the following error message when trying to serialize a ForeignKey field of the same class as the parent model. It fails with the following message: Could not resolve URL for hyperlinked relationship using view name "employee-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. Is there something special in the serializer I need to do to support using recursive model relationships like this? Example code # app/models.py from django.db import models class AbstractBase(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: abstract = True class Employee(AbstractBase): name = models.CharField(max_length=254) manager = models.ForeignKey('self', related_name='direct_reports', on_delete=models.SET_NULL, blank=True, null=True) ... def __str__(self): return str(self.name) # app/views.py from rest_framework import viewsets from rest_framework.pagination import PageNumberPagination from app import models … -
Why doesn't Django have a simpler way to style form fields?
I've looked at a lot of different methods on how to style form fields and all of them seem to be pretty unideal. Especially when you're trying to use bootstrap. I've done it a few different ways and I'm just surprised there isn't a better method than any of these. Ex: Within the form file alias = forms.CharField(max_length=15, widget=forms.TextInput(attrs={'placeholder': 'Username'})) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['alias'].widget.attrs.update({'class': 'special'}) Ex: Doing it manually in the template as Django mentions (which I would rather not have to resort to doing) Ex: with the django-widget-tweaks package (got errors saying incorrect inputs when they definitely were correct) Is there another method or any instructions someone can point me to for what has worked well for them? Thanks. -
Python 2.7 and 3.7.2 compatible django-redis serializer
I'm trying to write a py2.7 - py3.7 compatible django-redis serializer. I'm using django-redis==4.8.0 with django==1.11.22 and the PickleSerializer. I saw this issue https://github.com/niwinz/django-redis/pull/279 on django-redis and wrote a serializer similar to what's said in the thread. However my object seems a little bit more complex? Not sure. My goal is to have 2 applications running at the same time, one with py2.7 and the other with py3.7. They have to be 100% compatible, and I'm not being able to get past this. Here is the code for the serializer: # -*- coding: utf-8 -*- import six from django.utils.encoding import force_bytes from django_redis.serializers.pickle import PickleSerializer try: import cPickle as pickle except ImportError: import pickle class CompatPickleSerializer(PickleSerializer): def loads(self, value): if six.PY3: return self._loads_py3(value) return super(CompatPickleSerializer, self).loads(force_bytes(value)) def _loads_py3(self, value): return pickle.loads( force_bytes(value), fix_imports=True, encoding='bytes' ) Example of object I'm trying to serialize: { 'created_at': datetime.datetime(2019, 7, 30, 20, 0, 29, 244916, tzinfo = < UTC > ), 'items': [{ 'unit_price': Decimal('3.00'), 'name': 'my item', 'id': '12312312', }] 'id': 'b5c6210d-561f-4e4e-a025-e55b39d95418', 'name': 'cart', 'customer': None, } The object is a lot bigger then that, but I assume that if I can do the flow with this object, I can do with a … -
Keep user session logged in when page refreshed in vue js
I'm create user login page in vue js and consuming data from django with axios. I have utilized jwt to create token session in client-side The problem is the session is not saved when the page is refreshed. I have frustated because it. This is my source code : In '../src/store/modules/auth.js' import Vue from 'vue' import Axios from 'axios' import 'es6-promise/auto' // In order that Axios work nice with Django CSRF Axios.defaults.xsrfCookieName = 'csrftoken' Axios.defaults.xsrfHeaderName = 'X-CSRFToken' const state = { authUser: {}, users: [], isAuthenticated: false, jwt: localStorage.getItem('token'), endpoints: { obtainJWT: 'http://127.0.0.1:8000/api/auth/obtain_token/', refreshJWT: 'http://127.0.0.1:8000/api/auth/refresh_token/', baseUrl: 'http://127.0.0.1:8000/api/auth/', register: 'http://127.0.0.1:8000/signup/' } } const mutations = { setAuthUser: (state, { authUser, isAuthenticated }) => { Vue.set(state, 'authUser', authUser) Vue.set(state, 'isAuthenticated', isAuthenticated) }, updateToken: (state, newToken) => { localStorage.setItem('token', newToken); state.jwt = newToken; }, removeToken: (state) => { localStorage.removeItem('token'); state.jwt = null; }, } const actions = { refreshToken(){ const payload = { token: this.state.jwt } Axios.post(state.endpoints.refreshJWT, payload) .then((response)=>{ this.commit('updateToken', response.data.token) }) .catch((error)=>{ console.log(error) }) } } export default { state, mutations, actions, } In '../src/store/index.js' import Vue from 'vue' import Vuex from 'vuex' import axios from 'axios' import auth from './modules/auth' Vue.use(Vuex) // Make Axios play nice with Django CSRF axios.defaults.xsrfCookieName = … -
Apache with Gunicorn proxy not serving /static Django files
As the title says, I'm having difficulty getting Apache setup correctly to serve Django static files in production with a Gunicorn proxy for the backend. I'm finding that when I switch DEBUG = False that the app quits working with: < unexpected token. Reading about it, it has to do with the use of STATIC_ROOT being incorrect. I have my STATIC_ROOT = os.path.join(BASE_DIR, 'static'), and I'm running python manage.py collectstatic which is collecting all the assets to /static in the project root. Then I run gunicorn wsgi -D in the same directory as wsgi.py. Anyway, this is how the Apache configs are setup: HTTP: ServerName www.website.com ServerAlias website.com ### Redirect http to https RewriteEngine On # This will enable the Rewrite capabilities RewriteCond %{HTTPS} !=on # This checks to make sure the connection is not already HTTPS RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L] # This rule will redirect users from their original location, to the same location but using HTTPS. # i.e. http://www.example.com/foo/ to https://www.example.com/foo/ # The leading slash is made optional so that this will work either in httpd.conf # or .htaccess context HTTPS: ServerName www.website.com ServerAlias website.com Alias /static /home/website/src/static ProxyPreserveHost On ProxyPass /static http://localhost:8000/static/ ProxyPass / http://localhost:8000/ retry=5 ProxyPassReverse … -
Django model not saving for some reason (after second run of function)
I am making a game. For users to be able to move, they need to solve math problems. Up/down/left/right each have problems. At the beginning of the game, 4 math problems are generated. Here is the code for it: def generate_first_4_problems(level, operation, game_object, player_type): creator_problems = ['p1up', 'p1right', 'p1down', 'p1left'] opponent_problems = ['p2up', 'p2right', 'p2down', 'p2left'] problems = [] answers = [] while len(problems) < 4: problem = generate_problem(level, operation) answer = x(problem).expr() if answer not in answers: problems.append(problem) answers.append(answer) print('problems') print(problems) if player_type == 'creator': for i, d in enumerate(creator_problems): setattr(game_object, d, problems[i]) print('creator_problem %s' % d) print(getattr(game_object, d)) game_object.save() elif player_type == 'opponent': for i, d in enumerate(opponent_problems): setattr(game_object, d, problems[i]) print('opponent_problem %s' % d) print(getattr(game_object, d)) game_object.save() game_object.save() print('after save') print(game_object.p1up) return problems This code is run twice for each player (creator and opponent) also, here is what is printed: problems ['7 + 3', '1 + 4', '10 + 9', '8 - 10'] creator_problem p1up 7 + 3 creator_problem p1right 1 + 4 creator_problem p1down 10 + 9 creator_problem p1left 8 - 10 after save 7 + 3 {'problem_list': ['7 + 3', '1 + 4', '10 + 9', '8 - 10']} problems ['2 + 6', '2 + … -
Django Rest Framework: Nested Serializer lookup based on ForeignKey object?
I have a single CustomUser model which is shared by different type of profiles. One particular profile model allows users to have multiple Photos. class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) ... other fields class Photo(models.Model): uuid = ShortUUIDField(unique=True, editable=False) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) image = models.ImageField(blank=False, null=False) My API endpoint retrieves the profile model via the CustomUser id, this is easy to do. models.Profile.objects.filter(user=user) What confuses me is how to reference the CustomUser model for the nested Photo serializer to retrieve all the user photos. All the examples I've managed to lookup use a field from the parent model as lookup but I need to use a child model field as lookup here. Here's what I've tried so far: class PhotoSerializer(serializers.ModelSerializer): class Meta: model = models.Photo fields = "__all__" class ProfileSerializer(serializers.ModelSerializer): photos = PhotoSerializer(many=True,read_only=True) class Meta: model = models.Profile fields = "__all__" Thanks! -
How to convert an uploaded file (InMemoryUploadedFile) from pdf to jpeg in Django using wand?
I'm trying to convert a pdf file uploaded in Django to a jpg file. I would like to use the file directly in the InMemoryUploadedFile state. I tried to use wand but without any success. Here is the code I wrote: from django.shortcuts import render from wand.image import Image as wi # Create your views here. def readPDF(request): context = {} if request.method == 'POST': uploaded_file = request.FILES['document'] if uploaded_file.content_type == 'application/pdf': pdf = wi(filename=uploaded_file.name, resolution=300) pdfImage = pdf.convert("jpeg") return render(request, 'readPDF.html', {"pdf": pdfImage}) I tried different things like using uploaded_file.file or uploaded_file.name as the first argument for the wand image but without any success.` I thank you in advance for your help! -
favicon.ico not loading with Django
I'm trying to make a simple web server with Django in Python3. I'm having trouble getting favicon.ico to load properly. When I attempt view the root web page I see the following on my terminal... [30/Jul/2019 19:49:22] "GET /catalog/ HTTP/1.1" 200 583 [30/Jul/2019 19:49:22] "GET /static/jquery-3.4.1.min.js HTTP/1.1" 304 0 [30/Jul/2019 19:49:22] "GET /static/my_typeahead.js HTTP/1.1" 304 0 [30/Jul/2019 19:49:22] "GET /static/bootstrap.min.css HTTP/1.1" 200 106006 [30/Jul/2019 19:49:22] "GET /static/bootstrap.min.js HTTP/1.1" 304 0 Not Found: /favicon.ico [30/Jul/2019 19:49:22] "GET /favicon.ico HTTP/1.1" 404 2313 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 55932) Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 720, in __init__ self.handle() File "/usr/local/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 171, in handle self.handle_one_request() File "/usr/local/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer ---------------------------------------- Here is my project file structure... . ├── catalog │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ ├── admin.cpython-37.pyc │ │ ├── models.cpython-37.pyc │ │ ├── urls.cpython-37.pyc │ │ └── views.cpython-37.pyc │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── __init__.py │ … -
How to Select Audio Element by ID when ID is dynamically generated by Django
I have a django app which is generating multiple audio elements (for loop) on a page based on a model. The id of each audio element is generated by the pk of the corresponding object. {{ beat.pk }} I am using jquery to style an audio player, and when I click play on one, all of the audio players play. I've tried to select in jquery by ID using $('#{{ beat.pk }}') but that doesn't work. Here is the code that generates the audio players: {% for beat in beats %} <div class="col-md-4"> <div class="card mb-2 h-100"> <img class="card-img-top" src="{% static beat.coverArt %}" alt="cover art for exclusive trap beats for sale"> <div class="card-body"> <h5 class="card-title">{{ beat.title }}</h5> <p class="card-text">{{ beat.description }}</p> <!-- AUDIO SOURCE HERE--> <audio id="{{ beat.pk }}"> <source src="{% static beat.mp3preview %}" type="audio/wav"> </audio> <!-- START CUSTOM AUDIO PLAYER DIV--> <div class="player"> <div class="btns"> <div class="iconfont play-pause icon-play"></div> </div><!-- END BUTTONS DIV --> <div class="progress"> </div> </div> <!--END CUSTOM AUDIO PLAYER DIV --> <a href="{% url 'beat_detail' beat.pk %}" class="btn btn-primary"> Purchase Exclusive Rights </a> </div> </div> </div> {% endfor %} </div> Here is the javascript: $( function(){ var aud = $('audio')[0]; $('.play-pause').on('click', function(){ if (aud.paused) { aud.play(); … -
intl-tel-input how can i set a relative path to the images ? django-intl-tel-input not working?
when I tried using Django-intl-tel-input it didn't work so how can I set a relative path to the images as in the documentation in this question I showed my template and my terminal log 3.Override the path to flags.png in your CSS .iti__flag {background-image: url("path/to/flags.png");} @media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) { .iti__flag {background-image: url("path/to/flags@2x.png");} } can I use Django's/python's template tags like {static 'images/flags@2x.png' } or should I just use the images inside the CSS file directory? so how can I set this with Django so I don't need to change the path when I deploy the project on a server? -
Users are not automatically logged in to social-auth-app-django
I configured user authorization via GoogleOauth2.0 (social-auth-app-django). Entries in the social_django / usersocialauth / application are created. Also created user profiles in accounts / user /. But for some reason there is no automatic login. What could be the reason? As I understand it, this is due to the fact that the user has is_active = False (I redefined BaseUser). Is it possible to somehow intercept user authorithation through social_django to set their status as is_active = True. Only signals come to mind. settings.py MIDDLEWARE_CLASSES = ( 'django.contrib.auth.middleware.AuthenticationMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ) TEMPLATES = [ { 'OPTIONS': { 'context_processors': [ 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.get_username', 'social_core.pipeline.mail.mail_validation', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) INSTALLED_APPS = ( #... 'social_django', ) AUTHENTICATION_BACKENDS = [ 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ] SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '***********' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '****' LOGIN_REDIRECT_URL = '/kredity/' urls url(r'^accounts/', include('django.contrib.auth.urls')), url('', include('social_django.urls', namespace='social')), html <a href="{% url 'social:begin' 'google-oauth2' %}">Google+</a> -
Single quote inside double quote is messing up javascript code
I'm building a Django web app and I'm trying to send a JSON object to my javascript code using a Django template variable. # views.py import json def get_autocomplete_cache(): autocomplete_list = ["test1", "test2", "test3", "test4 - don't delete"] return json.dumps(autocomplete_list) <!-- html page --> <script> // Things i've tried autocomplete = {{ autocomplete_list|safe }}; autocomplete = '{{ autocomplete_list|safe }}'; autocomplete = JSON.parse('{{ autocomplete_list|safe }}'); </script> If I wrap {{ autocomplete_list|safe } in single quotes like '{{ autocomplete_list|safe }}', then the single quote in test4 - don't delete messes up the variable and Uncaught SyntaxError: Unexpected identifier. However, if I leave it as {{ autocomplete_list|safe }}, then the HTML text highlights it as an error with red underlines. What am I doing wrong here? -
How to deserialize MySql timestamp field in Django
I have MySQL database with a column called 'created' and its type is TIMESTAMP. In my Djano serializers.py if I do the following: created = serializers.DateTimeField() an exception is thrown: 'datetime.date' object has no attribute 'utcoffset' How can I resolve it? -
NameError: name 'l' is not defined while connecting Metamask in django
I'm now trying to connect my django page with Metamask for Ethereum(solidity) environment. All I want to do is connecting Metamask login function in my webpage. But I'm just a student and can't unserstand mechanisms well. I'm now just following instructions in https://django-web3-auth.readthedocs.io. in https://django-web3-auth.readthedocs.io/en/latest/readme.html page. I copied all the examples, but error NameError: name 'l' is not defined. What should I do? File "C:\Users\000\Desktop\midpro2\hi\hiproject\settings.py", line 64, in <module> MIDDLEWARE = l NameError: name 'l' is not defined (myvenv) Settings.py from django import get_version from packaging import version if version.parse(get_version()) < version.parse("1.10"): MIDDLEWARE_CLASSES = l MIDDLEWARE_CLASSES += ['django.contrib.auth.middleware.SessionAuthenticationMiddleware', ] else: MIDDLEWARE = l ROOT_URLCONF = 'hiproject.urls' -
Django super(type, obj): obj must be an instance or subtype of type
I keep getting this error, when submitting data from a form: super(type, obj): obj must be an instance or subtype of type I've made some research but i can't find the specific part of my code causing the error, but i think it's in the view, since it processes the data: view def myview(request): if request.method == 'POST': if 'button1' in request.POST: form1 = FirstForm(request.POST) if form1.is_valid(): # do what needs to be done and redirect profile = form.save(commit=False) profile.user = request.user profile.save() messages.success(request, f"Success") if 'button2' in request.POST: form2 = form = SecondForm(request.POST) if form2.is_valid(): # do what needs to be done and redirect profile = form.save(commit=False) profile.user = request.user profile.save() messages.success(request, f"Success") else: form1 = FirstForm() form2 = SecondForm() return render(request, "main/mytemplate.html", context={'form1': FirstForm, 'form2': SecondForm}) This view handles two forms, the problem seems to happen in the second form. Any advice is appreciated! -
Problems with CreateView eyesight, django bug?
( I come from stackoverflow in Spanish for help ) I have an interesting problem, first of all the model as such: class Reserve(models.Model): client = models.CharField(max_length = 200) employee_of_turn = models.ForeignKey(User, on_delete = models.CASCADE) The problem is to create an instance of the Reserve model through the CreateView view, which will create a form to create that instance, but in the form I do not want to display the field employee_of_turn I want only the client field to be shown and that by default the value of the field employee_of_turn is the user who logged in at that time. Well to solve this problem, try to modify the data sent by the POST method, in the get_form_kwargs method: class ReserveCreateView(CreateView): model = Reserve template_name = 'testapp1/example.html' fields = ['client'] success_url = reverse_lazy('home') def get_form_kwargs(self): form_kwargs = super().get_form_kwargs() if form_kwargs.get('data'): user = User.objects.get(username = self.request.user) post = self.request.POST.copy() post['employee_of_turn'] = str(user.pk) form_kwargs['data'] = post return form_kwargs The fact is that it does not work, I always get this error: django.db.utils.IntegrityError: NOT NULL constraint failed: testapp1_reserve.employee_of_turn_id I started trying to figure out where exactly the error occurred, because the solution of the get_form_kwargs method that I showed earlier, should fix the … -
Which web framework is best for new web developers? Django or Node?
I want to be a web back-end engineer in future. But I have zero knowledge about back-end development. I want to know between django and node.js, which is the best option for me as a new developer? -
How do I imitate an http request in python
I want to build a python http server (using Django or Flask or etc.) which I'll call it X. Also there's another python service on another machine, which I'll call Y, and there's an HTTP server Z running on a machine accessible only by Y. I want X to imitate Z. More formally: when X receives a request on http://x/PATH, I want to serialize the whole request (method, headers, cookies, body, etc.) into a binary string, transmit it to Y over a secure connection, Y make the same exact request to http://z/PATH, serialize the whole response (again including headers, etc.) into a binary string and transmit it to X over a secure channel, and X servers the same response to the client, almost as if client is connecting Z rather than X. This is practically a proxy, but I want to be able to do all of these using a custom communication channel between X and Y that I've developed (which uses websockets and thus is full-duplex). I mean, be able to use any communication channel as long as it supports transmitting strings. I'm open to use SOCKS and etc. I just don't know how. I need technical details rather … -
MySQL Backend Django
I am migrating my project to an Linux Ubuntu server and I am having some issues with my MySQL backend. When I runserver I am presented with the following error: django.core.exceptions.ImproperlyConfigured: 'django.db.backends.mysql' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'oracle', 'postgresql', 'sqlite3' yet in my local project everything works fine. Why is the 'mysql' backend not availavle? -
How do I resolve error 10013 in Django development?
I'm learning Django by following the "Writing your first Django app, part 1" tutorial on the Django website https://docs.djangoproject.com/en/2.2/intro/tutorial01/. Everything works fine until I run "python manage.py runserver" in my command prompt. I get an error that says: "Error: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions". I have tried using Windows PowerShell as well as a command prompt window to execute the following codes (all of which yield the same error): "python manage.py runserver", "python manage.py runserver 8000", "python manage.py runserver 8080". -
local variable 'password1' referenced before assignment
so i have been follow Django Documentation example regarding Custom user Model (AbstractBaseUser). But when i create user from admin site it started giving me this error "local variable 'password1' referenced before assignment" class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label= 'Password' , widget = forms.PasswordInput) password2 = forms.CharField(label = 'Password Confirmation', widget = forms.PasswordInput) class Meta: model = CustomUser #with my added feilds in AbstractBaseUser fields = ('email','first_name','last_name', 'Mobile', 'Aadhar_Card', 'Address','is_supervisor','is_employee','is_driver') def clean_password2(self): password1 = self.cleaned_data.get(password1) password2 = self.cleaned_data.get(password2) if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords Dont Match") return password2 def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user -
Django Allauth: Problem with Twitter Authentication
Allauth Github is working without any problem, however, Twitter is not. When clicking on https://0.0.0.0:9000/accounts/twitter/login/ nothing happens and yet there's no error. Everything is 200 ok. I'm using SSL in dev environement using django-sslserver. settings.py INSTALLED_APPS = [ ... 'django.contrib.sites', # new 'allauth', # new 'allauth.account', # new 'allauth.socialaccount', # new 'allauth.socialaccount.providers.github', # new 'allauth.socialaccount.providers.twitter', # new 'sslserver', ] SOCIALACCOUNT_PROVIDERS = {'github': {}, 'twitter':{}} AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ) SITE_ID = 1 LOGIN_REDIRECT_URL = '/' I use example.com in my hosts' file: /etc/hosts 0.0.0.0 example.com And in the Twitter app, I use these configurations: This is the social app configuration: And the site configuration: Do you see any problem?