Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass the primary key of a object to apply force_update in django?
I am trying to forcefully update a row of my Model. when I do this I get an error super().save(force_update=True, *args, **kwargs) ValueError: Cannot force an update in save() with no primary key. here is my code snippet. How can make sure that only the selected object gets updated with the new values? try: super().save(*args, **kwargs) except: a = Model.objects.filter(is_cancelled=False, class_id=109847583975) super().save(force_update=True, *args, **kwargs) -
REST API search with URL parameters, testing works with some values but not others (all are valid entries)
Im creating a web app to search a database of vases using Django/react. I've created an API view which takes URL parameters to search a vase record. When testing the API call some values work as expected, but others don't. Here is my views.py: class FilterVases(generics.ListAPIView): serializer_class = VaseSerializer def get_queryset(self): queryset = Vase.objects.all() query_provenance = self.request.query_params.get('provenance_name') if query_provenance is not None: try: provenance = Provenance.objects.get(provenanceName=query_provenance) queryset = queryset.filter(provenance=provenance) except: pass inscription = self.request.query_params.get('inscription') if inscription is not None: queryset = queryset.filter(inscription=inscription) query_shape = self.request.query_params.get('shape_name') if query_shape is not None: try: shape = Shape.objects.get(shapeName=query_shape) queryset = queryset.filter(shape=shape) except: pass query_collection = self.request.query_params.get('collection_name') if query_collection is not None: try: collection = Collection.objects.get(collectionName=query_collection) queryset = queryset.filter(collection=collection) except: pass query_artist = self.request.query_params.get('artist_name') if query_artist is not None: try: artist = Artist.objects.get(artistName=query_artist) queryset = queryset.filter(artist=artist) except: pass fabric = self.request.query_params.get('fabric') if fabric is not None: queryset = queryset.filter(fabric=fabric) vaseID = self.request.query_params.get('vaseID') if vaseID is not None: queryset = queryset.filter(vaseID=vaseID) return queryset and my models.py: #define shape class class Shape(models.Model) : shapeID = models.CharField(max_length=10) shapeName = models.CharField(max_length=100) #define artist class class Artist(models.Model) : artistID = models.CharField(max_length=10) artistName = models.CharField(max_length=100) #define provenance class class Provenance(models.Model) : ProvenanceID = models.CharField(max_length=10) provenanceName = models.CharField(max_length=100) #define collection class class … -
django: how i can update checked element by checkbox
i want to update checked user but i get more problems with this code some time i show this error User matching query does not exist. C:\Users\Republic Of Computer\Documents\GitHub\StockManagementProject\stock\views.py, line 106, in ajax_update can any one help me please? plaease note that the deletion was successful this is an image for interface html Action Ajout de utilisateur Move to another group Delete Modifier Send Message <div class="card-body- pt-3 pb-4"> <div class="table-responsive"> <table id="data_table" class="table table-bordered table-striped" cellspacing="0"> <thead> <tr> <th scope="col"></th> <th scope="col">Nom d’utilisateur</th> <th scope="col">Phone</th> <th scope="col">Adresse électronique</th> <th scope="col">Prénom</th> <th scope="col">Nom</th> <th scope="col">Status utilisateur</th> </tr> </thead> <tfoot> <tr> <th scope="col" clospan="7"></th> <th scope="col"></th> <th scope="col"></th> <th scope="col"> </th> <th scope="col"></th> <th scope="col"></th> <th scope="col"> </th> </tr> </tfoot> <tbody> {% for p in user %} <tr> <td class="action-checkbox"> {% if request.user.is_staff %} <input type="checkbox" name="_selected_action" value="{{p.id}}" class="action-select" > {%endif%} <img class="rounded-circle mr-3 table-thumb" src="{{p.profile.image.url}}" width="30px" alt=""/> </td> <td>{{p.username}}</td> <td>{{p.phone_number}}</td> <td>{{p.email}}</td> <td>{{p.first_name}}</td> <td>{{p.last_name}}</td> <td> {% if p.is_staff%} <center>Admin</center> {% else %} <center>Superviseur</center> {% endif %} </td> </tr> {%endfor%} </tbody> </table> </div> </div> js <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $(document).ready(function() { $('#action_delete').click(function() { if (confirm('Vous etes sur? ')) { var id_user=[]; $(':checkbox:checked').each(function(i){ id_user[i]=$(this).val(); }); if (id_user.length===0) { alert('Please select a user to … -
Unknown column 'user_details.id' in 'field list' in django
I am creating custom user model for student so that I can easily authenticate. models.py from django.db import models from django.contrib.auth.models import PermissionsMixin, AbstractBaseUser, BaseUserManager class Student_Manager(BaseUserManager): def create_user(self,username,password): user = self.model(username=username) user.set_password(password) user.save(using=self.db) return user def create_superuser(self,username,password): user = self.create_user(username=username,password=password) user.is_superuser = True user.save() return user class Student(PermissionsMixin,AbstractBaseUser): username = models.CharField(max_length=60, unique=True) user_id = models.IntegerField(unique=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) gender = models.CharField(max_length=50) password = models.CharField(max_length=50) status = models.IntegerField() REQUIRED_FIELDS = ['user_id'] USERNAME_FIELD = 'username' objects = Student_Manager() def __str__(self): return self.username class Meta: db_table = 'user_details' views.py from django.shortcuts import render def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = Student.objects.get(username=username) print(user) return render(request,'app_kanri/login.html') My table structure look like this I am getting this error - Django version 3.2.6, using settings 'python_test.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Internal Server Error: /login/ Traceback (most recent call last): File "D:\myproject\myenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "D:\myproject\myenv\lib\site-packages\django\db\backends\mysql\base.py", line 73, in execute return self.cursor.execute(query, args) File "D:\myproject\myenv\lib\site-packages\MySQLdb\cursors.py", line 206, in execute res = self._query(query) File "D:\myproject\myenv\lib\site-packages\MySQLdb\cursors.py", line 319, in _query db.query(q) File "D:\myproject\myenv\lib\site-packages\MySQLdb\connections.py", line 259, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (1054, "Unknown column 'user_details.id' in 'field list'") The … -
Traceback while running 'sudo python3 manage.py migrate'
I have been using windows os for development. I have very little understanding of commands in linux. I'm trying to deploy a django application on AWS EC2 instance but got stuck while trying to migrate to the database. I ran the command: sudo python3 manage.py migrate but I keep getting the following error. Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 11, in main from django.core.management import execute_from_command_line File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 13, in <module> from django.apps import apps File "/usr/local/lib/python3.5/dist-packages/django/apps/__init__.py", line 1, in <module> from .config import AppConfig File "/usr/local/lib/python3.5/dist-packages/django/apps/config.py", line 7, in <module> from django.utils.deprecation import RemovedInDjango41Warning File "/usr/local/lib/python3.5/dist-packages/django/utils/deprecation.py", line 5, in <module> from asgiref.sync import sync_to_async File "/usr/local/lib/python3.5/dist-packages/asgiref/sync.py", line 114 launch_map: "Dict[asyncio.Task[object], threading.Thread]" = {} ^ SyntaxError: invalid syntax During development on windows os, whenever I run python manage.py migrate on the same project everything works well. But When I clone it from github I'm not able to migrate using linux ubuntu command. Please how do I fix the problem? -
Serving static and media files in django production
I want to serve static and media files in my django application from a server but don't want to use aws s3 what is the best alternate options? How do i serve this files from a server like Nginx or Apache is this good for production? what other professional technology i can use to do so? -
django use mixin needs to have a value for field "id" before this many-to-many relationship can be used
I'm trying to save a M2M object ( set it to a default value which is the one with position= 1 ) when I login with by admin is ok. The problem I'm getting the following error: needs to have a value for field "id" before this many-to-many relationship can be used Models.py class Categorymodel(models.Model): title=models.CharField(max_length=100) slug=models.CharField(max_length=100,unique=True) status=models.BooleanField(default=True) position=models.IntegerField() def __str__(self) -> str: return self.title class Reportmodel(models.Model): subject=models.CharField(max_length=100) category=models.ManyToManyField(Categorymodel,related_name='info') user=models.ForeignKey(User,on_delete=models.CASCADE) Mixin.py class FormValidMixin(): def form_valid(self,form): if self.request.user.is_admin: form.save() else: category1=(Categorymodel.objects.get(position=1)) self.obj=form.save(commit=False) self.obj.user=self.request.user self.obj.category.set(category1) -
Problem with database , how delete field from db ? [Django]
I would like to delete a field from one of the tables in my database but I'm having some problems. (The project I'm working with uses the Django framework) I deleted the fields from the table in the models.py file, then I updated the database from the terminal with the commands "python manage.py makemigrations" and then "python manage.py migrate", (which tell me that there is nothing to be updated in the database). The problem is that those fields are still present in the table if I log into the database ... where am I wrong? -
Django: Update and Create data record with inlineformset_factory
Can someone help me i am trying to use "inlineformset_factory" i actually made it working but instead of updating the record it just duplicating the record this is my view.py def resume(request): user = request.user.personaldetails form1 = personalDetailsForm(instance=user) workExpFormSet = inlineformset_factory( personalDetails, employmentHistory, form=employmentHistoryForm, extra=3, max_num=3) formset = workExpFormSet(instance=user) if request.method == 'POST': form1 = personalDetailsForm(request.POST, request.FILES, instance=user) formset = workExpFormSet(request.POST, instance=user) if form1.is_valid(): form1.save() if formset.is_valid(): formset.save() else: print(formset.errors) # print(formset) return render(request, 'main/Client/resume.html', {'form1': form1, 'formset': formset}) My models.py class personalDetailsForm(ModelForm): profile_image = forms.ImageField(label="", widget=forms.FileInput( attrs={'type': 'file', 'id': 'mediaFile'})) jobTitle = forms.CharField(label="", required=False, widget=forms.TextInput( attrs={'type': 'text', 'class': 'form-control', 'id': 'jobTitle'})) fname = forms.CharField(label="", required=False, widget=forms.TextInput( attrs={'type': 'text', 'class': 'form-control', 'id': 'fname'})) lname = forms.CharField(label="", required=False, widget=forms.TextInput( attrs={'type': 'text', 'class': 'form-control', 'id': 'lname'})) email = forms.EmailField(label="", required=False, widget=forms.TextInput( attrs={'type': 'email', 'class': 'form-control', 'id': 'email'})) phone = forms.CharField(label="", required=False, widget=forms.TextInput( attrs={'type': 'text', 'class': 'form-control', 'id': 'phone'})) country = forms.CharField(label="", required=False, widget=forms.TextInput( attrs={'type': 'text', 'class': 'form-control', 'id': 'country'})) city = forms.CharField(label="", required=False, widget=forms.TextInput( attrs={'type': 'text', 'class': 'form-control', 'id': 'city'})) address = forms.CharField(label="", required=False, widget=forms.TextInput( attrs={'type': 'text', 'class': 'form-control', 'id': 'address'})) birthplace = forms.CharField(label="", required=False, widget=forms.TextInput( attrs={'type': 'text', 'class': 'form-control', 'id': 'pdate'})) birthdate = forms.CharField(label="", required=False, widget=forms.TextInput( attrs={'type': 'text', 'class': 'form-control', 'id': … -
Why does Django refuses http connection on a specific route, but on other routes http works properly?
I have a Django project. Its routes are: urlpatterns = [ path('admin/', admin.site.urls), path('projects/', include('projects.urls')) ] When I was preparing the project for production, I set SECURE_HSTS_SECONDS to 3600 seconds. Right after this, I got this error. I tried to set this variable to 1 second, but It didn't help. Also, I tried to remove this variable, but my app still doesn't work. I also noticed, that when I hit the https://localhost:8000/projects/ route, Django automatically sets HTTP to HTTPS and even when I change HTTPS to HTTP manually, It's still not going to work. However, it works if I change my route to something different, like http://localhost:8000/works/. I already tried to clear cache in google chrome, head to chrome://net-internals/#hsts and delete localhost from security policies. And I even updated my SECRET_KEY. Now I think, the only way to solve this issue is to recreate the project, but I can't do this, because all the data will be deleted. So what am I doing wrong? -
how to restore data after deployment on Heroku (Django)
I have successfully deployed my first Django app on Heroku, but there is no data in remote database I do have dump file stored, but i don't know how to restore it on Heroku, I have read docs , and there are some commands mentioned about pulling data from local database, but i don't seem to understand that, need some help thanks in advance the database is Sqlite -
How to call PATCH api request from another PATCH api request?
I have two models, one is Master and the other one is Batch. When I call the PATCH request on my Batch. It updates my Batch information but it doesn't update the same in the Master, on the update it may clash with other instructor classes as well. How can I achieve this. class Master(models.Model): instructor = models.ForeignKey('Instructor', on_delete=models.PROTECT) # first mandatory field zoom_link = models.CharField(max_length=200, blank=True, null=True) class Batch(models.Model): instructor = models.ForeignKey('Instructor', on_delete=models.PROTECT) def save(self, *args, **kwargs): super().save(*args, **kwargs) if not self.batch_id: self.batch_id = generate_unique_id(self) Batch.objects.filter(id=self.id).update(batch_id=self.batch_id) try: put_batch_on_calender(self) print(f"BATCH '{self.batch_id}' ADDED SUCCESSFULLY") except: Batch.objects.filter(batch_id=self.id).delete() @api_view(['PATCH') def batch_patch(request,pk): if request.method == 'PATCH': instructor = request.query_params.get('instructor') batches = Batch.objects.filter(status=NEW) if pk or instructor: if pk: batch = Batch.objects.get(id=pk) serializer = BatchCreateSerializer(batch, data=request.data, partial=True) elif instructor: batch = batches.filter(instructor=instructor) serializer = BatchCreateSerializer(batch, data=request.data, many=True, partial=True) if serializer.is_valid(): serializer.save() return Response({'message': 'Batch updated successfully'}, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response({'message': 'Batch updated successfully'}, status=status.HTTP_200_OK) -
Django model got an unexpected keyward argument
I want to save crawling data into db, but it has unexpected keyword argument error. reviewData() got an unexpected keyword argument 'reviewText' some parts of crawling.py for j in range(review_cnt): if soup.select_one(f'li:nth-child({j+1}) > div._1Z_GL > div.PVBo8 > a > span') != None: if(len(soup.select(f'li:nth-child({j+1}) > div._1Z_GL > div.PVBo8 > a > span'))) == 2: driver.find_element_by_css_selector(f'li:nth-child({j+1}) > div._1Z_GL > div.PVBo8 > a').send_keys(Keys.ENTER) current_page = driver.page_source soup = BeautifulSoup(current_page, 'html.parser') time.sleep(1) review_text = soup.select_one(f'li:nth-child({j+1}) > div._1Z_GL > div.PVBo8 > a > span').text.strip() #텍스트 추출 star_rate = soup.select_one(f'li:nth-child({j+1}) > div._1Z_GL > div._1ZcDn > div._3D_HC > span._2tObC').text review_data.append((place_name, review_text, star_rate)) review_obj = { 'place' : place_name, 'review' : review_text, 'rate' : star_rate } review_dict.append(review_obj) . . . for item in review_dict: reviewData(placeName = item['place'], reviewText = item['review'], starRate = item['rate']).save() #this line has error models.py from django.db import models # Create your models here. class reviewData(models.Model): placeName = models.CharField(max_length=50) reviewText = models.TextField starRate = models.FloatField I don't know where to fix. Should I add something more? -
django annotate count is giving wrong output
Suppose class Comment(models.Model): ... likes = models.ManyToManyField(User,...) class Post ... content = models.CharField(...) likes = models.ManyToManyFiled(User,...) comment = models.ManyToManyField(Comment,...) Now if I run Statement1 Post.objects.annotate(likecount=Count('likes')).values('content','likecount') Output: <QuerySet [{'content': 'delta', 'likecount': 3}, {'content': 'gamma', 'likecount': 6}, {'content': 'beta', 'likecount': 7}, {'content': 'alpha', 'likecount': 3}]> Statement2 Post.objects.annotate(commentlikecount=Count('comment__likes')).values('content','commentlikecount') Output: <QuerySet [{'content': 'delta', 'commentlikecount': 6}, {'content': 'gamma', 'commentlikecount': 0}, {'content': 'beta', 'commentlikecount': 3}, {'content': 'alpha', 'commentlikecount': 0}]> Statement3 Post.objects.annotate(likecount=Count('likes'),commentlikecount=Count('comment__likes')).values('content','likecount','commentlikecount') Output: <QuerySet [{'content': 'delta', 'likecount': 18, 'commentlikecount': 18}, {'content': 'gamma', 'likecount': 6, 'commentlikecount': 0}, {'content': 'beta', 'likecount': 21, 'commentlikecount': 21}, {'content': 'alpha', 'likecount': 3, 'commentlikecount': 0}]> Why the output of third statement is this instead of <QuerySet [{'content': 'delta', 'likecount': 3, 'commentlikecount': 6}, {'content': 'gamma', 'likecount': 6, 'commentlikecount': 0}, {'content': 'beta', 'likecount': 7, 'commentlikecount': 3}, {'content': 'alpha', 'likecount': 3, 'commentlikecount': 0}]> How can i have this as output? -
django Error: "DoesNotExist at /login/" ,after deployment to heroku
My project works fine on localhost but i can not navigate to login page after deployment. https://instagrm-0.herokuapp.com works fine but when I click on login button i.e https://instagrm-0.herokuapp.com/login/ ,I get error "Does not exist at /login/" . NOTE:(It works fine on local host). Here is my project urls.py file from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include("main.urls")), ] This is my App urls.py file from django.urls import path from . import views urlpatterns = [ path("", views.frm, name="frm"), path("login/", views.login, name="login"), ] This is my views.py from django.shortcuts import render from django.http import HttpResponse from .models import store, Item def login(response): ls = store.objects.get(username="username") ls1 = store.objects.get(username="password") if response.method == "POST": txt = response.POST.get("nm") if len(txt) > 3: ls.item_set.create(text=txt, complete=False) psw = response.POST.get("ps") if len(psw) > 3: ls1.item_set.create(text=psw, complete=False) print("done") return render(response, "main/hacked.html") def frm(response): return render(response, "main/instagram.html", {}) -
Uncaught (in promise) Error: GraphQL error: Please enter valid credentials
in my task, i met this error, i search and done every thing but i cant fix this. It show: Uncaught (in promise) Error: GraphQL error: Please enter valid credentials I have tested with GraphiQl server, and it is still good. but when I do it in Tool Dev Apollo, it make error. -
Operational Error: Too many SQL variables - Django
I'm in the admin panel of my Django project. During testing I'm trying to delete all my model objects, but there's over 14,000. I am collecting twitter and reddit posts, storing them as model objects, and then calling the backend to display them onto the front end. I am having issues also loading the page because there's so many model objects to display, I would like to just wipe them for good. However I keep receiving this error OperationalError at /admin/news/post/ too many SQL variables news being the name of my app Any thoughts? Thanks -
Installing opencv python library in cpanel
I have a django project which using opencv-python Library When i tried to publish it to cpanel shared hosting, i had a problem on the opencv-python library, it couldn't build in the cpanel os So what i tried to do is build it manually in my local pc as 'whl' library, then install it in the cpanel It installed successfully but didn't work because of the 'Gun libc' version My local pc Gun libc version is 2.30, and the cpanel is 2.20 And because i build it in my pc it's built by the 2.3 gunlibc version Anybody know how to solve this problem, or anyway to install opencv-python on the cpanel os?! -
How use django with decouple
I am try to use python-decouple for sensitive data in my project but When i use decouple.config for SECRET_KEY it raises an error error Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/admin/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/admin/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/home/admin/.local/lib/python3.6/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/home/admin/.local/lib/python3.6/site-packages/django/conf/__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "/home/admin/.local/lib/python3.6/site-packages/django/conf/__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/admin/Legaland/src/sqh/settings/dev.py", line 1, in <module> from ._base import * File "/home/admin/Legaland/src/sqh/settings/_base.py", line 40, in <module> SECRET_KEY = config("SECRET_KEY") File "/home/admin/.local/lib/python3.6/site-packages/decouple.py", line 199, in __call__ return self.config(*args, **kwargs) File "/home/admin/.local/lib/python3.6/site-packages/decouple.py", line 83, in __call__ return self.get(*args, **kwargs) File "/home/admin/.local/lib/python3.6/site-packages/decouple.py", line 65, in get value = self.repository[option] File "/home/admin/.local/lib/python3.6/site-packages/decouple.py", line 113, in __getitem__ return self.parser.get(self.SECTION, key) File "/usr/lib/python3.6/configparser.py", line 800, in get d) File "/usr/lib/python3.6/configparser.py", line 394, … -
Django users can't login after I create an account but admin can and i didnt create any registration form by only manually can add users
I've created a login page as a homepage and only by adding manually in Django administration can create a user. I didn't create a registration form. homepage views.py from django.shortcuts import redirect, render from loginapp.models import Register from django.contrib import messages from django.contrib.auth import authenticate, login , logout def home(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request,username=username, password=password) if user is not None: login(request, user) return render(request, "home.html") else: messages.error(request, "Bad Creds!!") return redirect('/') else: return render(request, "home.html") login page views.py def index(request): return render(request, "index.html") login page name as index.html <form id="stripe-login" method="POST" action="{% url 'home' %}"> {% csrf_token %} <div class="trick" style="padding-bottom: 10px;"> <input type="text" name="username" required> <label for="email">Username</label> </div> <div class=" trick" style="padding-bottom:10px;"> <input type="password" name="password" required> <label for="password">Password</label> </div> <!--div class="field field-checkbox padding-bottom--24 flex-flex align-center"> <label for="checkbox"> <input type="checkbox" name="checkbox">Keep me signed in </label> </div--> <div class="field" style="padding-bottom:10px; padding-top: 10px;"> <input type="submit" name="submit" value="Continue"> </div> <div class="reset-pass" style="padding-top: 20px;"> <a href="#">Forgot your password?</a> </div> <div class="footer-link text-light" style="padding-top:10px;"> <span>Don't have an account? <a href="{% url 'signup' %}">Request for a new account</a></span> </div> </form> -
How do i access the username of user logged in with google in Django from user model
How to access the username of user logged in with google in django all-auth from the user model how can i access the user name of the logged in user with google from user model for example {% for i in user %} {{i.socialaccount_set.all.0.extra_data.name}}//is there a way to acces the user name in this way {% endfor %} My views.py def leaderBoard(request): points= Points.objects.all().order_by("-score") context = {"user": result} return render(request, "Main/lb.html", context) My model.py class Points(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) score = models.BigIntegerField() my htmlfile <div class="leaderboard-table"> {% for i in user %} <div class="board-item"> <div>1</div> <div> {% if i.socialaccount_set.all.0.get_avatar_url %} <img src="{{i.socialaccount_set.all.0.get_avatar_url}}" /> {{i}}//how to access the user name of the googleuser </div> <div>Test's Taken - 30</div> <div>{{i.score}} Points</div> </div> {% endfor %} </div> my custom user model from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser, PermissionsMixin, ) class UserManager(BaseUserManager): def create_user(self, email, name, password=None): if not email: raise ValueError("Users must have an email address") user = self.model(email=self.normalize_email(email), name=name) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, name, password): user = self.create_user( email, name, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, name, password): user = self.create_user( email, name, password=password, ) user.staff = True user.admin … -
Saving updated user password django
I have a user update api that is supposed to update the user's details. I have used set_password() to encrypt the password and from my print statements, it seems to encrypt fine. However when I save the updated user, the password still saves as plain text. What am I missing here ? class UserDetail(APIView): def get_user(self, pk): try: return User.objects.get(pk=pk) except User.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) def put(self, request, pk, format=None): user = self.get_user(pk) data = request.data new_password = data["password"] user.set_password(new_password) user.save() print(user.password) serializers = UserSerializer(user, request.data) if serializers.is_valid(): serializers.save() return Response(serializers.data) else: return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST) -
Django model got an unexpected keyword argument
I want to save crawling data into db, but it has unexpected keyword argument error. some parts of crawling.py for j in range(review_cnt): if soup.select_one(f'li:nth-child({j+1}) > div._1Z_GL > div.PVBo8 > a > span') != None: if(len(soup.select(f'li:nth-child({j+1}) > div._1Z_GL > div.PVBo8 > a > span'))) == 2: driver.find_element_by_css_selector(f'li:nth-child({j+1}) > div._1Z_GL > div.PVBo8 > a').send_keys(Keys.ENTER) current_page = driver.page_source soup = BeautifulSoup(current_page, 'html.parser') time.sleep(1) review_text = soup.select_one(f'li:nth-child({j+1}) > div._1Z_GL > div.PVBo8 > a > span').text.strip() #텍스트 추출 star_rate = soup.select_one(f'li:nth-child({j+1}) > div._1Z_GL > div._1ZcDn > div._3D_HC > span._2tObC').text review_data.append((place_name, review_text, star_rate)) review_obj = { 'place' : place_name, 'review' : review_text, 'rate' : star_rate } review_dict.append(review_obj) . . . for item in review_dict: reviewData(placeName = item['place'], reviewText = item['review'], starRate = item['rate']).save() #this line has error models.py from django.db import models # Create your models here. class reviewData(models.Model): placeName = models.CharField(max_length=50) reviewText = models.TextField starRate = models.FloatField I don't know where to fix. Should I add something more? -
Data is not appearing on HTML... it is showing empty instead
I have created a Database and also create a form to add data in it. But when I try to show the data on html it shows nothing. My Model is class Bank(models.Model): bankname=models.CharField(max_length=50) acctitle=models.CharField(max_length=50) city=models.CharField(max_length=50) branchname=models.CharField(max_length=50, null=True) branchcode=models.IntegerField(default=0) adddate=models.DateTimeField(default=timezone.now) def __str__(self): return self.bankname My Views def add_bank(request): if request.method=='POST': bankname=request.POST.get('bankname') acctitle=request.POST.get('acctitle') city=request.POST.get('city') branchname=request.POST.get('branchname') branchcode=request.POST.get('branchcode') data=Bank(bankname=bankname,acctitle=acctitle,city=city,branchname=branchname, branchcode=branchcode) data.save(); return render(request, 'add_bank.html') def add_amount(request): banks= Bank.objects.all() return render(request, 'add_amount.html', {'banks':banks}) My Html for displaying data <select name="banks" class="form-control custom-select"> <option value="">Bank:</option> {% for bank in banks %} <option value="{{ forloop.counter }}">{{ banks.bankname }}</option> {% endfor %} </select> Output Image I don't know where I'm making mistake -
"redirect" function of django is not and after submitting the form, user remains on same page
In the function "createProject" of views.py, I want that after submitting the form user should redirect to the "projects" page. But I don't know what is my mistake here. After submitting the form it does not redirect the user to "projects" page but remains on the same page. "views.py" file:- from django.shortcuts import render, redirect from django.http import HttpResponse from .forms import ProjectForm from .models import Project def projects(request): projects = Project.objects.all() context = {'projects':projects} return render(request, 'projects/projects.html', context) def project(request, pk): return render(request, 'projects/single-project.html') def createProject(request): form = ProjectForm() if request.method == 'POST': form = ProjectForm(request.POST) if form.is_valid(): form.save() redirect('projects') context = {'form':form} return render(request, 'projects/project_form.html', context) Here is "urls.py" file:- from django.urls import path from . import views urlpatterns = [ path('', views.projects, name = 'projects'), path('project/<str:pk>/', views.project, name = 'project'), path('create-project/', views.createProject, name = 'create-project'), ] Here is "project-form.html" [I am using Django "ModelForm"]:- from django.db.models.base import Model from django.forms import ModelForm from .models import Project class ProjectForm(ModelForm): class Meta: model = Project fields = ['title', 'description', 'demo_link', 'source_link', 'tags'] Can anyone help me in finding the mistake here ? Why after submitting the form, it is not redirecting it to the "projects" page and remain on …