Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make login in django through a different table than auth_users?
Not sure what I am doing wrong I will leave below my files. The register method works perfectly but when I am doing the login, everytime the output is user is none. Does anyone know what I did wrong? I read the documentation of authentication with django but I cannot spot the problem. I saw that there were some questions about this problem, but I couldn't solve mine. settings.py AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('register/', views.registerMethod, name="register"), path('login/', views.loginMethod, name="login"), path('', include("main.urls")), path('', include("django.contrib.auth.urls")), ] views.py def registerMethod(request): if request.method=='POST': if request.POST.get('email') and request.POST.get('firstname') and request.POST.get('lastname') and request.POST.get('password'): user = NewUser() user.first_name = request.POST.get('firstname') user.last_name = request.POST.get('lastname') user.password = request.POST.get('password') user.email = request.POST.get('email') password = user.password.encode('utf-8') # Hash the ecoded password and generate a salt: hashedPassword = bcrypt.hashpw(password, bcrypt.gensalt(10)) user.password = str(hashedPassword) user.first_name = CleanString(user.first_name) user.last_name = CleanString(user.last_name) user.email = CleanString(user.email) message = None if UserExistsByEmail(user.email): message = 'You are already registered!' return render(request, 'register/register.html', {"message":message}) else: user.save() message = 'You have succesfully created an account!' return render(request, 'registration/login.html', {"message":message}) else: return render(request, 'register/register.html') else: return render(request, 'register/register.html') def loginMethod(request): if request.method == "POST": email = request.POST.get('email') password = request.POST.get('password') user = authenticate( email=email, password=password) if … -
How to solve coursera assigiment?
For this assignment work through Part 2 of the Django tutorial a [For this assignment work through Part 2 of the Django tutorial ] -
"from storages.backends.s3boto3 import S3Boto3Storage" not working
I imported django-storages and boto3 to my virtual enviroment and i am running the program within it but "storages.backends.s3boto3 import S3Boto3Storage" is not being recognized as a library and I am stumped. -
How to call a function when you delete a model object in django admin page? (or override delete action?)
I need to call a function whenever I have an object of a model deleted via admin page. How can I do such thing? -
Django error : exceptions caused by format_suffix_patterns are.error: redefinition of group name 'id' as group 2; was group 1 at position 56
my code works fine in my old computer, but I changed my computer suddenly I get this error, I couldn't fix it error: Traceback (most recent call last): File "/manage.py", line 22, in <module> main() File "/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/my_env/lib/python3.8/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/my_env/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/my_env/lib/python3.8/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/my_env/lib/python3.8/site-packages/django/core/management/base.py", line 412, in execute self.check() File "/my_env/lib/python3.8/site-packages/django/core/management/base.py", line 438, in check all_issues = checks.run_checks( File "/my_env/lib/python3.8/site-packages/django/core/checks/registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/my_env/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/my_env/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/my_env/lib/python3.8/site-packages/django/urls/resolvers.py", line 449, in check messages.extend(check_resolver(pattern)) File "/my_env/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/my_env/lib/python3.8/site-packages/django/urls/resolvers.py", line 449, in check messages.extend(check_resolver(pattern)) File "/usr/lib/python3.8/sre_parse.py", line 443, in _parse_sub itemsappend(_parse(source, state, verbose, nested + 1, File "/usr/lib/python3.8/sre_parse.py", line 831, in _parse raise source.error(err.msg, len(name) + 1) from None re.error: redefinition of group name 'id' as group 2; was group 1 at position 56 anyone knows how can i fix it? -
How can I show randomly different data for each user in Django?
I have a tag system in Django with the following model; class Data(models.Model): new = models.ChardField() is_tagged = models.BooleanField(default=False) class Tag(models.Model): data = models.ForeignKey(Data,on_delete=models.CASCADE,related_name="data") status = models.CharField(verbose_name="New Status",max_length=10,null=True) This model holds "positive", "negative", and "pass". There is a page called "new tags" and around 100 users will enter the page at the same time. There are 10000 data and users will enter the page and just click "positive", "negative", and "pass". I want to show different data for each user. It will prevent the users not seeing the same data and tagging the data 2 times. Let's say a user tagged the new as "positive". If I will send the new with random() it can be the same at another user unluckily. And the user can tag as "pass". This status will make "Data" "is_tagged" False. But other users tagged "positive" before. How can I prevent users see the same data at the same time? -
how can I send a message from a view to another view when use reverse in Django
I have 2 views for inserting phone number and another view is used to verify OTP code, now I want to send a message from verify view to the previous view that shows verify code is not valid or the time has expired. this view just check phone number that registar or not def manage_account(request,): form = RegisterForm(request.POST) if request.method == 'POST': # if user is exist just login else make user try: if 'phone_number' in request.POST: phone_number = request.POST.get('phone_number') user = UserPhone.objects.get(phone_number=phone_number) # send OTP otp = helper.get_random_otp() # helper.send_otp(phone_number, otp) # save otp user.otp = otp print('OTP:', otp) user.save() request.session['user_phone'] = user.phone_number # redirect to verify page return HttpResponseRedirect(reverse('verify')) except UserPhone.DoesNotExist: form = RegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) # send otp otp = helper.get_random_otp() # helper.send_otp(phone_number, otp) # save otp user.is_active = False user.otp = otp print('OTP:', otp) user.save() # for send a value to other pages request.session['user_phone'] = user.phone_number # redirect to verify page return HttpResponseRedirect(reverse('verify')) return render(request, 'registration/login.html', {'form': form, }) this view for verify OTP Code if is not valid or time has expired it reverse to manage_accout view that I want to send a message too. def verify(request): # for get value from … -
Move data from MySQL to PostgreSQL in Django application
I would like to move entire database in my Django app from MySQL to PostgreSQL. I now how to create such database, how to migrate tables but I am worried about user accounts and data that is on other tables. There is a lot of data there so I would like to know how in smart and efficient way move all data to PostgreSQL. Both databases are hosted on Azure. -
Django and React - npm run watch/build very slow
I'm trying to make a django/drf and react project but it takes 15+ seconds for npm run build to finish. What are my options here? It's not feasible to wait that long after every change I make to the front end. Should I keep the react and django parts separate till the end? I followed these instructions since I'm new to npm: https://medium.com/how-to-react/use-npm-watch-to-auto-build-your-reactjs-app-6ed0e5d6cb00 -
Using reportlab to create watermark on a pdf, how do I place the text on the top left hand corner
I have this code, what it does is it converts images to pdf and add a generated name to to the top left corner of the pdf. problem is the last part, the text placement is not where I want it to be,the top left corner. I am using reportlab and PIL import sys from PIL import Image from io import BytesIO from django.core.files.uploadedfile import InMemoryUploadedFile from PyPDF2 import PdfFileWriter, PdfFileReader from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter can = canvas.Canvas(packet, pagesize=letter) can.drawString(10, 100, name) can.save() packet.seek(0) new_pdf = PdfFileReader(packet) existing_pdf = PdfFileReader(document, "rb") output = PdfFileWriter() # add the "watermark" (which is the new pdf) on the existing page page = existing_pdf.getPage(0) page2 = new_pdf.getPage(0) page.mergePage(page2) output.addPage(page) # finally, write "output" to a real file buf = BytesIO() # outputStream = open(f"{name}.pdf", "wb") output.write(buf) buf.seek(0) What's the solution to this? any resources maybe in the documentation will be helpful. -
Issue with s3 bucket for STATIC FILES and Django
Something weird is happening and it might be an easy fix, but for the life of me I cant figure it out. When I use AWS_S3_CUSTOM_DOMAIN my website wont launch the static files but if i ignore the custom domain it works. if i use this it works fine # AWS SETTINGS AND ENVIROMENTVARIABLES AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = os.environ.get("AWS_STORAGE_BUCKET_NAME") # AWS_S3_CUSTOM_DOMAIN = "%s.s3.amazonaws.com" % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"} # AWS_DEFAULT_ACL = None AWS_LOCATION = "static" STATICFILES_DIRS = [ os.path.join(BASE_DIR, "spotify/static"), ] STATIC_URL = "https://%s/%s/" % (AWS_STORAGE_BUCKET_NAME, AWS_LOCATION) STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" # AWS_S3_FILE_OVERWRITE = False # AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" AWS_S3_REGION_NAME = "us-east-2" AWS_S3_SIGNATURE_VERSION = "s3v4" but if i use this way, which is how everyone usually does it, it wont find the correct files # AWS SETTINGS AND ENVIROMENTVARIABLES AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = os.environ.get("AWS_STORAGE_BUCKET_NAME") AWS_S3_CUSTOM_DOMAIN = "%s.s3.amazonaws.com" % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"} # AWS_DEFAULT_ACL = None AWS_LOCATION = "static" STATICFILES_DIRS = [ os.path.join(BASE_DIR, "spotify/static"), ] STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" # AWS_S3_FILE_OVERWRITE = False # AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" AWS_S3_REGION_NAME = "us-east-2" AWS_S3_SIGNATURE_VERSION = "s3v4" -
Django 4 migrate error: c.releasepartition does not exist
When trying to migrate, I am getting an error: Traceback (most recent call last): File "/var/www/..../venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) psycopg2.errors.UndefinedColumn: column c.relispartition does not exist LINE 3: CASE WHEN c.relispartition THEN 'p' WHEN c.relki... ^ -
Is it possible to use filter and classmethod at the same time?
I have model like this, and it has the function which use the custom function which works as filter in models.py class Item: status = models.IntegerField(blank=True, null=True) power = models.IntegerField(blank=True, null=True) def get_regular(): cls.objects.filter(status__lt=12) Now I want to use like this from another script. (this sentence is wrong though) in views.py import models Item.get_regular.filter(power=14) I know I can do this below, but cls.objects.filter(status__lt=12).filter(power=14) I want to reuse the get_regular function in models.py Because this function is called from other places, and I want to keep it here one place. -
The directory '/static/' in the STATICFILES_DIRS setting does not exist. (Visual Studio)
When I want to "python manage.py makemigrations", it returns the following. System check identified some issues: WARNINGS ?: (staticfiles.W004) The directory '/static/' in the STATICFILES_DIRS setting does not exist. How should I solve this issue? Thanks in advance. -
For ocr scanner based web app does flask is useful in python?
i am university student and new on python. i have to submit my final year project base on web app in which you can scan image and convert it into digital text. Also some other features i want to add like Conversion of text into handwritten format Conversion of mp3 file into text form Handwritten text into digital form Conversion of digital text into and other language I want to ask that which framework i need to learn after python to make web app like this and can flask will be useful for me? -
Statistic in template show CombinedExpression for one field
I have problem with template render. It shows statistic table for Document model (counts of views, downloads, likes, dislikes), but view_count in final html is not a number, it's an CombinedExpression object like F(view_count) + Value(1). Perhaps the reason for my problem is that I am updating a statistic and adding it to the template in the same part of the code. # views.py class DocumentDetailView(DetailView): ... def get(self, request, *args, **kwargs): self.object = self.get_object() self.statistic = FileStatistic.objects.get(document=self.object) self.statistic.increment_field('view_count') context = self.get_context_data(object=self.object, statistic=self.statistic) return self.render_to_response(context) # models.py # NOTE: this model class is OneToOneField referenced in Document model class. class FileStatistic(models.Model): download_count = models.IntegerField( default=0, verbose_name='Количество скачиваний' ) view_count = models.IntegerField( default=0, verbose_name='Количество просмотров' ) like_count = models.IntegerField( default=0, verbose_name='Количество лайков' ) dislike_count = models.IntegerField( default=0, verbose_name='Количество дизлайков' ) def increment_field(self, field_name: str) -> None: setattr(self, field_name, models.F(field_name) + 1) self.save(update_fields=[field_name]) <table class="table table-borderless table-sm"> <thread> <tr> <th class="text-center" scope='col'>Число скачиваний</th> <th class="text-center" scope='col'>Число просмотров</th> <th class="text-center" score='col'>Число лайков</th> <th class="text-center" score='col'>Число дизлайков</th> </tr> </thread> <tbody> <tr> <td class="text-center border-top">{{statistic.download_count}}</td> <td class="text-center border-top">{{statistic.view_count}}</td> <td class="text-center border-top">{{statistic.like_count}}</td> <td class="text-center border-top">{{statistic.dislike_count}}</td> </tr> </tbody> </table> Output: -
How to register as an admin in Django app using Registration Model and Views.py?
I am familiar with creating a superuser in a Django App using python manage.py createsuperuser command in terminal. I am also familiar with creating a superuser using Python Shell. But I want to know that how do we register a user as an admin in a Django App using RegistrationModel and views.py? Or more specifically, how to register the user and change it's status to staff or superuser in views.py? -
Docker python:alpine image can not install backports.zoneinfo using pip
I was trying to dockerize an django app. My requirements.txt had backports.zoneinfo. But when ever I try to install this packages docker is showing error. I tried the same in regular image (not alpine or slim) then it was working fine. I have tried upgrading pip, tzdata, wheel, gcc. But no luck. -
django download view downloading only .xls instead of file with extension on model
I have my django view where i upload the file from admin and users download it on front end when i downlaod the file on the frontend the download is extension with only .xls i.e when i upload the file with .xlsx extension it is still down;load ing with .xls instead the file should be downloaded according to the extension either its xls or xlsx. views.py class myAPIView(APIView): def get(self, request): data = Model.objects.first() return HttpResponse( data.file, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel', ) -
Regex patter to capture all variables in url including forward slash
I want to match dynamic created urls which can have multiple endpoints. Need some regex pattern for this. For ex. http://127.0.0.1:8000/api/:user_id/:endpointa/:endpoint1/ http://127.0.0.1:8000/api/:user_id/:endpointb/:endpoint2/:endpoint3/:endpoint4 http://127.0.0.1:8000/api/:user_id/:endpointc/:endpoint2/ http://127.0.0.1:8000/api/:user_id/:endpointd/:endpoint1/:endpoint2/ so till BASE_URL/api/:user_id/ is common. I am able to catch user_id but want to catch other params after user_id on single string variable. after that there can be any number of endpoints and I want to catch them all in one single string variable. like for first url string variable catched will be "endpointa/endpoint1/" and for next url string variable will be "endpointb/endpoint2/endpoint3/endpoint4" along with fwd slashes. What regex pattern should I write in urls.py for capturing this variables? I tried with re_path(r'(?P<user_id>[-\w]+)/(?P<customUrl>(.*?)(?:\/)?$)/.*', customLink, name='customLink'), but couldn't get it work. -
Ajax post request is printing json response on empty html page instead of html signup page
I am making a website in django with ajax.I have created a base html file django template and two other html templates named signup.html and home.html. I have written code to make ajax request with signup form in base.html file like this. $("#signupBtn").click(function() { event.preventDefault(); username=$('#id_username').val(); password1=$('#id_password1').val(); password2=$('#id_password2').val(); data={username=username,password1=password1,password2=password2} $.ajax({ type:'POST', url:'{% url "signup" %}', data:data, success:function(response){ // $('#msg').html(`<p style="font-size: 30px;color: lime;font-weight: bold;">User created succcess!</p>`); console.log('FORM SUCCESS!') window.location='{% url "home" %}' }, error:function(){ } }) }); and my signup views is like this: class signup(View): def post(self,request): fm=UserCreationForm(request.POST) if fm.is_valid(): fm.save() return JsonResponse({'status':1}) fm=UserCreationForm() return JsonResponse({'status':0}) def get(self,request): fm=UserCreationForm() return render(request,"home/signup.html",{"form":fm}) Main problem is this ,when there goes Get request form is showing and we can enter all details to create account and also account created successfully in admin panel,But in post request,after saving the form ,i get json response printed on blank page instead of getting again that signup page. How this is possible to return to the same page after post request is made? THIS IS PROBLEM: please check the problem as show in image -
Regarding Backend Framework
Hello guys I need a small piece of advice from you like I have completed django and flask and I have industrial experience on them now I am willing to learn a new backend language but I am confused in between go-lang,node.js,ruby on rails.First I thought to learn go lang bcz its very fast but when I researched about it there are negligible job opportunities for junior go lang developers so I am confused can you tell me what to do -
DJango Login Issue with incoorect credentials
If I try to enter wrong username and password it shows an tuple error, not my message def login(request): if request.method == 'POST' : username=request.POST['username'] password=request.POST['password'] user=auth.authenticate(username=username,password=password) if user is not None: auth.login(request,user), return redirect('/') else: messages.info(request,"invalid username or password"), return redirect('login'), return render(request,"login.html") enter image description here -
Django Classbased views with condition
I created script in function based view in django and I want to convert it into classbased views with if/else condition. I done searching but I didn't found the solutions. Sorry for a basic question, Im new in django and start learning. This is my function script that I want to convert in Classbased views. def vm_create(request): if request.method == 'POST': Number = request.POST.get('number') Date = request.POST.get('date') if Date == '': Date = None else: Date = datetime.datetime.strptime(or_date,'%Y-%m-%d') month = '' endnum = '' if Number != '': endnum = int(Number[-1]) if endnum == 1: month = 'January' elif endnum == 2: month = 'Febuary' save = Models(CS_Number=Number, CS_Date=Date, CS_Month=month) I tried to convert to classbased but return is not working. class vm_create(CreateView): model = models form_class = forms template_name = 'cs_form.html' def create_new(self, request, *args, **kwargs): endnum = '' if request.GET.get('Number') != '': endnum = int(Number[-1]) if endnum == 1: return 'January' elif endnum == 2: return 'Febuary' return super().create_new(request, *args, **kwargs) -
Does PasswordResetConfirmView.py auto populate uid and token?
The view definitely does not populate on my end but password_reset_confirm.html in the demo template folder seems to do that. password_reset_confirm_form.html Any help appreciated. url.py path("dj-rest-auth/password/reset/confirm/<str:uid>/<str:token>/", # TemplateView.as_view(template_name="password_reset_confirm.html"), PasswordResetConfirmView.as_view(), name='resend-email-verification' ), edit: maybe this webpage here is not the same page in dj-rest-auth demo folder...