Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django extend AbstractUser no such table error
Im trying to extend django 3.0.1 (drf==3.10.3) AbstractUser, on python 3.8.0. I'm getting no such table <appName>_user error when trying to login on the admin page and with JWT. My project dir structure: root -|app --|<projectName> ---|<appName> ---|statics ---|__init__.py ---|settings.py ---|urls.py ---|wsgi.py ---|asgi.py --|manage.py --|.env --|db.sql I've got__init__.py on my app/projectName/appName/migrations and app/projectName/appName/tests. Here is my relevant parts of settings.py file: BASE_DIR = os.path.join(os.path.dirname(os.path.dirname( os.path.abspath(__file__))), '<projectName>/') INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'drf_yasg', # openapi # local '<projectName>.<appName>', ] if DEBUG: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': env.str('DATABASE_NAME', 'db.sqlite3'), 'HOST': env.str('DATABASE_HOST', os.path.join(BASE_DIR, 'db.sqlite3')), 'PORT': env.int('DATABASE_PORT', '5000') }, 'test': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': env.str('DATABASE_NAME', 'testing.sqlite3'), 'HOST': env.str('DATABASE_HOST', os.path.join(BASE_DIR, 'testing.sqlite3')), 'PORT': env.int('DATABASE_PORT', '5000') } } else: DATABASES = { 'default': env.db(), } AUTH_USER_MODEL = '<appName>.User' Relevant parts of my appName/models.py: class User(AbstractUser): role = models.CharField( max_length=15, choices=[(tag, tag.value) for tag in UserRolesChoise] # Choices is a list of Tuple ) is_vendor = models.BooleanField( _('vendor status'), default=False, help_text=_( 'Designates whether the user is a vendor.'), ) is_customer = models.BooleanField( _('customer status'), default=True, help_text=_( 'Designates whether the user is a customer.'), ) def __str__(self): return self.username Relevent parts of my appName/serializers.py: from rest_framework import serializers from django.contrib.auth import … -
I want to write a django-python method that will send remainder email to a user, on specified date
this is my model.py, with send_email method to send email on time that i have been specified on geting_date(). Function to set a deadline def geting_date(): initial_date = datetime.date(2019,12,1) //initial date deadline = initial_date + datetime.timedelta(days=23,hours=14, minutes=44)// deadline date return deadline //model contains reports class ReportType(models.Model): ICYUMWERU = 1 IGIHEMBWE = 2 UMWAKA = 3 TIME_CHOICES = ( (ICYUMWERU, 'Icyumweru'), (IGIHEMBWE, 'Igihembwe'), (UMWAKA, 'Umwaka'), ) r_type = models.CharField(max_length=300) igihe_itangirwa = models.PositiveSmallIntegerField(choices=TIME_CHOICES, default=1) owner = models.ForeignKey(User, models.CASCADE) department = models.ForeignKey(Department, models.CASCADE) deadline = models.DateField(default=geting_date) // send email on specified date from geting_date() above def send_email(self): report_remainder = self.deadline if report_remainder: subject = "Welcome " message = 'We are in Reporting period you need to submitt your report on time !!!' rec = self.owner.email recepient = rec send_mail(subject, message, EMAIL_HOST_USER, [recepient], fail_silently = False) But is not working anyone could help me -
Task results are saved only when all tasks are done
I want to monitor/report task statuses, but tasks are saved only when all tasks are done. I want them to be saved as soon as they start. '''inside my Queue project''' celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Queue.settings') app = Celery('Queue', broker='redis://localhost:6379', backend='django-db', task_track_started=True, include=['index.tasks']) app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() inside "index" app tasks.py from __future__ import absolute_import, unicode_literals from celery import shared_task, current_task import time @shared_task def gozle(): time.sleep(15) return 1 views.py def index(request): gozle.delay() return HttpResponse('<a href="admin/">admin</a>') I expect that as I visit index page my task be triggered and be recorded into ResultTask, but it waits 15 seconds then be recorded. -
Django two-phase user registration form with email verification
I am trying to implement a Django registration app that at first takes the initial details from an User, then sends an email with a link to verify their email and directly login, and then provides them with another form to complete their registration. After the email verification, the status of 'is_active' and 'email_confirmed' field should change, but it does not change and remains at it's default value, i.e. false. Also, the data from the second form seems to be not registered, as when printing out the 'location' value, it always remains blank, even when entered in the form. How do I get to update these fields? These are the files for the app, called 'core'. The completeRegistration view is for handling the second form. My models.py file from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) email_confirmed = models.BooleanField(default=False) fee_paid = models.BooleanField(default=False) def __str__(self): return self.user.username class Extendedprofile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) location = models.CharField(max_length=30, blank=True) def __str__(self): return self.user.username forms.py file: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import Profile, … -
How to add more model Field in Django based on input from HTML
I want to to make a website where a user gives some value and based on it more fields are created. Like for <form class="form-inline my-2 my-lg-0" method = "POST"> {% csrf_token %} <input class="form-control mr-sm-2" type="search" placeholder="NO Of Episodes" aria-label="Search" name = "Episodes"><br> <button class="btn btn-outline-success my-2 my-sm-0" type="submit" action="{% url 'add_Anime' %}">Add task</button> </form> If the user gives input as 8 ,then eight fields are added in admin of Django class watched(models.Model): watched = models.BooleanField(default = False) Then create a webpage for marking which episodes have been watched and not. -
Django : Storing an array of strings ( filepaths) in a model field in sqlite3
I am trying to store an array of image paths (created randomly initially) to be retrieved later as it is and then pass it to an html template. I have tried using the Arrayfield option given in a lot of answers but I keep gettings errors because probably I am not postgress : from django.contrib.postgres.fields import ArrayField lst=ArrayField( models.IntegerField(null=True,blank=True), size=5, default=list, null=True ) errors from psycopg2.extras import DateRange, DateTimeTZRange, NumericRange ModuleNotFoundError: No module named 'psycopg2' -
CORS header missing when project hosted in a Subpath
I have a Django(v2.2) project hosted on an url which looks like https://some.example.com/mypath/ which has an API endpoint at blog/create. I need to make a POST request from https://some.example.com/anotherpath/ofmine/ (using axios), but that gives me a 301 error with the following messages in Firefox 71.0: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://some.example.com/mypath/blog/create/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://some.example.com/mypath/blog/create/. (Reason: CORS request did not succeed). However, I can easily make the same requests to a dev server hosted locally. Relevant settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework_docs', 'corsheaders', 'django_extensions', ... ] USE_X_FORWARDED_HOST = True FORCE_SCRIPT_NAME = '/mypath' What could be the reason and possible workarounds for the error? -
Django filtering a timedelta error: TypeError: expected string or bytes-like object
I have a model Run that contains start_time and end_time timestamps that signify the beginning of data measuring, and the end (we call that a "run"). class Run(models.Model): start_time = models.DateTimeField(db_index=True) end_time = models.DateTimeField() Recently, a customer has started to perform new types of operations, and one of those requires them to know the duration of a run (easy enough to figure out), but also filtering a table based on that duration. The filtering is the part I don't have. So trying to filter by duration (a field we don't have on the model), I came up with the following query: from django.db.models import F test_query = Run.objects.all().annotate(duration=F('end_time') - F('start_time')) By using annotate, along with F operations, I am able to add a new temporary field to my query, called "duration". This part works as expected. The problem comes down to trying to filter by that newly generated annotation, by using __gte and __lte filters: from datetime import timedelta from django.db.models import F test_query = Run.objects.all().annotate(duration=F('end_time') - F('start_time')).filter(duration__gte=timedelta(seconds=50)) For simplicity's sake, let's assume I only want to get Runs that are 50 seconds or longer, as an example. My work so far with timedelta has been straightforward enough. end_time - … -
Django choice form to determine the class and fields used
Ideally I would like the user to be presented with two forms, after filling in the 'type' form (Modern/Retro), to then be shown the field attributes specified within the classes. My forms.py looks like this at the moment to hopefully make it clearer what I'm after: from django import forms from .import models class AddGame(forms.ModelForm): class Meta: model = models.Game fields = ['name', 'type'] if type == 'Retro Game': model = models.RetroGame fields = ['name', 'type', 'platform', 'genre', 'slug', 'developer', 'rom', 'bios', 'emulator'] elif type == 'Modern Game': model = models.ModernGame fields = ['name', 'type', 'genre', 'publisher', 'slug', 'developer', 'online_play'] -
Automatically retrieve a value from session as integer?
My Django app uses a Cart class like below: class Cart: def __init__(self, request): self.session = request.session if self.session.get('cart'): self.cart = self.session['cart'] else: self.cart = {} def add_product(self, product, quantity=1): if self.cart.get(product.id): self.cart[product.id]['quantity'] += quantity else: self.cart[product.id] = { 'name': product.name, 'quantity': quantity, } self.save() def remove_product(self, product): del self.cart[product.id] self.save() def save(self): self.session['cart'] = self.cart As you can see, add_product method accepts product, which is an instance of Product model. As such, its id attribute is an integer. However, upon calling Cart's class save method, this integer gets converted into a string, which breaks the functionality of add_product (as it expects an integer). I know I could manually convert product.id to string in add_product to fix this (and also in remove_product etc.), but is there a cleaner way? Like automatically telling the session that whenever the cart is retrieved from session, the products' ids should be retrieved as integers? -
Django and jquery load pages
I'm trying to develop a crud web app with Django to modify a MySQL database, and to that, I have multiple forms that I can't use on a single page! for that, I decided to create multiple Html codes and then load those pages via jquery load method but for example, add CSV page get loaded but it does not affect the database after uploading the CSV file, my main html file <button id="BaseCasecsv" class="btn btn-default">Add CSV</button> <script> function BaseCasecsv() { $("#output").load("../basecasecsv") } </script> <div id="output"></div> ... upload csv html file : <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="file"> <button type="submit">upload</button> </form> my view : def BaseCasecsv(request): template = 'BaseCasecsv.html' if request.method == 'GET': return render(request,template) csv_file=request.FILES['file'] BaseCase_columns = [key for key, value in BaseCase.__dict__.items()] BaseCase_columns = BaseCase_columns[5:-1] if not csv_file.name.endswith('.csv'): messages.error(request,'this is not a csv file') data_set=csv_file.read().decode('UTF-8') io_string=io.StringIO(data_set) next(io_string) for column in csv.reader(io_string,delimiter=',',quoting=csv.QUOTE_NONE): _, created=BaseCase.objects.update_or_create( base_case_name= column[0], version= column[1], default= column[2], ) context ={} return render(request,template,context) ps : it works fine when i upload the file on csv html page without loading it -
Unable to access API despite entering the token
I have an API that's only accessible by passing a JWT token. I am using Simple-JWT library in Django. Also, I have stored this token within my localStorage and I obtain it within my views module via Ajax. I created an API using the GET method and it should retrieve back certain data from the model. However, when accessing the API URL via the Requests module in Python, it still says that authentication credentials were not provided. See my code below: models.py: class Mymodel(models.Model): emp= models.ForeignKey(User, on_delete = models.CASCADE) entry_time = models.DateTimeField() views.py: def get_time(request): if (request.method == 'GET'): tk = request.GET.get('token') #from AJAX headers = {'Authorization': 'JWT {}"'.format(tk), 'content-type': "application/json",} url = 'http://127.0.0.1:8000/secret_api/' response = requests.get(url, headers = headers) if response: print("success") return HttpResponse(response) class MyAPI(generics.ListAPIView): permission_classes = [IsAuthenticated] def get(self, request, format = None): user_id = User.objects.get(username=request.GET.get('username')).pk user = User.objects.get(id = user_id) if not Mymodel.objects.filter(emp=user).exists(): current_time = timezone.now() time = Mymodel.objects.create(emp=user, entry_time=current_time) data = time.entry_time return data #returns time AJAX call: $.ajax({ cache: false, url: {% url 'get_time' %}, #points to the get_time function type: 'GET', data: {username: username, token: token}, success: function(data) { $("#time").html(data); } However, when executing the get_time function, I am receiving this error: {"detail": … -
Django local variable referenced before assignment error when updating via modelformset
I have this view to edit 3 ModelForms (2 via ModelFormSet): @login_required def reviserdossier(request, pk): DocumentFormSet = modelformset_factory(DocumentdeBase, form=DocumentdebaseForm, extra=5) PhotoAvantFormSet = modelformset_factory(PhotoAvant, form=PhotoAvantForm, extra=5) instance_dossier = Dossier.objects.get(pk=pk) if request.method == 'POST': dossierForm = DossierForm(request.POST, instance=instance_dossier) formset = DocumentFormSet(request.POST, request.FILES, queryset=DocumentdeBase.objects.none()) formset2 = PhotoAvantFormSet(request.POST, request.FILES, queryset=PhotoAvant.objects.none()) if dossierForm.is_valid() and formset.is_valid() and formset2.is_valid(): if instance_dossier.rejection_count == 1: dossier_form = dossierForm.save(commit=False) dossier_form.status_admin = 'Validation OR Requise' dossier_form.status_prestataire = "En Attente d'ordre de réparation" dossier_form.rejection_count = 0 dossier_form.save() elif instance_dossier.rejection_count == 2: dossier_form = dossierForm.save(commit=False) dossier_form.status_admin = 'Dossier à clôturer' dossier_form.status_prestataire = "En attente de clôture" dossier_form.rejection_count = 0 dossier_form.save() for form in formset.cleaned_data: #this helps to not crash if the user #do not upload all the photos if form: image = form['documentdebase_image'] photo = DocumentdeBase(dossier=dossier_form, documentdebase_image=image) photo.save() for form2 in formset2.cleaned_data: #this helps to not crash if the user #do not upload all the photos if form2: image2 = form2['photoavant_image'] photo2 = PhotoAvant(dossier=dossier_form, photoavant_image=image2) photo2.save() #messages.success(request, "Dossier révisé!") return HttpResponseRedirect("/") else: print(dossierForm.errors, formset.errors, formset2.errors) else: dossierForm = DossierForm(instance=instance_dossier) formset = DocumentFormSet(queryset=DocumentdeBase.objects.none()) formset2 = PhotoAvantFormSet(queryset=PhotoAvant.objects.none()) return render(request, 'dashboard/reviser_dossier.html', {'dossierForm': dossierForm, 'formset': formset, 'formset2': formset2, 'dossier': instance_dossier}) This is my forms.py: class DossierForm(forms.ModelForm): mat_id = forms.CharField(max_length=7, label="N°") mattypes = ( ('A - أ', 'A … -
Is it available using pandas in django?
I'm low-end web developer. I'm undergraduate and have started data-science academic group last semester. What I trying to build is "Web page of our group,which has 'leaderboard' " We did kind of self competition last semester(inspired by kaggle competition) and scored by comparing submitted csv file and answer.csv file(pandas, sklearn accuracy score) So, here's my question is it possible to apply my scoring.py code in models.py or view.py? (I'm following some blogs and books) I made virtual env, built project under venv, and installed some pakages by venv/Scrips/~ pip install ~ (pandas, sklearn etc) I'll add my Compete code in manage.py, I also built file field, I really wonder if I can open that file and score it. class Compete(models.Model): author = models.ForeignKey('auth.User', on_delete = models.CASCADE) team = models.CharField(max_length = 200) sub_date = models.DateField('submission date') file = models.FileField(null = True) def __str__(self): return self.team -
How to index just selected json key using Django functionality instead of all keys?
I have the next model: from django.contrib.postgres.fields import JSONField from django.contrib.postgres.fields.jsonb import KeyTextTransform from django.contrib.postgres.indexes import GinIndex from django.contrib.postgres.search import SearchVectorField, SearchVector from django.db import models class ProfileUser(models.Model): name = JSONField() search_vector = SearchVectorField(null=True) class Meta: indexes = [GinIndex(fields=["search_vector"], name="user_full_name_gin_idx")] def save(self, *args, **kwargs): super(ProfileUser, self).save(*args, **kwargs) ProfileUser.objects.filter(pk=self.pk).update(search_vector=SearchVector('name')) # I have tried this, but this does not work. # ProfileUser.objects.filter(pk=self.pk).update(search_vector=SearchVector(KeyTextTransform('name', 'name'))) And name looks like [{'name': 'Random Name', 'lang': 'en'}, {'name': 'Какое-то Имя', 'lang': 'ru'}]. Currently the code above indexes both name and lang keys. Is it possible using Django to index just name key? I found how to workaround this using SQL directly, but I just want to know, if it is possible to do that just via Django. I use Django 2.2 and PostgreSQL 12. -
How to change model argument in inlineformset_factory?
It all works according to that logic. There is a Project model that contains general information about the project. Many users can work on this project (model Employee) and perform their part of the project work (model Work). I created a view for edditing forms using inlineformset_factory. forms.py ProjectEditFormSet = inlineformset_factory(Project, Work, form=WorkCreateForm, extra=0) models.py class Work(models.Model): """On which projects an employee has worked.""" employee = models.ForeignKey( Employee, on_delete=models.CASCADE, related_name='employee_projects') project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='project_work') start_year = models.CharField('work start year', max_length=4, default=datetime.datetime.now().year) start_month = models.CharField('work start month', max_length=10, default=datetime.datetime.now().month) end_year = models.CharField('work end year', max_length=4, default=datetime.datetime.now().year) end_month = models.CharField('work end month', max_length=10, default=datetime.datetime.now().year) responsibility = models.TextField("employee work responsibility", blank=True) technologies = models.ManyToManyField( Technology, verbose_name="technologies used on the project") class Project(models.Model): """Project information.""" name = models.CharField("project name", max_length=64) description = models.TextField("project description") views.py class WorkEditView(AuthorizedMixin, UpdateView): """ Edit new project instances """ model = Project form_class = ProjectForm template_name = 'work_edit.html' def get_context_data(self, **kwargs): context = super(WorkEditView, self).get_context_data(**kwargs) context['project_form'] = ProjectEditFormSet(instance=self.object) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) project_form = WorkFormSet(self.request.POST, instance=self.object) if form.is_valid() and project_form.is_valid(): return self.form_valid(form, project_form) else: return self.form_invalid(form, project_form) def form_valid(self, form, project_form): self.object = form.save() project_form.instance = … -
Django Dynamic Models with Control Panel
Hi all i want make a dynamic models for academic year registration form. 2019 2020 unique table 2020 2021 unique table and admin can create new form with models and active delete this. Whats wrong with this codes. and this idea is true? All academic year must own table or one table is enough. My Views class BasvuruFormCreateView(LoginRequiredMixin,CreateView): model = SinavBasvuruModel fields = ["grade","student_name","student_surname","student_tc","parent_name","parent_surname","parent_tel","parent_mail"] template_name = "includes/dashboard/addform.html" def form_valid(self, form): article = form.save(commit=False) article.author = self.request.user article.save() messages.add_message(self.request, messages.INFO, 'success.') return redirect("dashboard:addform") class SınavBasvuruDonemiView(LoginRequiredMixin,CreateView): model = SinavBasvuruDonem fields = ['title',"published"] template_name = "includes/dashboard/addyear.html" def form_valid(self, form): article = form.save(commit=False) article.author = self.request.user article.save() messages.add_message(self.request, messages.INFO, 'success.') return redirect("dashboard:addform") And Models class SinavBasvuruModel(models.Model): class Meta: abstract = True GRADE_CHOICES = ( (2, "2"), (3, "3"), (4, "4"), (5, "5"), (6, "6"), (7, "7"),) author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete = models.CASCADE) created_date = models.DateTimeField(auto_now_add = True) published = models.BooleanField(auto_created=True,default=False) student_name = models.CharField(max_length = 50,verbose_name=" Öğrenci Adı") student_surname=models.CharField(max_length = 50,verbose_name="Öğrenci Soyadı") student_tc=models.IntegerField(verbose_name="Öğrenci T.C. Kimlik Numarası") parent_name = models.CharField(max_length = 50,verbose_name="Veli Adı") parent_surname= models.CharField(max_length = 50,verbose_name="Veli Soyadı") parent_tel=models.IntegerField(verbose_name="Veli Telefon Numarası") parent_mail=models.EmailField(max_length = 254) grade = models.IntegerField(blank=False, null=False,verbose_name="Sınıf", default=1,choices=GRADE_CHOICES) def __str__(self): return self.title def get_absolute_url(self): return reverse('detail', args=[str(self.id)]) class SinavBasvuruDonem(SinavBasvuruModel): title = models.CharField(max_length = 50,verbose_name="Sınav Dönemi",unique=True,default=True) -
DRF getting random objects
I am going to get objects randomly but it shows one elements one more time. It should return all elements randomly without duplicate. Actually code I am using this it shows duplicates class ListObjectView(generics.ListAPIView): queryset = Model.objects.all().order_by('-pk').order_by('?') serializer_class = ExampleSerializer I also wrote custom function that takes randomly but It returns one object not all of them def get_random_objects(): return random.randrange(1, Model.objects.all().count() + 1) class ItemsListView(generics.ListAPIView): #queryset = Model.objects.all() serializer_class = ExampleSerializer def get_queryset(self): return Model.objects.all().filter(id=get_random_objects()) it only return one Model objects not all. How can I return all elements randomly? Any help plz? Thank you in advance! -
How to perform a single sign on between Django app and React JS app?
I have a django app and a react js app. The django app has some views, while the react dashboard is the link between the different views of the django app. My objective is: When user signs into the react app, the django app should also be logged in and logged out simultaneously. For the react app, I am using token authentication, and the token comes from a custom login method I have implemented using django-rest-auth library. api/views.py class LoginView(views.APIView): def post(self, request): serializer = LoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] login(request, user) token, created = TokenModel.objects.get_or_create(user=user) return Response({'token': token.key}, status=200) I am calling the token in the react client using axios. export const authLogin = (username, password) => { return dispatch => { dispatch(authStart()); axios.post('http://127.0.0.1:8000/rest-auth/custom/login/', { username: username, password: password },) .then(res => { const token = res.data; const expirationDate = new Date(new Date().getTime() + 3600*1000*24*7) //multiplied by 1000 because time is in milliseconds localStorage.setItem('token', token); localStorage.setItem('expirationDate', expirationDate); dispatch(authSuccess(token)); dispatch(checkAuthTimeout(3600)); }) .catch(err => { dispatch(authFail(err)) }) }} Here is how my settings.py file looks: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', ), } # AUTH_USER_MODEL = 'BankScoreCard.User' CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_HEADERS = ( 'xsrfheadername', 'xsrfcookiename', … -
Password not saving when creating user
I know there are hundreds of posts about that topic but, in all of them, there is something slightly different from my own program and I can't adapt it to my program because the Django way of handling password is such a mess that I understand nothing. A little help would be greatly appreciated, I thank you in advance. So, when a new user registers, everything works perfectly but, somehow, the password is not saved in the database. When I go to the admin interface, it tells me that the password format is invalid or the hashag function is not known. Here is my code : Forms.py class InscriptionForm(forms.ModelForm): class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password'] widgets = {'username': forms.TextInput(attrs={'class': 'form-control'}), 'first_name': forms.TextInput(attrs={'class': 'form-control'}), 'last_name': forms.TextInput(attrs={'class': 'form-control'}), 'email': forms.EmailInput(attrs={'class': 'form-control'}), 'password': forms.PasswordInput(attrs={'class': 'form-control'})} def clean_password(self): password = self.cleaned_data['password'] try: validate_password(password, user=self) except forms.ValidationError: self.add_error('password', password_validators_help_texts()) return password Views.py def inscription(request): if request.method == "POST": form = InscriptionForm(request.POST) if form.is_valid(): new_user = form.save() authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password'],) login(request, new_user) request.session['is_connected'] = True return redirect(inscription_suite) else: form = InscriptionForm() return render(request, 'inscription/inscription.html', {'form': form}) I already tried modifying the view like this : def inscription(request): if request.method == "POST": … -
How to send Dynamic data from Django backend to a React component?
I want to send a list of dictionaries from a function in Django backend to a React component in the frontend. This function runs once per day to update the data, so there's new data every day. What's the most optimal way to send/display this list in a React component? -
Django create instance of class from a choice select field
I am currently building a simple game library web app. My models.py file has two child classes (RetroGame, ModernGame) that inherit from the class 'Game'. When users add a new game to their library, it will be either a ModernGame or RetroGame. I'm trying to figure out how to set up a choice selection form that will then display the extra attributes I have listed within the child classes. Here is the code I have so far: from django.db import models from django.contrib.auth.models import User class Game(models.Model): name = models.CharField(max_length=200) genre = models.CharField(blank=True, max_length=100) players = models.PositiveIntegerField(default=1) publisher = models.CharField(blank=True, max_length=200) developer = models.CharField(blank=True, max_length=200) slug = models.SlugField() date_added = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) game_type = ( ('Retro', 'Retro Game'), ('Modern', 'Modern Game') ) type = models.CharField(max_length=6, choices=game_type) game_platform = ( ('PC', 'PC'), ('PS4', 'PS4'), ('XB1', 'Xbox One'), ('NS', 'Nintendo Switch') ) platform = models.CharField(max_length=3, choices=game_platform) def __str__(self): return self.name class ModernGame(Game): online_play = models.BooleanField(default=False) class RetroGame(Game): rom = models.CharField(blank=True, max_length=200) bios = models.CharField(blank=True, max_length=200) emulator = models.CharField(blank=True, max_length=200) -
Django Admin Validation for Inline ModelAdmin
I am using Tabular Inline for my admin page in which for an instruction there could be multiple scrap_code and event_code. But one scrap_code or event_code cannot have multiple instructions. I have made scrap_code and event_code throughout the table so that they cannot be duplicated. My admin.py class InstructionAdmin(admin.ModelAdmin): inlines = [ ScrapEventInstructionMapInline, ] fields=('name',) form = InstructionMapForm I need to show the users an alert when they try to enter event_code or scrap_code which already exists. But the problem is even if we have data instruction, s_code and e_code are coming as None My forms.py file:- class InstructionMapForm(forms.ModelForm): def clean(self): instruction = self.cleaned_data.get('instruction') s_code = self.cleaned_data.get('scrap_code') e_code = self.cleaned_data.get('event_code') qs = ScrapEventInstructionMap.objects.all() if s_code: dup_scrap = list(ScrapEventInstructionMap.objects.filter(scrap_code=s_code).values('scrap_code')) if dup_scrap: raise forms.ValidationError ('The Scrap Code provided ({}) already exists, kindly edit it or provide another Scrap Code'.format(s_code)) elif e_code: dup_event = list(ScrapEventInstructionMap.objects.filter(event_code=e_code).values('event_code')) if dup_event: raise forms.ValidationError ('The Event Code provided ({}) already exists, kindly edit it or provide another Event Code'.format(e_code)) How to get the data avoiding None? And how to show the alert to users? -
php or django which is best choice for future demand?
please help me..... I have completed html, css, bootstrap and js....now I need your suggestions.....which is best choice for future demand.... php & django they are both powerful language.....now which should I learn.....? -
Setting the selected value on a Django forms.select()
I am changing the code already written before me. There are a couple of selects that somehow remember the existing value when changing the record, I need to add another one. Repeated all the steps, but nothing works. I want to figure out what's wrong. model.py class Deal(models.Model): service = models.ForeignKey( Service, on_delete=models.CASCADE, related_name='deals_services' ) currency = models.ForeignKey( Currency, on_delete=models.CASCADE, related_name='deals_currencies' ) amounts_rule = models.TextField() comission_rule = models.TextField() weight_rule = JSONField(null=True, blank=True, default=dict()) active = models.BooleanField(default=True) provider_enabled = models.BooleanField(default=True) min_amount = models.IntegerField(default=0) max_amount = models.IntegerField(null=True, blank=True) payment_types = ArrayField(models.CharField(max_length=30), default=list()) adapter_account = models.ForeignKey( AdapterAccount, on_delete=models.CASCADE, related_name='deals_adapter_accounts' ) contractor_params = JSONField(null=True, blank=True, default=dict()) # Serializer @property def currency_iso_name(self): return str(self.currency) @property def service_name(self): return str(self.service) @property def adapter_account_name(self): return str(self.adapter_account) @signal_sending(pre_save_with_user, post_save_with_user) def save(self, *args, **kwargs): super(Deal, self).save(*args, **kwargs) def __str__(self): return 'Deal #{}'.format(self.pk) class Meta: db_table = '"processing"."deal"' permissions = ( ("can_see_deals", "Can see deals"), ) class Adapter(models.Model): contractor = models.ForeignKey( Contractor, on_delete=models.CASCADE, related_name='adapters_contractors' ) name = models.CharField(max_length=255) slug = models.SlugField(max_length=64) payment_type_group = models.CharField(max_length=64) def __str__(self): return self.name class Meta: db_table = '"processing"."adapter"' class AdapterManager(models.Manager): def get_queryset(self): return super(AdapterManager, self).get_queryset().select_related() class AdapterAccount(models.Model): adapter = models.ForeignKey( Adapter, on_delete=models.CASCADE, related_name='adapter_accounts_adapters' ) objects = AdapterManager() params = JSONField(null=True, blank=True) def __str__(self): return '#{} …