Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Overwrite/replace instead of update MySql table in a Django Project
Let's say I have df1 which is pulled from a MySql database in a django project: import pandas as pd df1 = pd.DataFrame({'Name': ['John', 'Jim'] ,'City': ['A', 'B'],'Project_id': 1}) df1 Then my function within django adds two rows: line_insert = pd.DataFrame({'Name': ['Jack', 'Jill'] ,'City': ['C', 'D']}) df1 = df1.append(line_insert).reset_index(drop=True) df1 Now i would like to save this dataframe back to the table in the database. My current code updates the sql table row by row (where Project_id = 1) but i am wanting to replace the dataframe with the same Project_id My current code to update the table is (for simplistic sake i have defined some variables first): proj_id = 1 iincreament_id = 1 for index, df_series in df1.iterrows(): dict_df = df_series.to_dict() """ Insertig dataframe into dict """ dict_df['Projectid_id'] = proj_id """ updating SQL DB """ sql_db.objects.filter(id=iincreament_id,Project_id=proj_id).update(**dict_df) iincreament_id += 1 So what this does is updates row 1 & 2 values with their new values but does not replace the sql table with the new table to bring in rows 3 & 4. Is there any ideas on a replace function using the .objects functions with python/django? Thanks very much! -
Why is Django Rest Knox token don't have three sections?
I am new to JWT and integrated django-rest-knox to my project. When I test it in postman, i get a token like b0073060117223714a3405ad7c1516ba61f7216b2165a40cb44b43b2c54d8dd4, but I know that JWT must have 3 sections. Why it don't have ones? -
How do I subtract from exiting model if a request is sent from another model?
Am trying to create a withdrawal request, the request sent successfully as expected but it doesn't subtract from the existing balance. Here's my model. def withdrawals(request): if request.method == 'POST': Input_Amount = request.POST['Input_Amount'] username = request.POST['username'] input_password = request.POST['password'] total = Users_Balanc.objects.get(user=request.user) if Withdrawal_password.objects.filter(username=request.user).exists(): password = Withdrawal_password.objects.get(username=request.user) if password.password3 == input_password: if int(Input_Amount) > 100: if (total.Amount >= float(Input_Amount)): New_Request = Request.objects.create(Wallet_Address=password.Wallet_Address, Amount=Input_Amount, user = username) New_Request.save messages.success(request, 'Successful') return redirect('withdrawals') else: messages.warning(request, 'Insufficient funds') return redirect('withdrawals') else: messages.warning(request, 'Sorry, your withdrawal is below 100TRX') return redirect('withdrawals') else: messages.warning(request, 'Sorry, your withdrawal password is not correct') return redirect('withdrawals') else: messages.warning(request, 'Sorry, you haven\'t create a withdrawal password yet.') return redirect('withdrawals') else: balance = Users_Balanc.objects.filter(user=request.user) return render(request, 'withdrawals.html', {'balance': balance}) Even when I add total.Amount - Input_Amount just after if (total.Amount >= float(Input_Amount)) Please what's the way around this? -
Django - Reset all filters
I am trying to clear all filters on button click at once. This is what I have on filters.py file and filters class: class Filters(django_filters.FilterSet): id = django_filters.NumberFilter(label=_("ID")) name = django_filters.TextFilter(label=_("Name")) And in base template: <form id="filters-filters-form" action="javascript:;" onsubmit="onSubmit(this)" class="form form-inline main-filter"> {% bootstrap_form filter.form layout='inline' %} <div> <button class="btn ml-auto mr-2" onclick="resetFilters()">Clear all</button> {% trans "Apply" as button_text %} {% bootstrap_button button_text button_class="btn-primary" %} </div> </form> resetFilters() function: var resetFilters = function() { let formId = document.getElementById('filters-form') let formChildren = formId.childNodes; Array.from(formChildren).forEach(formChild => { formChild.val(null).trigger('change') }); } Is there any easy way to reset all filters? P.S: I need to reset these filters without any id of form-control because it will be reusable base template -
Forward reference must be an expression -- got 'postgresql
I am getting this error Forward reference must be an expression -- got 'postgresql Here is the complete log Traceback (most recent call last): File "/usr/local/lib/python3.9/typing.py", line 528, in __init__ code = compile(arg, '<string>', 'eval') File "<string>", line 1 postgresql+asyncpg://postgres:postgres@db:5432/blog ^ SyntaxError: invalid syntax During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/code/asgi.py", line 3, in <module> from api.app import create_app File "/code/api/app.py", line 2, in <module> from api.database import create_db_and_tables File "/code/api/database.py", line 3, in <module> from api.config import settings File "/code/api/config.py", line 8, in <module> class Settings(BaseSettings): File "/usr/local/lib/python3.9/site-packages/pydantic/main.py", line 179, in __new__ annotations = resolve_annotations(namespace.get('__annotations__', {}), namespace.get('__module__', None)) File "/usr/local/lib/python3.9/site-packages/pydantic/typing.py", line 395, in resolve_annotations value = ForwardRef(value, is_argument=False, is_class=True) File "/usr/local/lib/python3.9/typing.py", line 530, in __init__ raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}") SyntaxError: Forward reference must be an expression -- got 'postgresql+asyncpg://postgres:postgres@db:5432/blog' Here is how I am using it class Settings(BaseSettings): PROJECT_NAME: str = f"SQLModel API - {os.getenv('ENV', 'development').capitalize()}" DESCRIPTION: str = "A FastAPI + SQLModel production-ready API" ENV: str = os.getenv('ENV', 'development') VERSION: str = "1" SECRET_KEY: str = secrets.token_urlsafe(32) # DATABASE_URI: Optional[PostgresDsn] = None DATABASE_URI: os.environ.get("DATABASE_URL") # sql Where env variable is being set like … -
Html code is not working in django block content
i understand the basic tag blocks but it didn't works well on my page. i have page called base.html and home.html **base.html !DOCTYPE html> <html> <body> {% include 'component/models.html' %} {% include 'component/header.html' %} {% block content %} inside this my code is not comming {% endblock %} {% include 'component/footer.html' %} </body home.html {% extends 'base.html' %} {% load static %} {% block content %} <h1>This code working <h1> <section> <h1>Rahul guptaa1</h1> <div> <h1>Rahul guptaa 2</h1> <div> <h1>Rahul guptaa 3</h1> <div> <h1>Rahul guptaa4</h1> </div> <div> <h1>Rahul guptaa5</h1> </div> </div> </div> <div> <h1>Rahul guptaa6</h1> </div> </section> {% endblock content %} **my output below but Rahul guptaa4 Rahul guptaa6 is not showing ... Rahul guptaa5 Learn On Your Schedule Technology Is Bringing A Massive Wave Of Evolution On Learning Things In Different Ways. ** Rahul guptaa1 Rahul guptaa 2 Rahul guptaa 3 Rahul guptaa5 *** i am not beginner in django but i face problem here i try so many times if you want to know my folder structure below myproject -myproject -App -templates -base.html -main -home.html ** Rahul guptaa1 Rahul guptaa 2 Rahul guptaa 3 Rahul guptaa4 Rahul guptaa5 Rahul guptaa6 ** -
Redirect non authenticated user to login page (for all views)
I am looking to redirect my user to login page, if they have not logged in. I initally looked at the decorator @login_required(login_url='/accounts/login/'). But this is not ideal, for 2 reasons: first I want this to apply to all views. Also the decorator returns an error message when I try to login with allauth. I am sure this is solvable, but I am looking for a solution that could apply to all views. I found something using authmiddleware(doc: https://pypi.org/project/django-authmiddleware/). However the code doesn't not seem to be responsive, in the sense nothing is happening and the logs on the console don't seem to pick up anything. Can someone see what I am doing wrong? base.py MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'AuthMiddleware.middleware.AuthRequiredMiddleware', ] AUTH_SETTINGS = { "LOGIN_URL" : "login_user", "DEFAULT_REDIRECT_URL" : None, "REDIRECT_AFTER_LOGIN" : False, } views.py from django.shortcuts import render, redirect, reverse from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth import authenticate, login, logout, get_user_model from django.urls import reverse class AuthRequiredMiddleware(object): def process_request(self, request): if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('login_user')) return None -
django: unable to login after successful registration
login reporting wrong username or password, after a new user is registered successfully. I am sure the there is no typo! below is my code and I guess the problem is to do with the hash code related to the password setup? @csrf_exempt def api_register(request): data = json.loads(request.body) username = data['username'] password_1 = data['password_1'] password_2 = data['password_2'] # 1,check if two pw is same if password_1 != password_2: return JsonResponse({"code": 0, "msg": "pw not consistant"}) else: m = hashlib.md5() m.update(password_1.encode()) password_m = m.hexdigest() # 2 check if username exists users = User.objects.filter(username=username) if users: return JsonResponse({"error": "username already exists"}) else: try: user = User.objects.create_user(username = username, password = password_m) user.set_password(password_m) user.save() user.is_active = True user.success = True ret_data = {"username": user.username, 'uid': user.id, 'password': user.password} token = TimestampSigner(sep='.').sign_object(ret_data) ret_data['token'] = token ret = {"code": 1, "msg": ret_data} except Exception as e: print('--create user error is %s' % e) return JsonResponse({"error": "username already exists"}) return JsonResponse(ret) below is login function @csrf_exempt def api_login(request): data = json.loads(request.body) user = authenticate(**data) #same as authenticate(username=data['username'],password=data['password'] if user: ret_data = {"username":user.username,'uid':user.id} token = TimestampSigner(sep='.').sign_object(ret_data) ret_data['token'] = token ret = {"code":1,"msg":ret_data} print("ret ", ret) else: ret = {"code":0,"msg":"username or password wrong!" } return JsonResponse(ret) -
"No module named manage" error when trying to debug a Werkzeug Django app in VSCode
As the title says. I have a Django app, which uses Werkzeug to enable https. I have the following launch.json set up: { "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "python": "${workspaceFolder}/venv/Scripts/python.exe", "program": "${workspaceFolder}\\appname\\manage.py", "args": [ "runserver_plus", "--cert-file", "${workspaceFolder}/certs/cert.pem", "--key-file", "${workspaceFolder}/certs/key.pem" ], "justMyCode": false, "django": true } ] } When I run this through the VSCode debugger it immediately quits in the get_wsgi_application() function with "No module named manage". I tried googling around, but no answer proved to be useful. Any ideas what I am doing wrong? -
MultiValueDictKeyError at /"" when uploading empty file
I have a django 4 application and if a a user try to upload a empty file, then this error occurs: MultiValueDictKeyError at /controlepunt140 'upload_file' I searched for that error. But it seems that the template is oke. Because the enctype is set correct: enctype="multipart/form-data" <form class="form-inline" action="/controlepunt140" method="POST" enctype="multipart/form-data"> <div class="d-grid gap-3"> <div class="form-group">{% csrf_token %} {{form}} <button type="submit" name="form_pdf" class="btn btn-warning">Upload!</button> </div> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" id="content" cols="70" rows="25"> {{content}}</textarea> </div> </div> </div> </form> and views.py: def post(self, *args, **kwargs): filter_text = FilterText() extract_excel_instance = ExtractingTextFromExcel() types_of_encoding = ["utf8", "cp1252"] submitted_form = ProfileForm(self.request.POST, self.request.FILES) content = '' content_excel = '' if self.request.POST.get('form_pdf') is not None: if submitted_form.is_valid() and self.request.POST: uploadfile = UploadFile( image=self.request.FILES["upload_file"]) uploadfile.save() for encoding_type in types_of_encoding: with open(os.path.join(settings.MEDIA_ROOT, f"{uploadfile.image}"), 'r', encoding=encoding_type) as f: if uploadfile.image.path.endswith('.pdf'): content = filter_text.show_extracted_data_from_file( uploadfile.image.path) else: content = f.read() return render(self.request, "main/controle_punt140.html", { 'form': ProfileForm(), "content": content }) return render(self.request, "main/controle_punt140.html", { "form": submitted_form, }) and forms.py: class ProfileForm(forms.Form): upload_file = forms.FileField(required=False) So how to tackle this? -
DJANGO - Unique records via ORM
I'm new to DJANGO and was hoping to get some help achieving this. I've been stuck on this for a few weeks trying out multiple answers found in StackOverflow, but no luck... Any help or guidance will be appreciated. Issue: As a business case, I need to collect all raw data (order updates). Because daily updates of the same order are provided daily and stored; we start accumulating a lot of duplicate data with different import dates. Objective: To create a table view that displays only the changes per order via ORM if possible. Disclaimer: I have achieved the desired result by handling the dataset through pandas. not in a postgres thus, thus distinct() doesn't work models.py OrderUpdates(models.Model): import_date = models.DateField(auto_now=False, auto_now_add=False) order_number = models.CharField(max_length=15,unique=False) field1 = models.CharField(max_length=25,unique=False) Sample Expectation: *RAW DATA* import_date order_no field1 10/30/22 A raw 10/30/22 B raw 11/01/22 A raw 11/01/22 B raw 11/02/22 A updated 11/03/22 B raw 11/03/22 A updated 11/03/22 B raw *UNIQUE VIEW* import_date order_no field1 10/30/22 A raw 11/02/22 A updated 10/30/22 B raw Approach: My current approach is as follows: Query the object > create a composite key > order by composite key and import date > get a count … -
Apache doesn't allow access to media files
I'm trying to set up my Apache so it can serve media files saved inside a Django Backend. Django is already in production mode (DEBUG=False) and I have SSL set up. I have one domain with a reverse proxy serving my frontend and a subdomain (api.domain) serving my Django backend. I'm now trying to serve my media files in backend/app/media/ from apache. My subdomain ssl .conf file in sites-available contains the following code inside the <VirtualHost *:433>: Alias /media/ /home/backend/main/media/ <Directory /home/backend/main/media> Options Indexes MultiViews AllowOverride None Require all granted Order allow,deny Allow from all </Directory> I tried this code block also inside my apache2.conf file but that didn't work either. Also worth mentioning, I don't get the default Apache "Service Unavailable" error when trying to access the files via the browser. I get (only if the Django Server runs) the Django production "Not Found" view. Therefore I guess it handles my request via Django which is expectable since I'm accessing the api subdomain serving Django. How can I manage to access my files served by Apache? When trying to access my domain, I get forwarded to my frontend and when trying it via the subdomain, I get forwarded to … -
How to automatically get user in django admin through form
I have a form in my django website where the user requests coins and the information is sent to the admin for me to process. I want to automatically get the user who filled the form without them doing it themselves. Here's the model.py file: class Requestpayment (models.Model): username= models.ForeignKey(User, on_delete= models.CASCADE, null=True) useremail= models.CharField(max_length=100) accountmail= models.CharField(max_length=100) accountphonenumber=models.CharField(max_length=15) coinsrequested=models.ForeignKey(Requestamount, on_delete= models.SET_NULL, null=True) created= models.DateTimeField(auto_now_add=True) def __str__(self): return self.accountmail the forms.py: class Requestpaymentform (ModelForm): class Meta: model = Requestpayment fields = '__all__' and the views.py: @login_required(login_url='login') def redeemcoins (request): form = Requestpaymentform if request.method =='POST': form = Requestpaymentform(request.POST) if form.is_valid(): form = form.save(commit=False) username = request.user form.save() return redirect ('home') I am pretty sure something is wrong but i don't know what it is (I'm very new at django) anyway the form always shows all the users in the website for the current user to pick who they are. enter image description here I also tried excluding that part of the form but it didn't work it just shows up empty in the admin. thank you. -
How to ADD registration email verifiction to my Django app
How to ADD registration email verifiction to my django app? I want to add an email registration verification and email and password reminder? my big problem solving -
Cannot resolve keyword 'slug' into field
Im making comment and reply system in my blog using Django. Now im trying to get queryset of comments that dont have reply comments(if I dont do this, reply comments will be displayed on a page as regular comments). Here is error that i got: FieldError at /post/fourh-news Cannot resolve keyword 'slug' into field. Choices are: comm_to_repl, comm_to_repl_id, comment_content, created, id, post, post_of_comment, post_of_comment_id, replies, user_created_comment, user_created_comment_id Request Method: GET Request URL: http://127.0.0.1:8000/post/fourh-news Django Version: 4.1.2 Exception Type: FieldError Exception Value: Cannot resolve keyword 'slug' into field. Choices are: comm_to_repl, comm_to_repl_id, comment_content, created, id, post, post_of_comment, post_of_comment_id, replies, user_created_comment, user_created_comment_id Exception Location: D:\pythonProject28django_pet_project\venv\lib\site-packages\django\db\models\sql\query.py, line 1709, in names_to_path Raised during: blog.views.ShowSingleNews Python Version: 3.10.4 Model: class Post(models.Model): title = models.CharField(max_length=150, verbose_name='Название') slug = models.CharField(max_length=100, unique=True, verbose_name='Url slug') content = models.TextField(verbose_name='Контент') created_at = models.DateTimeField(auto_now=True, verbose_name='Дата добавления') updated_at = models.DateTimeField(auto_now=True, verbose_name='Дата обновления') posted_by = models.CharField(max_length=100, verbose_name='Кем добавлено') photo = models.ImageField(upload_to='photos/%Y/%m/%d', verbose_name='Фото', blank=True) views = models.IntegerField(default=0) category = models.ForeignKey('Category', on_delete=models.PROTECT, verbose_name='Категория') tag = models.ManyToManyField('Tags', verbose_name='Тэг', blank=True) comment = models.ForeignKey('Comment', verbose_name='Комментарий', on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('single_news', kwargs={'slug': self.slug}) class Meta: ordering = ['-created_at'] class Category(models.Model): title = models.CharField(max_length=150, verbose_name='Название') slug = models.CharField(max_length=100, unique=True, verbose_name='category_url_slug') def __str__(self): return self.title def … -
How to access queryset values in a dictionary - Python
I'm trying to access the queryset of this dictionary with no success: {'post': <Post: alta papa>, 'distance': '0'} I've tried for thing in post... but is giving me a str value... instead of the queryset... Any help will be welcome. -
Django send password reset link via email when new user account added
I am working on an application where admins will create new user accounts. A randomized password is auto-generated when the user is added. Ideally an email will be automatically sent to the new user with a link to reset their password (It will not include the autogenerated password). I could figure out how to send an email with link to a page to enter an email to get a password reset link. However, I would like to avoid the extra steps and simply send the link to reset the password. Any suggestions about how to trigger and send this link? The model: from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import Group from django.contrib import admin from django.db.models import Count from django.db.models.signals import post_save class CustomUser(AbstractUser): full_name = models.CharField(max_length=250, null=True) age = models.PositiveIntegerField(null=True, blank=True) employee_type = models.ForeignKey(Group, null=True, on_delete=models.SET_NULL, default=1) employee_start_date = models.DateField(null=True, blank=True) is_active = models.BooleanField(null=False, default=True) The view: class AddCompanyEmployee(CreateView): model = CustomUser template_name = 'manage/add_employee.html' form_class = BrowserCreateUserForm success_url = reverse_lazy('directory') def form_valid(self, form): password = CustomUser.objects.make_random_password() account = form.save(commit=False) account.password = make_password(password) account.save() return super().form_valid(form) The form: class BrowserCreateUserForm(forms.ModelForm): class Meta: model = CustomUser fields = ['username','full_name', 'email', 'employee_type', 'employee_start_date', 'is_active'] widgets = { … -
Python script inside of html <script> tag
this is html template in Django. I have Mapbox map and i need to pass markers from Django database via forcycle "{% for address in addresses %}... " ` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src='https://api.mapbox.com/mapbox-gl-js/v2.1.1/mapbox-gl.js'></script> <link href='https://api.mapbox.com/mapbox-gl-js/v2.1.1/mapbox-gl.css' rel='stylesheet' /> <title>Document</title> </head> <body> <h1>Django Home</h1> <form method='POST'> {% csrf_token %} {{ form }} <input type="submit" value="submit address" /> </form> <div id='map' style='width: 100%; height: 600px;'></div> <script> mapboxgl.accessToken = '{{ mapbox_access_token }}'; var map = new mapboxgl.Map({ container: 'map', // container ID style: 'mapbox://styles/mapbox/streets-v11', // style URL center: [-111.061854, 45.695711], // starting position [lng, lat] zoom: 11 // starting zoom }); {% for address in addresses %} var marker = new mapboxgl.Marker() .setLngLat([{{ address.long }}, {{ address.lat }}]) .setPopup(new mapboxgl.Popup().setHTML("<p>{{ address.address }}</p>")) .addTo(map); {% endfor %} </script> </body> </html> ` Source code: https://github.com/Simonm17/mapbox_demo/blob/master/templates/addresses/home.html This code above from Github works fine for author in Youtube video, but i got red underline text and nothing happens. How i can combine python script inside html tag and pass markers from python? Thx! -
Passing variable to inherited template in Django
I want to list servers in the sidebar. Server data comes from database. All the pages will have the sidebar and sidebar is in the inherited template. I found one solution: Passing via middleware I can write a custom middleware, so I can pass the servers to request object. But at this point I have to pass servers variable again and again to the templates and inherited template in each view. This is a lot of repeated code. Is there a cleaner solution? -
Django - issue with Not Null constraint
Hi in my program I keep receiving the above exception and am unsure why. The issue happens when my requestLessons_view method tries to save the form. Views.py def requestLessons_view(request): if request.method == 'POST': form = RequestLessonsForm(request.POST) if form.is_valid() & request.user.is_authenticated: user = request.user form.save(user) return redirect('login') else: form = RequestLessonsForm() return render(request, 'RequestLessonsPage.html', {'form': form}) forms.py class RequestLessonsForm(forms.ModelForm): class Meta: model = Request fields = ['availability', 'num_of_lessons', 'interval_between_lessons', 'duration_of_lesson','further_information'] widgets = {'further_information' : forms.Textarea()} def save(self, user): super().save(commit=False) request = Request.objects.create( student = user, availability=self.cleaned_data.get('availability'), num_of_lessons=self.cleaned_data.get('num_of_lessons'), interval_between_lessons=self.cleaned_data.get('interval_between_lessons'), duration_of_lesson=self.cleaned_data.get('duration_of_lesson'), further_information=self.cleaned_data.get('further_information'), ) return request models.py class Request(models.Model): student = models.ForeignKey( User, on_delete=models.CASCADE ) availability=models.CharField(blank=False, max_length=5) num_of_lessons=models.CharField(blank=False,max_length=40) interval_between_lessons=models.CharField(blank=False,max_length=30) duration_of_lesson=models.CharField(blank=False,max_length=60) further_information=models.CharField(blank=False,max_length=300) is_fulfilled=models.BooleanField(default=False) The error I receive is: IntegrityError at /request_lessons/ NOT NULL constraint failed: lessons_request.student_id -
django how to generate commercial offers
I am developing a business website in django. and there was a task - to add the ability to generate commercial offers. it is necessary for the user to be able to select a product from the database, and after that the remaining fields (category, price, description, photo) would be automatically substituted. I do not quite understand how to implement it correctly. Is it possible to do this in the admin panel or do I need to create a new page and write all the logic in views. models.py: class product(models.Model): title = models.CharField(max_length = 100) slug = models.SlugField(max_length=100, unique=True, db_index=True, verbose_name="URL") category = TreeForeignKey(Catalog, on_delete=models.PROTECT) manufacturer = models.ForeignKey(manufacturer, on_delete = models.PROTECT) image = models.FileField(upload_to='photos/', blank=True) price = models.IntegerField() description = models.TextField() technikal_description = models.TextField() technikal_param = models.TextField() manufacturer_code = models.IntegerField() our_code = models.IntegerField() def __str__(self): return self.title def return_category(self): return self.category I assume that you need to make up a new page and link it to models.py -
How can I unit tests for this Django Form
I do coverage report and there are many place that not cover, do you have any idea how to I write test for th? this views.py was not cover def addreview(request, u_id, shop_id): url = request.META.get('HTTP_REFERER') shop = shop_detail.objects.get(id=shop_id) user = cs.objects.get(customer=u_id) if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): data = Review() data.review_text = form.cleaned_data['review_text'] data.review_rating = form.cleaned_data['review_rating'] data.shop = shop data.user = user data.save() return redirect(url) def rating(request): if not request.user.is_authenticated: return HttpResponseRedirect(reverse('customer_login')) if request.method == 'POST': form = RateUsForm(request.POST) if form.is_valid(): rate = RateUs() rate.rate_text = form.cleaned_data['rate_text'] rate.rating = form.cleaned_data['rating'] rate.user = request.user rate.save() return HttpResponseRedirect(reverse("index")) return render(request, 'shop/rate.html') models.py class Review(models.Model): user = models.ForeignKey(Profile,on_delete=models.CASCADE) shop = models.ForeignKey(shop_detail,on_delete=models.CASCADE) review_text = models.TextField(max_length=300) review_rating = models.IntegerField() def __str__(self): return f"{self.review_rating}" class RateUs(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) rate_text = models.TextField() rating = models.IntegerField() def __str__(self): return f"{self.rating}" forms.py class ReviewForm(forms.ModelForm): class Meta: model= Review fields= ["review_text", "review_rating"] class RateUsForm(forms.ModelForm): class Meta: model= RateUs fields= ["rate_text","rating"] This is what I write for rating def test_valid_rating(self): rateus1 = RateUs.objects.first() data={ "user": rateus1.user, "rate_text": rateus1.rate_text, "rating": rateus1.rating } response = self.client.post(reverse('rating'), data=data) self.assertEqual(response.status_code, 302) When I try to write test for addreview i got customer.models.Profile.DoesNotExist: Profile matching query does not exist. -
Allow users to create ingredients using a CreateView and ManyToMany field
I have a form where users can create ingredients using a jQuery Plugin for Custom Tags. Submitting the form results in the error Field 'id' expected a number but got 'b'. where each letter in the ingredient (vs the word) is being picked up as an item that's expected to already exist in the database. # form.py class EatForm(forms.ModelForm): notes = forms.CharField(widget=forms.Textarea(attrs={"rows":3}),required=False) ingredient = forms.CharField(widget=forms.TextInput(),required=False) allergen = forms.CharField(widget=forms.TextInput(),required=False) class Meta: model = Eat fields = ["name", "notes", "meal","ingredient","allergen","favorite","datetime"] # Models class Eat(models.Model): MEAL_CHOICES = ( ("breakfast", "Breakfast"), ("lunch", "Lunch"), ("dinner", "Dinner"), ("supper", "Supper"), ("snack", "Snack"), ("drink", "Drink"), ) id = models.BigAutoField(primary_key=True, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=255) notes = models.CharField(max_length=255, blank=True, null=True) meal = models.CharField(choices=MEAL_CHOICES, max_length=20) ingredient = models.ManyToManyField(Ingredient,blank=True) allergen = models.ManyToManyField(Allergen,blank=True) favorite = models.BooleanField(default=False) datetime = models.DateTimeField() # View class EatFormAddView(LoginRequiredMixin, CreateView): model = Eat template_name = "dashboard.html" success_url = reverse_lazy("core:activity") form_class = EatForm # get user # def get_object(self): # return self.request.user # determine which submit button was pressed def form_valid(self, form): form.instance.user = self.request.user ingredients = form.cleaned_data['ingredient'].split(',') for ingredient in ingredients: try: ingredient_obj = Ingredient.objects.get(name=ingredient) except: ingredient_obj = Ingredient(name=ingredient) ingredient_obj.save() return super().form_valid(form) -
Django social-auth-app-django cannot login & show Authentication process canceled
There is a problem when I upload my django application to the hosting. That is, when I logged in using Google OAuth after selecting a Google account, an error suddenly appeared AuthCanceled at /auth/complete/google-oauth2/. But, I didn't do anything during the login process. So, why was the authentication process canceled? When run on localhost, the application runs smoothly. But, when run on hosting it will be like that. I don't know what happened. settings.py DEBUG = True ALLOWED_HOSTS = ['*', 'siadis.mydomain.sch.id'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website.apps.WebsiteConfig', 'quiz.apps.QuizConfig', 'django.contrib.humanize', 'social_django' ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / "templates/" ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.template.context_processors.media', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'my id client' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = 'my secret cliend' LOGIN_REDIRECT_URL = '/' LOGIN_ERROR_URL = '/login/failed/' LOGIN_URL = '/login/' SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = { 'access_type': 'offline', 'approval_prompt': 'auto', 'redirect_uri': 'https://siadis.mydomain.sch.id/auth/complete/google-oauth2/' } error Request Method: GET Request URL: http://127.0.0.1:51457/auth/complete/google-oauth2/?state=4XEytKWxSU62AuZjlOr888SjzXe1XjEg&code=4%2F0AfgeXvvepRVcezejl-IwUwh6QVw9-AJnZzaz42my-QDlsEFWko2IFWwRml2UH9TRq_RZXw&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&authuser=2&prompt=none Django Version: 3.2.14 Python Version: 3.8.9 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website.apps.WebsiteConfig', 'quiz.apps.QuizConfig', 'django.contrib.humanize', 'social_django'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', … -
Django app.get_models giving partial model list
I have django app which contains model segregated such that models/new and models/old, where both have models.py in it. So when I try django.app.get_models it's returning models of models/old folder. What can be done to get all models from both folder? Django app.get_models giving partial model list. It should give all the models containing in each folder.