Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Search bar error: 'WSGIRequest' object has no attribute 'Post' / Django
I am trying to implement search in Django. When I enter something into the search, I get an error: 'WSGIRequest' object has no attribute 'Post'. app view def searchbar(request): if request.method == "POST": searched = request.Post["searched"] students = Q(pk__contains=searched) | Q(first_name__contains=searched) | Q(last_name__contains=searched) return render(request, template_name='searchbar.html', context={"searched": searched, "students": students}) else: return render(request, template_name='searchbar.html', context={}) template {% extends "index.html" %} {% block content %} <center> {% if searched %} <h1>You search for {{ searched }}</h1> <br/> {% for student in students %} {{ student.first_name }} {{ student.last_name }}<br/> {% endfor %} {% else %} <h1>Nothing to search</h1> {% endif %} </center> {% endblock %} Tell me what could be the problem? Thanks in advance. -
Django: Table doesn't exist( python manage.py migrate)
I dropped some table related to an app. and again tried the syncdb command python manage.py migrate It shows error like django.db.utils.ProgrammingError: (1146, "Table 'homeapp_enroll_course' doesn't exist") models.py class Enroll_course(models.Model): SHFE_CHOICES = ( ('M', 'Moring'), ('E', 'Evening'), ) BATCH_CHOICES = ( ("A", "1ST"), ("B", "2ND") ) userinfo = models.ForeignKey(User, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) batch = models.CharField(max_length=1, choices=BATCH_CHOICES, default="A") shife = models.CharField(max_length=1, choices=SHFE_CHOICES, default="M") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) -
Stuck at the start lerning Django
Sorry for mistakes, this text transleted by Google Translate Hi all! My story is short: I'm 21, I studied computer science, Python and algorithmization, basic sql, a little Git for 3 months. I am a 3rd grade university student. I started learning django and got stuck. The library turned out to be a stone wall that I pick with a wooden stick. knowledge does not fit in the head. I went through 5 of the 7 steps of the documentation tutorial. They say, start writing small programs, or catch up with tons of theory, or buy a course) But what to write when, at the start of writing, there is a fog in my head. I have of course ideas for pet-projects but they are hard to realize for me) I have been standing still for 2 months and it seems that I have already lost the knowledge gained in the tutorial I thought of copy-pasting a project on tutorials from YouTube, but some people told me that you won’t remember anything, that is why this idea died at the start) advice me something! -
Django AUTH0 serializer
In my app I use auth0 to do authentication. Everything works great, I can see new users being created in admin panel etc, but there is one issue. when I go to my endpoint that displays data I have an empty list. Like this { "id": "d458196e-49f1-42db-8bc2-ee1dba438953", "owner": 1, "name": "dsdsds", "viewable": [] } the list viewable is a list of users that can view the data object. So if you want to share your data with your friend you just add his email Like I said previous. This list is viewable form django admin level and drf form level but not in JSON. How to display this data? Models from django.contrib.auth.models import AbstractUser from django.conf import settings class User(AbstractUser): pass class WalletInstance(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=30, null=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='owner', on_delete=models.CASCADE) viewable = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='can_view', blank=True) Settings.py AUTH_USER_MODEL = 'budget_app.User' SOCIAL_AUTH_TRAILING_SLASH = False SOCIAL_AUTH_AUTH0_DOMAIN = '####' SOCIAL_AUTH_AUTH0_KEY = '####' SOCIAL_AUTH_AUTH0_SECRET = '####' SOCIAL_AUTH_AUTH0_SCOPE = [ 'openid', 'profile', 'email' ] AUTHENTICATION_BACKENDS = { 'social_core.backends.auth0.Auth0OAuth2', 'django.contrib.auth.backends.ModelBackend' } LOGIN_URL = '/login/auth0' LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' Serializers class WalletInstanceSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.id') class Meta: model = WalletInstance fields = '__all__' depth = 1 -
django channels + nginx occurs 504 timeout
I deployed my django server with nginx. I use daphne as a web server in my docker image, so docker execute ENTRYPOINT ["daphne", "-b", "0.0.0.0", "-p", "8000", "my_app.asgi:application"] daphne is the only web server and nginx cover all about django. location / { proxy_pass http://my_backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } and when I'm trying to login in admin panel, 504 occurs. I implemented one django channels consumer (about chatting) but I can't understand why chat websocket is related with the problem being logined in django admin. and docker saids, my_app | 2022-08-14 03:30:14,084 WARNING Application instance <Task pending name='Task-5' coro=<ProtocolTypeRouter.__call__() running at /usr/local/lib/python3.10/site-packages/channels/routing.py:71> wait_for=<Future pending cb=[_chain_future.<locals>._call_check_cancel() at /usr/local/lib/python3.10/asyncio/futures.py:384, Task.task_wakeup()]>> for connection <WebRequest at 0x7ff0f0feb7c0 method=POST uri=/admin/login/?next=/admin/ clientproto=HTTP/1.1> took too long to shut down and was killed. Ironically, swagger documentation(drf-yasg) and django login page is normally connectable. Everything is ok in localhost when I execute in my pycharm. I don't know anymore. What should I do further? please help -
How to call next page in cursor pagination in django
from rest_framework.pagination import CursorPagination # In API View def get(self, request, *args, **kwargs): all_message = GroupMessages.objects.filter(group_id=ChannelGroup.objects.filter(group_name=group_name).first()) paginator = CursorPagination() result_page = paginator.paginate_queryset(all_message, request) serializer = GroupMessagesSerializer(result_page, many=True,context={'request': request}) response = Response(serializer.data, status=status.HTTP_200_OK I have implemented Cursor Pagination and i am getting response also. In PageNumberPagination We can manipulate our response via parameter in request url for eg ?page=1 or 2 but in cursor pagination if i want to test my pagination in postman how should i manipulate it when i hit my url {{BaseUrl}}channel/getmessages/GeneralChannel/ i am getting 2 records but how can i fetch next two records which parameter should i pass or is there something else in Cursor pagination in order to do this -
Redux Toolkit Query sends empty data to DRF API, ie. request.data is showing empty in django backend views
I want to send form data using Redux RTK Query to Django API. I have two models User and Profile related with One To One Relationship. Everything works fine in backend as I checked with Postman. I can update in Profile model or Create new entry in Profile model. But when I send my form data from React front end using Redux RTK Query for POST/PATCH, I got request.data as empty {} . RTK Query: editProfile: builder.mutation({ query: (access_token, actualData) => { console.log(actualData) return { url:'editprofile/', method:'PATCH', body:actualData, headers:{'authorization' : `Bearer ${access_token}`, 'Content-type':'application/json'} } } }), createProfile: builder.mutation({ query: (access_token, actualData ) => { return { url:'createprofile/', method:'POST', body:actualData, headers:{'authorization' : `Bearer ${access_token}`, 'Content-type':'application/json'} } } }) console.log(actualData) gives {locality: 'ffff', city: 'ffff', address: 'ffff', pin: 'fffff', user: 1} view.py : Through POSTMAN I have checked everything works fine. class UserProfileDataView(APIView): renderer_classes = [UserRenderer] permission_classes = [IsAuthenticated] def get(self, request, format=None): serializer = ProfileSerializer(request.user.profile, context={'request': request}) return Response(serializer.data, status=status.HTTP_200_OK) def post(self, request, format=None): serializer = ProfileSerializer(data= request.data, context={'request': request}) serializer.is_valid(raise_exception=True) serializer.save() return Response ({ 'msg':'Data Updated Successfully'},status=status.HTTP_201_CREATED ) def patch(self, request, format=None): item = Profile.objects.get(user = request.user) serializer = ProfileSerializer(item ,data = request.data, partial=True, context={'request': request}) print(request.data) serializer.is_valid(raise_exception=True) user = … -
axios post request not giving any data to django view
I am trying to make my first post request using axios to a Django view which accepts both POST and GET. I am getting an empty dict from the request.POST: <QueryDict: {}> [13/Aug/2022 16:44:00] "POST /users/114260670592402026255 HTTP/1.1" 200 9 The server does return a 200 status code but the data I sent from the UI is not present. I have the following django view: from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import json from .models import UserProfile @csrf_exempt def get_user_profile(request, user_id): if request.method == 'GET': try: user = UserProfile.objects.get(user_id=user_id) print("user found") except Exception as error: print("User profile wasnt found:") print(error) user = None profile = UserProfile() profile.user_id = user_id profile.searches = [ {'search_term': 'hd'}, {'search_term': 'wba'}, ] profile.save() print("user saved in db") user = UserProfile.objects.get(user_id=user_id) data = { 'user_id': user.user_id, 'searches': user.searches } json_data = json.dumps(data) return HttpResponse(json_data, content_type='application/json') if request.method == 'POST': data = request.POST print(data) return HttpResponse("it worked") in the UI app, SearchPage.js: useEffect(() => { console.log("user id changed") if (userId) { const user_profile_api_url = BASE_URL + '/users/' + userId axios.get(user_profile_api_url, {}) .then(response => { const recent_searches_response = response.data.searches; const new_recent_searches = []; recent_searches_response.map(dict => { new_recent_searches.push(dict.search_term) }) setRecentSearches(new_recent_searches); }) .catch((error) => { … -
problem: Table doesn't exist( python manage.py migrate)
I dropped some table related to an app. and again tried the syncdb command 'python manage.py migrate' It shows error like django.db.utils.ProgrammingError: (1146, "Table 'someapp.feed' doesn't exist") models.py ''' class Enroll_course(models.Model): SHFE_CHOICES = ( ('M', 'Moring'), ('E', 'Evening'), ) BATCH_CHOICES = ( ("A", "1ST"), ("B", "2ND") ) userinfo = models.ForeignKey(User, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) batch = models.CharField(max_length=1, choices=BATCH_CHOICES, default="A") shife = models.CharField(max_length=1, choices=SHFE_CHOICES, default="M") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) ''' -
How to send to print an ajax response in django
I'm trying to print (the action of sending to printer) a png image I get as a response from my ajax call. The reply from ajax is successful, meaning the image is properly sent. I can even open it in another window. However, I want to send that image automatically to print. I can do window.print() but that just prints the current page, not the response (obviously). Does anyone know how to process the response in order to print it? function traer_1234(){ $.ajax({ dataType: "html", contentType: "application/json", type: 'GET', data: {"nanda": 1}, url: "{% url 'View_test' %}", success: function (response) { alert("1234") window.print() }, error: function (response) { alert("Error") } }) } Thanks in advance to anyone who can supply any info. -
DRF display nested json
i have my DRF app. In my case, one wallet can have many entries such as income or expense. When I call my endpoint (viewset) I get data in this format [ { "id": "d458196e-49f1-42db-8bc2-ee1dba438953", "owner": 1, "viewable": [], "entry": [] } ] How can I get the content of "entry" variable?. class Category(models.Model): name = models.CharField(max_length=20, unique=True) def __str__(self): return self.name class BudgetEntry(models.Model): STATE= [ ('income','income'), ('expenses','expenses'), ] amount = models.IntegerField() entry_type = models.CharField(max_length=15, choices=STATE, null=True) entry_category = models.ForeignKey(Category, null=True, blank=True, on_delete=models.SET_NULL) class WalletInstance(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='owner', on_delete=models.CASCADE) viewable = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='can_view', blank=True) entry = models.ManyToManyField(BudgetEntry, related_name='BudgetEntry', blank=True) serializers class BudgetEntrySerializer(serializers.ModelSerializer): class Meta: model = BudgetEntry fields = '__all__' class WalletInstanceSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.id') class Meta: model = WalletInstance fields = '__all__' views class WalletViewset(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] serializer_class = WalletInstanceSerializer def get_queryset(self): user_id = self.request.user.id available = WalletInstance.objects.filter( Q(owner=user_id) ) return available -
Why celery task read past value
I want celery task read value in settings.py to getattr. When I call a specific API, the value changes to setattr. But, celery still get the initial value through getattr. I tested to output the changed value when calling API, It's print change data. def api(mode): setattr(settings, SYSTEM_MODE, mode) ... def tasks(): ... mode = getattr(settings, SYSTEM_MODE) ... -
How to download Instagram DP in browser using Instaloader in django?
views.py def submit_form(request): if request.method=="POST": url=request.POST.get('url1') test=instaloader.Instaloader() test.download_profile(profile_name=url,profile_pic_only=True) return HttpResponse main.html <div class="row text-center py-3 mt-3"> <div class="col-4 mx-auto"> <form action="{% url 'submit_form' %}" method='post'> {% csrf_token %} {{ form | crispy }} <input type="text" placeholder="Regular" class="form-control" name="url1" > <input type="submit" value="Download" class="btn bg-gradient-primary btn-sm me-2" > </form> </div> </div> url.py urlpatterns = [ # The home page path('', views.index, name='home'), path('main', views.main, name='main'), path('submit_form', views.submit_form, name='submit_form'), # Matches any html file re_path(r'^.*\.*', views.pages, name='pages'), ] OFFICIAL MODULE INSTALOADER LINK https://instaloader.github.io/index.html actually its download in project dir but i want to download file from browser when we click on download button. so how to download in my computer from browser. Please guys help me. -
Create a LDAP users and groups from the dajango interface admin
I am trying to modify a user in OpenLDAP server. As of now I can log but when I try to create users or groups in django. I can't see those users and groups in my LDAP server. Do you have any idea how a can sycnronize this data from django to LDAP For now i use the package django-auth-ldap for LDAP backend. This my conf in settings.py #OpenLdap-AUTH import ldap from django_auth_ldap.config import LDAPSearch, LDAPGroupQuery,GroupOfNamesType,PosixGroupType AUTH_LDAP_SERVER_URI = 'ldap://localhost' AUTH_LDAP_BIND_DN = 'cn=admin,dc=example,dc=com' AUTH_LDAP_BIND_PASSWORD = 'omar77' AUTH_LDAP_USER_SEARCH = LDAPSearch('ou=users,dc=example,dc=com',ldap.SCOPE_SUBTREE, '(uid=%(user)s)') AUTH_LDAP_GROUP_SEARCH = LDAPSearch('ou=groups,dc=example,dc=com',ldap.SCOPE_SUBTREE, '(objectClass=top)') AUTH_LDAP_GROUP_TYPE = PosixGroupType(name_attr="cn") AUTH_LDAP_MIRROR_GROUPS = True # Populate users from the LDAP directory to Django db. AUTH_LDAP_REQUIRE_GROUP = "cn=enabled,ou=groups,dc=example,dc=com" AUTH_LDAP_DENY_GROUP = "cn=disabled,ou=groups,dc=example,dc=com" AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail", "username": "uid", "password": "userPassword", } AUTH_LDAP_PROFILE_ATTR_MAP = { "home_directory": "homeDirectory" } AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active": "cn=active,ou=groups,dc=example,dc=com", "is_staff": "cn=staff,ou=groups,dc=example,dc=com", "is_superuser": "cn=superuser,ou=groups,dc=example,dc=com" } AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_TIMEOUT = 3600 AUTH_LDAP_FIND_GROUP_PERMS = True -
Django find common instances data in two models
I have models like: class Hospital(models.Model): name = models.CharField(max_length=200, unique=True) manager_name = models.CharField(max_length=200, default='') manager_id = models.CharField(max_length=200) def __str__(self): return f'{self.name}' class Sick(models.Model): name = models.CharField(max_length=200, default='') nationalID = models.CharField(max_length=200) illName = models.CharField(max_length=200) hospital = models.ForeignKey(Hospital, related_name='sicks', on_delete=models.DO_NOTHING) def __str__(self): return f'({self.name}, {self.nationalID})' class Employee(models.Model): name = models.CharField(max_length=200, default='') nationalID = models.CharField(max_length=200) company = models.ForeignKey(Company, related_name='employees', on_delete=models.CASCADE) def __str__(self): return f'({self.name}, {self.nationalID})' views: @api_view(['POST']) def get_sick_employee_by_hospital(request): pass and a serializer like : from rest_framework import serializers class NameSerializer(serializers.Serializer): name = serializers.CharField(required=True, max_length=200, allow_null=False) my problem is : my view get_sick_employee_by_hospital() receives a hospital name and it must return all sick peoples that are employees and They have visited that hospital, in a dictionary with keys 1,2,3,..., n and values like "(name, nationalID)". Pay attention that it does not matter which value is assigned to which key. what is the best way to do that ? how can i get all sick peoples that are employees and They have visited a hospital? thanks for your time. -
verbose name on class field in django
I am need of help to add a verbose name class Address(models.Model) : class Zip(models.Field): def db_type(self, connection): return 'char(8)' zip = Zip() address = models.CharField(max_length=200, verbose_name="Rua") ..... Need put the vebose name of ZIP to CEP -
How multiply and sum two columns in different tables in django
I have an application for calculating diets based on the nutrients of each meal. In admin of this application I want to price of each meal to the Meal table, which I have managed to do by calculating the price when displaying it in admin: # admin.py class AdminMeal(admin.ModelAdmin): list_display = ['name', 'meal_type_names', 'price'] @admin.display(description='Price') def price(self, obj): unit_prices = np.asarray(obj.mealingredient_set.order_by('id').values_list('ingredient__unit_price')) amounts = np.asarray(obj.mealingredient_set.order_by('id').values_list('amount')) to_return = float(np.matmul(np.transpose(unit_prices), amounts) / 1000) return mark_safe(to_return) Now my main question: I need to allow ordering of Meal table based on Price which I don't know how. based on my search it seems I should use annotate instead of my current way of calculating the price to be able to sort my table, I found a solution in here # admin.py class AdminMeal(admin.ModelAdmin): list_display = ['name', 'meal_type_names', 'price'] def get_queryset(self, request): queryset = super().get_queryset(request) queryset = queryset.annotate(_price=Sum('mealingredient__amount * mealingredient__ingredient__unit_price')) But sadly it throws this error (I think it's because i'm trying to SUM over different tables): Unsupported lookup 'amount * mealingredient' for AutoField or join on the field not permitted. Any help is appreciated, forgive me if I have missed something obvious, I'm a beginner in django. Some of the relevant Models for Meal table: … -
I want to host my webserver installed on aws ec2 instance [closed]
I have django webserver running on my aws ec2 instance. I installed self signed SSL on the apache2 webserver but whenever I try to access my webserver, i get a Install certificate warning. I know why this is happing but I want my server to be accessible to the public over https without showing this warning. How can I get a certificate for my webserver?? -
python manage.py collectstatic not working: TypeError: sequence item 0: expected str instance, NoneType found
I have been following this video on Youtube: https://www.youtube.com/watch?v=inQyZ7zFMHM1 My project so far is working fine with static files and all the files load and work properly. So, now I have to deploy the website on Heroku and for that, I uploaded the database on Amazon AWS using this video. After bucket creation, I did the configurations as mentioned in the video (copied the static files into the Bucket AWS) but it didn't work for me. It always showed me an error, that failed to load the resources On searching, I found the command python manage.py collectstatic to upload files into Bucket so I tried it out but this is the error I keep on getting TypeError: sequence item 0: expected str instance, NoneType found I have searched a lot on this but unable to figure out what is the issue. This is also the same error which I got when I myself uploaded static files into Bucket and tried to upload a Profile Image My settings.py file is as follows, """ Django settings for fcap project. Generated by 'django-admin startproject' using Django 4.1. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their … -
Adding commas to Django for loop values
I am trying to write a javascript to 3 digit comma separate number values that are passed in through my django database and can't figure it out. Exp: (1000 -> 1,000). Before writing the JS, I am also trying to figure out if I comma separate these values, will they mess up potential usage in other JS code that utilize these numbers to do math? Thanks. <table class="database-table"> <thead> <tr> <th>Market Value</th> </tr> </thead> <tbody> <tr> {% for s in securities %} <tr> <td id="security-value">${{s.market_value_of_security}}</td> </tr> {% endfor %} </tr> </tbody> </table> <script> const security_value = document.getElementById("security-value"); function numberWithCommas(x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); } -
How to add new field to a table in django that have "managed=False" because it was generated using inspectdb tool
I'm using an existing mysql database in a new django project, so I generated the models using inspectdb tool. But now I need to add a new field to a table, I'm doing it by adding the new field to the model and running migrations, but it doesn't work, It doesn't add the field to the table. Maybe it is because I have managed=False in the meta config of the model, but if I remove it, the migrations won't work, giving me the error "Table5 already exists" Here is the Model where I'm trying to add the "fields" field class Table5(models.Model): names = models.CharField(max_length=150) fields=models.JSONField(null=True) class Meta: managed = False db_table = 'table5' How can I achieve this? -
Django Celery Error on Runserver Using Redis
Currently using django and celery i have done my configuration and installed redis and redis is actually active i have check using the cli also when i run python manage.py shell and run a task it works perfectly but when i access the task by calling it from a view i get this error Internal Server Error: /contact/ Traceback (most recent call last): File "/home/codertjay/.virtualenvs/Gimsap-Ecommerce/lib/python3.9/site-packages/kombu/utils/functional.py", line 30, in __call__ return self.__value__ AttributeError: 'ChannelPromise' object has no attribute '__value__' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/codertjay/.virtualenvs/Gimsap-Ecommerce/lib/python3.9/site-packages/amqp/transport.py", line 188, in _connect entries = socket.getaddrinfo( File "/usr/local/lib/python3.9/socket.py", line 953, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno -9] Address family for hostname not supported During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/codertjay/.virtualenvs/Gimsap-Ecommerce/lib/python3.9/site-packages/kombu/connection.py", line 446, in _reraise_as_library_errors yield File "/home/codertjay/.virtualenvs/Gimsap-Ecommerce/lib/python3.9/site-packages/kombu/connection.py", line 433, in _ensure_connection return retry_over_time( File "/home/codertjay/.virtualenvs/Gimsap-Ecommerce/lib/python3.9/site-packages/kombu/utils/functional.py", line 312, in retry_over_time return fun(*args, **kwargs) File "/home/codertjay/.virtualenvs/Gimsap-Ecommerce/lib/python3.9/site-packages/kombu/connection.py", line 877, in _connection_factory self._connection = self._establish_connection() File "/home/codertjay/.virtualenvs/Gimsap-Ecommerce/lib/python3.9/site-packages/kombu/connection.py", line 812, in _establish_connection conn = self.transport.establish_connection() File "/home/codertjay/.virtualenvs/Gimsap-Ecommerce/lib/python3.9/site-packages/kombu/transport/pyamqp.py", line 201, in establish_connection conn.connect() File "/home/codertjay/.virtualenvs/Gimsap-Ecommerce/lib/python3.9/site-packages/amqp/connection.py", line 323, in connect self.transport.connect() File "/home/codertjay/.virtualenvs/Gimsap-Ecommerce/lib/python3.9/site-packages/amqp/transport.py", line 129, in … -
Does obj.save() in save_model() in admin.ModelAdmin call save() in models.Model?
I overrided "save()" in "Person(models.Model)" class as shown below: # "models.py" from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) def save(self, *args, **kwargs): super().save(*args, **kwargs) Then, I also overrided "save_model()" in "PersonAdmin(admin.ModelAdmin)" class as shown below: # "admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): super().save_model(request, obj, form, change) Then, I could add "Steve Jobs" as shown below: Next, for "save_model()" in "PersonAdmin(admin.ModelAdmin)" class, I replaced "super().save_model(request, obj, form, change)" with "pass" as shown below: # "admin.py" from django.contrib import admin from .models import Person @admin.register(Person) class PersonAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): pass # super().save_model(request, obj, form, change) But now, I couldn't add "Bill Gates" as shown below: So, I checked save_model() on Django repository on GitHub. Then, in "save_model()" in ModelAdmin(BaseModelAdmin)" class, "obj.save()" is called as shown below: # "django/django/contrib/admin/options.py" # ... class ModelAdmin(BaseModelAdmin): # ... def save_model(self, request, obj, form, change): """ Given a model instance save it to the database. """ obj.save() # Here So, does "obj.save()" call "save()" in "Person(models.Model)" class? -
Javascript: Ecommerce add to cart function not working in Javascript?
I am trying to write an add to cart functionality using Javascript and django (main functionality is Javascript). I have written this code for the cart.js var updateBtns = document.getElementsByClassName('update-cart') console.log("Working"); for (i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId is:', productId, 'Action is:', action) console.log('USER:', user) }) } And this is the code for template index.html {% for product in products %} {{ product.title }} {{ product.price}} <button data-product="{{product.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> {% endfor %} When i print(product.id) it gets the specific product id but the button does not wwork what could be the problem with my code? -
I am getting an error in Django while trying to submit the details in my form, what should I do?
Basically I am filling in the details in my form in Django and clicking on submit but the error is appearing. What should I do? Thanks in advance. My Error- TypeError at /contact Contact() got unexpected keyword arguments: 'name', 'email', 'phone', 'desc', 'date' My views.py from django.shortcuts import render, HttpResponse from datetime import datetime from Home.models import Contact # Create your views here. def index(request): context = { 'variable':"this is sent" } return render(request,'index.html',context) #return HttpResponse("This is Home Page") def about(request): return render(request,'about.html') #return HttpResponse("This is About Page") def services(request): return render(request,'services.html') #return HttpResponse("This is Service Page") def contact(request): if request.method == "POST": name=request.POST.get('name') email=request.POST.get('email') phone=request.POST.get('phone') desc=request.POST.get('desc') contact = Contact(name=name, email=email, phone=phone, desc=desc,date=datetime.today) contact.save() return render(request,'contact.html') #return HttpResponse("This is Contact Page") My urls.py from django.contrib import admin from django.urls import path from Home import views urlpatterns = [ path("",views.index, name='home'), path("about",views.about, name='about'), path("services",views.services, name='services'), path("contact",views.contact, name='contact'), ]