Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Couldn't connect to the server? Getting the below error.How to get rid of that error?
Couldn't connect to the server? Getting the below error.How to get rid of that error? Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\base\base.py", line 216, in ensure_connection self.connect() File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\base\base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\postgresql\base.py", line 168, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\psycopg2\__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? -
Django eCommerce Resource 2018
Hey all i have been looking around the web for little over a week, if someone could help, i'm looking for resources (links/vids etc.) to help me code a website with the basic idea of UberEats. it would be great help if anyone has any links -
Construct a recursive nested model data
I intend to construct a database structure as: "Name" includes "Text" and "Command", Meanwhile, "Name" itself is a Command, How to accomplish such a task? class Name(models.Model): desc = models.CharField(max_length=100) class Text(models.Model): desc = models.CharField(max_length=100) class Command(models.Model): desc = models.CharField(max_length=100) -
why celery, rabbitmq needed in django-channel when it can do their job?
I was reading the documentation of django-channels for the first time today and found the following line Channels will take care of scheduling them and running them all in parallel. Does this mean, it does the celery task as well? I used to get confuse with the celery, rabbitmq, mqtt. I thought I was clear and my understanding of celery, rabbitmq and mqtt was celery - background job, task scheduling rabbitmq - message broker, sends message to worker mqtt - it's also another message queuing in my understanding, celery does both background job tasks as well as of rabbitmq task or mqtt task. so my question is, when using django-channel, will we need to use those listed stacks(celery, rabbitmq) ? If needed, why it is needed? I look over several articles but could not get the insight clearly. I feel their usecase are somewhat similar. Can anyone clear my confusion with real life examples? -
Validate information on form fields generated at runtime in Django
I am trying to create a process that generates a form with its fields at runtime. This form is a simple form and not a Model form. It contains a number of RadioSelect fields, a TextArea, and an IntegerField. The number of radio button fields that will be generated is determined by the data gotten from a database table. The data is in JSON which contains a list of dictionaries when parsed, and it looks like this: [ {'criteria': 'design', 'description': 'aaa, bbb'}, {'criteria': 'design', 'description': 'ccc, ddd'}, {'criteria': 'design', 'description': 'eee, fff'}, {'criteria': 'design', 'description': 'ggg, hhh'}, {'criteria': 'design', 'description': 'iii, jjj'}, {'criteria': 'design', 'description': 'kkk, lll'}, ] In the above example, there are 6 dictionaries which means that 6 RadioSelect fields will be generated. If the JSON data contains 10 dictionaries then 10 RadioSelect fields will be generated. The TextArea and IntegerField fields are always present in the form. When the form is submitted, I would like to validate the form and if no errors, get the data from the form, perform some operations on the data, save the data in a different database table and display the form with the saved data. If there are errors then … -
Django can't find package even though in virtualenv
I'm coming into an inherited Django project, so I can't say how it was originally set up. However, pip freeze tells me that django-cms is installed in the virtualenv: (demo)$ pip freeze ... django-cms==3.3.0 ... So why when I do anything with, manage.py, do I get an error saying it's not available? (demo)$ ./manage.py shell Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/iscape/sites/demo/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/iscape/sites/demo/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 328, in execute django.setup() File "/iscape/sites/demo/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/iscape/sites/demo/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/iscape/sites/demo/local/lib/python2.7/site-packages/django/apps/config.py", line 112, in create mod = import_module(mod_path) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named cms I can also confirm that VIRTUAL_ENV has the correct value in the "activate" script. It's like pip knows what's installed, but Django doesn't. This is Django1.8, btw, though I don't know how much of a factor that is. Any ideas? I'm getting nothing out of the stack trace and don't know where else to look. -
addind list key value to a result of query
i am use django 2.0 and w2ui 1.5 grid i want to show result in the datagrid of w2ui. The structure of the json for the grid is like {"status": "success", "total": 1, "records": [{"key": "value", "key2": "value2"} ]} my views.py i use cursor because my query is to long and i don't know how to do it with djaog from django.db import connection cursor = connection.cursor() query=("select table1.id as id,table1.code as code,table1.nom as nom,table2.nom as tgen\ from table1, table2\ where table1.table2_id = table2.id\ EXCEPT\ select select table1.id,table1.code,table1.nom,table2.nom\ from table1,table2\ where where table1.table2_id = table2.id\ and table1.id in (select table1_id\ from table3\ where table3.id in (select table3_id\ from table4))") cursor.execute(query) result = [ dict(line) for line in [zip([ column[0] for column in cursor.description], row) for row in cursor.fetchall()] ] result give me this [{"id": 1, "nom": "jojo", "typegen": "aloba", "code": "GEN-1"} ] how can i insert {"status": "success"} and the {"total":1} for the grid show it? -
Session dropped after HttpResponseRedirect in Django?
I have a multi-page form in Django. That is to say I have multiple Django Form objects spread across five or so templates. What I would like to do is pass that form between the pages, then commit it to my model at the end of the string. My code snippet is as follows: def firstFormStep(request): if form.is_valid() : for field in form : request.session[str(field.name)] = form.cleaned_data[str(field.name)] request.session.modified = True request.session.save() print ("Request: " + str(request.session.items())) print ("Session: " + str(request.session.session_key)) return HttpResponseRedirect(reverse('core:nextFormStep'), request) Before session.save() my session_key was None. Afterwards it is a number. The first line of my next view is: def nextFormStep(request): print ("Session: " + str(request.session.session_key)) The session_key at this point is None. Somewhere in HttpResponseRedirect my session gets dropped. Why? How can I fix this? -
bitcoin api stored in django models postgres
I'm creating webapp that searches in postgres database for address/transactions, and if no match- takes json from api. The problem is, I need to use only two models for django project, Address and Transaction, and bitcoin blocks are very often with multiple inputs and outputs. So I can't think of any good solution for storing transactions without putting entire json inside and quering on it later on, and it seems like a messy solution. Any ideas? I created something like this: class Transaction(models.Model): transaction_id = models.CharField(max_length=54) tx_json = JSONField() timestamp = models.IntegerField(null=True) class Address(models.Model): address = models.CharField(max_length=35) hash = models.CharField(max_length=54) no_transactions = models.IntegerField() received = models.BigIntegerField() sent = models.BigIntegerField() balance = models.BigIntegerField() transactions = models.ManyToManyField(Transaction) -
filter in django 2.0
Hey I am writing app in django many blogs with many articles each but i dont know how to take artices which belongs to blog and write filter My articles model class Articles(models.Model): title = models.CharField(max_length=150, verbose_name="Tytul") content = models.TextField(verbose_name="Tekst") published = models.DateTimeField(verbose_name="Data publikacji",auto_now=True) image = models.FileField(upload_to="images",verbose_name="Obrazy",default=None) blog = models.ForeignKey(Blogs,on_delete=models.CASCADE,null=True) My blogs model class Blogs(models.Model): title = models.CharField(max_length=150, verbose_name="Tytul") user = models.CharField(max_length=160, verbose_name="Uzytkownik") blog.html {% include 'base.html' %} {% block blog %} <h2>{{ blog.title }}</h2> <div class="blog-info"> Tworca : {{ blog.user }} </div> {% block article %} {% for a in article.blog_set.all %} <---- here <div class="article"> Opublikowano : {{ a.published }} </div> <img src="{{ a.image.url }}" class="article-img"> <div class="article-intro"> <p>{{ a.content }}</p> </div> {% endfor %} {% endblock %} {% endblock %} database -
Celery with Django uses UTC, refuses to honour localtime
I have a job running on django, with celery. According to the celery docs, it should honour django's USE_TZ = True and TIME_ZONE = 'Europe/London' parameters, but it doesn't, it uses UTC time. The server is ubuntu, and the server time is local time (i.e. currently British Summer Time - UTC+1). The celery schedule in the django settings looks like this: CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//' CELERY_RESULT_BACKEND = 'amqp://guest:guest@localhost:5672//' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_IMPORTS = ('proj.tasks',) CELERY_BEAT_SCHEDULE = { '12.30 weekdays': { 'task': 'proj.tasks.mail', 'schedule': crontab(minute=30, hour=12, day_of_week='mon-fri'), }, } The above works perfectly, except that it is always at 12.30 UTC, not 12.30 localtime. -
Selenium tests fail on CircleCI
I have a Django app I am trying to Selenium tests on CircleCI, but even though they run fine locally on my test environment they keep failing with a NoSuchElementException from Selenium on CircleCI. At the beginning of most of my browser tests, I run the following method, which is what is making the tests fail: def login(): driver.get(self.live_server_url + reverse("login")) # FAILURE HAPPENS HERE: Not able to find the `id_email` element driver.find_element_by_id("id_email").send_keys(u.email) driver.find_element_by_id("id_password").send_keys("12345678") driver.find_element_by_id("submit-login").click() config.yml version: 2 jobs: build: docker: - image: circleci/python:3.6.5-node-browsers environment: CI_TESTING: 1 - image: redis working_directory: ~/repo steps: - checkout # Selenium setup - run: mkdir test-reports - run: name: Download Selenium command: | curl -O http://selenium-release.storage.googleapis.com/3.5/selenium-server-standalone-3.5.3.jar - run: name: Start Selenium command: | java -jar selenium-server-standalone-3.5.3.jar -log test-reports/selenium.log background: true - restore_cache: name: Restore Pip Package Cache keys: - v1-dependencies-{{ checksum "requirements.txt" }} - v1-dependencies- - run: name: Install Pip Dependencies command: | python3 -m venv venv . venv/bin/activate pip install -r requirements.txt - save_cache: name: Save Pip Package Cache key: v1-dependencies-{{ checksum "requirements.txt" }} paths: - ./venv - restore_cache: name: Restore Yarn Package Cache keys: - yarn-packages-{{ .Branch }}-{{ checksum "yarn.lock" }} - yarn-packages-{{ .Branch }} - yarn-packages-master - yarn-packages- - run: name: … -
Google API Oauth2 Authentication Fails To Give Objects?
I have coded an authentication and I get an access token, but when I use it to grab an object I just end up getting 'NoneType' object is not callable on Internal Server Error: /oauth2callback for GetService. I am thinking the token expired, but I don't even know how to get it to get a new one, and I don't have a refresh token. I am also not using ssl so I don't think I can get a refresh token. I get the same result whether calling for Customer or CampaignService. I don't understand what I am doing wrong. I am following the code in Google. def getAdwordsFlow(): FLOW.redirect_uri = 'http://localhost/oauth2callback' # Generate URL for request to Google's OAuth 2.0 server. authorization_url, state = FLOW.authorization_url( access_type='offline', include_granted_scopes='true') return authorization_url def getAdwordsTokens(request): auth_code = request.GET.get('code') FLOW.fetch_token(code=auth_code) credentials = FLOW.credentials oauth2_client = oauth2.GoogleAccessTokenClient( FLOW.credentials.token, FLOW.credentials.expiry) adwords_client = adwords.AdWordsClient( "DEVELOPER-TOKEN", oauth2_client, "USER-AGENT", "CLIENT-CUSTOMER-ID") customer = adwords_client.GetService('CustomerService').getCustomers()[0] print('You are logged in as customer: %s' % customer['customerId']) return HttpResponseRedirect("/") url.py urlpatterns = [ re_path(r'^oauth2callback', queries.getAdwordsTokens, name='auth_calledback'),] #How view.py def index(request): return redirect(getAdwordsFlow()) Not sure if relevant, but this is on the cmd output: "GET /oauth2callback?state=XXXXXXXXX&code=4/XXXXXXXXXXX&scope=https://www.googleapis.com/auth/adwords+https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email HTTP/1.1" 500 80213 -
Authenticate users from external site by ajax
Problem I need that people from one specific external website can authenticate in my website by sending a Ajax request. After that, they have to be redirected to my website home. What i'm trying I've created a custom authentication function and configured the CORS headers, so my request is fully working and i can authenticate from the external website. The problem is: even if i can authenticate and get a OK response, when i redirect the user to my website, he doesn't have a active session. Why? I'm guessing that Django sets the session information in the browser cookies, and i'm not doing it. My question: What do i have to do, so i can keep a user authenticated after he authenticates from an external website? I would appreciate any ideas. -
Pass <input> text from template to django view through handlebars
Is it possible to pass the text value of an element to a django view via handlebars? Eg. <div class="ui icon input" style="width: 60rem;" > <input placeholder="Search..." type="text"> <a href="{% url appnamespace:myview TEXT_FROM_INPUT %}"><i class="search link icon"></i></a> </div> where the urls.py looks like urlpatterns = [ # capture any string url(r'(?P<search_str>.+)/$', views.index, name='index'), ] Basically want to pass the text input as a (+ delimited) string in the url that the view can then parse and do stuff to. Is this possible? Is there a more common way to do this specific thing? ** It seems like django forms are apparently the "right" way to pass values from templates to views, but new to html and was not able to get a quick working implementation of a form that was still able to use the semantic ui components that I am using in the example here. -
Django template is not displaying correct infromation
I have a django template and a view. In the view, there is a query that will check to see if the user and view have a record in the friend table. In the template, if the query comes up as empty, it will display to send a friend request. If the query comes back with objects, it will not display the option to send a request. I have the following if statement to display the request if the friends objects is empty. {% if friends == None %} <a href="{% url 'user_request' username=view.username %}">Send Request</a> {% endif %} For some reason, when the query friends is empty, it is not displaying the message. when the query friends is not empty, it is sill not displaying the message. I checked if it has to do with the query but it is unrelated to the query... -
django registration and login with custom user model
Custom User Model (models.py): class Users(AbstractBaseUser): user_id = models.AutoField(primary_key=True) user_email = models.EmailField(max_length=100, unique=True) password = models.CharField(max_length=100) registration_date = models.DateField(auto_now_add=True) last_login = models.DateField(auto_now_add=True) is_administrator = models.BooleanField(default=False) is_active = models.BooleanField(default=True) email_verified = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'user_email' Custom User Manager (models.py) class UserManager(BaseUserManager): def create_user(self, user_email, password): user = self.model( email=self.normalize_email(user_email) ) user.set_password(password) user.save(using=self._db) return user Registration Form (forms.py): class RegistrationForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) password_confirm = forms.CharField(widget=forms.PasswordInput) class Meta: model = get_user_model() fields = ('user_email',) def clean_password(self): password1 = self.cleaned_data.get("password") password2 = self.cleaned_data.get("password_confirm") if password1 and password2 and password1 != password2: raise forms.ValidationError( self.error_messages['password_mismatch'], code='password_mismatch' ) return password2 def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.registration_date = datetime.date.today() user.last_login = datetime.date.today() user.set_password("password") if commit: user.save() return user Register view (views.py) def register(request): if request.method == "POST": form = RegistrationForm(request.POST) if form.is_valid: form.save() else: form = RegistrationForm() return render(request, 'web/page.html', {'form' : form}) This is my first question on .. anything online (I'm an avid user of the search facility), but I've been struggling with this for days and I feel like it shouldn't be so difficult. For my question, it is more like a two part query. 1) I want a custom user model, but want to use as much … -
How do you display a views.py's variable linked to annotated queryset in a django template?
How do you display a views.py's variable linked to annotated queryset in a django template? I know the annotated queryset returns correct data when I printed it out, but somehow the template for loop is not retrieving the data on the html page. Can someone please advise me on how to fix this issue? Thanks. VIEWS.PY from django.shortcuts import render from django.views.generic import (TemplateView,ListView, DetailView,CreateView, UpdateView,DeleteView) from django.urls import reverse_lazy from myapp.models import Pastry from myapp.forms import PastryForm from django.db.models import F This line ps = Pastry.objects.values('pastry').annotate(total=Count('pastry')) returns correct data: {'pastry': 'Brownie', 'total': 1} {'pastry': 'Cake', 'total': 1} {'pastry': 'Cupcake', 'total': 1} {'pastry': 'Fruit Tart', 'total': 1} {'pastry': 'Muffin', 'total': 2} class PollsListView(ListView): model = Pastry def get_queryset(self): return Pastry.objects.all() class PollsDetailView(DetailView): model = Pastry class PollsCreateView(CreateView): success_url = reverse_lazy('pastry_list') form_class = PastryForm model = Pastry class PollsUpdateView(UpdateView): success_url = reverse_lazy('pastry_list') form_class = PastryForm model = Pastry class PollsDeleteView(DeleteView): model = Pastry success_url = reverse_lazy('pastry_list') pastry_list.html (template) {% extends "base.html" %} {% block content %} <div class="jumbotron"> <a href="{% url 'pastry_new' %}">New Poll</a> <h1>Voting for the favorite pastry</h1> Somehow this code here is not displaying any data. {% for p in ps %} {% for k, v in p.items %} … -
Django - Serialize aggregate result from returned from the raw sql
I am using Django raw function to run a SQL statement on Postgres to get a count on the database in the view function but I could not figure out how to setup the serializer for it. Any help will be appreciated it. Below is my code for view and the serializer. View: @api_view() def count_person_time_series(request,person): try: serializer = RSerializer(RModel. objects.raw( "SELECT date,count(*) from rtable where %s =ANY(person) group by date",[person]), many=True) except RModel.DoesNotExist: raise Http404("person does not exist") return Response(serializer.data) Serilizer: class RSerializer(serializers.ModelSerializer): ## I could not figure out this part person_count = serializers.SerializerMethodField() class Meta: model = RModel fields = '__all__' -
django - or_ is not defined
I have a query I am making in a django view.py file. I want to use 'or' and 'and' statements in the query. I am getting a message that says 'or_' is not defined and I was wondering what the import statement is for that because I can not find it anyhwere. Here is the query: @login_required(login_url='/login/') def user_profile(request, username): user = request.user view = User.objects.filter(username = username).first() view_profile = Profile.objects.filter(user = view).first() friends = Friends.objects.filter(or_( and_(user = user.username, friends = view), and_(user = view.username, friends = user) )) print(friends) parameters = { 'user':user, 'view':view, 'view_profile':view_profile, 'friends':friends, } return render(request, 'users/view_profile.html', parameters) Here is the error: Internal Server Error: /assad/ Traceback (most recent call last): File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/Users/omarjandali/Desktop/demo/mysplit/users/views.py", line 174, in user_profile friends = Friends.objects.filter(or_( NameError: name 'or_' is not defined -
Values between two dates
I have a database in Django contains amounts and values stored by dates, I want to calculate the values or the amounts between 2 dates how to do that ? Date the value 01/01/2018 500$ 01/02/2018 700$ 01/03/2018 800$ how to calculate the values from 01/01/2018 to 01/02/2018 for example ? -
Django annotate constant datetime MariaDB
Given a queryset qs of model A I would like to annotate it with a constant datetime. E.g., # models.py # --------- from django.db import models class A(models.Model): pass # test.py # ------- from datetime import datetime from django.db.models import Value from django.db import models from myapp.models import A A.objects.create() qs = A.objects.all() qs.annotate(now=Value(datetime.utcnow(), models.DateTimeField())) # Throws: AttributeError: 'str' object has no attribute 'tzinfo' The above code works using sqlite but fails with MariaDB (5.5.52). Any idea how to get this to work on MariaDB? django==1.11.3 python==3.4.5 Traceback /var/www/cgi-bin/tracking/lib64/python3.4/site-packages/django/db/models/fields/__init__.py:1451: RuntimeWarning: DateTimeField (unbound) received a naive datetime (2018-05-24 21:34:04.070362) while time zone support is active. RuntimeWarning) Traceback (most recent call last): File "./manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/var/www/cgi-bin/tracking/lib64/python3.4/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/var/www/cgi-bin/tracking/lib64/python3.4/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/var/www/cgi-bin/tracking/lib64/python3.4/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/var/www/cgi-bin/tracking/lib64/python3.4/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/var/www/cgi-bin/tracking/lib64/python3.4/site-packages/django/core/management/commands/shell.py", line 101, in handle exec(sys.stdin.read()) File "<string>", line 14, in <module> File "/var/www/cgi-bin/tracking/lib64/python3.4/site-packages/django/db/models/query.py", line 289, in __getitem__ return list(qs)[0] File "/var/www/cgi-bin/tracking/lib64/python3.4/site-packages/django/db/models/query.py", line 250, in __iter__ self._fetch_all() File "/var/www/cgi-bin/tracking/lib64/python3.4/site-packages/django/db/models/query.py", line 1118, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/var/www/cgi-bin/tracking/lib64/python3.4/site-packages/django/db/models/query.py", line 62, in __iter__ for row in compiler.results_iter(results): File "/var/www/cgi-bin/tracking/lib64/python3.4/site-packages/django/db/models/sql/compiler.py", line 834, … -
Having trouble saving a Foreign Key for an object in Django using a CreateView
Context: I am writing a Django-App that deals with Groups, Posts, and Users. Post entries contain a foreign key for both Group and User (a post must belong to a group and a user). I want the user to be able to add a post to a group from the group page itself -- i.e. when they access the CreateView form for this new post, there should be no 'Group' field. My Problem: I want to save a new post object with a CreateView class with a behind-the-scenes insertion of the Group (from a slug) and User (from self.request.user). Usually, I use the form_valid() method to do this, and it works just fine for inserting the User object; however, I cannot figure out why my Group object won't save. Some other information: I know that I am able to successfully grab the Group object from the slug in the kwargs. I have assigned this object to the variable self.form_group in the get() method and I have confirmed the 'type' of the object is the correct instance of my Group class. I have tried 'getting' the Group object in the form_valid() method itself: still no luck. I have tried both the … -
Using auth_user, email is saved under last_name column
I'm using the Django provided user model. Everything worked fine but after a single change where I tried to make the email field unique. my forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False, help_text='Optional.') last_name = forms.CharField(max_length=30, required=False, help_text='Optional.') email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') User._meta.get_field('email')._unique = True class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) the line of code I added to forms.py in order to make the email field unique is: User._meta.get_field('email')._unique = True my views.py: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() user.refresh_from_db() private_key = rsa.generate_private_key( public_exponent=65537, key_size=4096, backend=default_backend() ) public_key = private_key.public_key() pem_private_key = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption() ) user.profile.public_key = public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo ) raw_password = form.cleaned_data.get('password1').encode() user.profile.salt = os.urandom(16) kdf = Scrypt( salt=user.profile.salt, length=32, n=2 ** 20, r=8, p=1, backend=default_backend() ) key = base64.urlsafe_b64encode(kdf.derive(raw_password)) f = Fernet(key) user.profile.encrypted_private_key = f.encrypt(pem_private_key) user.save() current_site = get_current_site(request) subject = 'Activate Your MySite Account' message = render_to_string('accounts/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('account_activation_sent') else: form = SignUpForm() return render(request, … -
Django allauth activation code during registration
I am using Django allauth for authentication to my rest api. I have the whole process working as expected (login, registration, password reset) with email confirmation ..etc. My question is when a user register the user receives an email with the link that user need to click and confirm to get access to the website. However, i want to use allauth but instead of a link I want a randomly generated activation code (example: 123456). That user can input in a form to confirm.