Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery consumes all queues
I'm trying to achieve a following configuration: Send a message to RabbitMQ. Copy this message to 2 different queues. Run 2 consumers, where each of them would consume from its own queue. So, I have this to send messages: def publish_message(): with app.producer_pool.acquire(block=True) as producer: producer.publish( body={"TEST": "OK"}, exchange='myexchange', routing_key='mykey', ) I create my consumers this way: with app.pool.acquire(block=True) as conn: exchange = kombu.Exchange( name="myexchange", type="direct", durable=True, channel=conn, ) exchange.declare() queue1 = kombu.Queue( name="myqueue", exchange=exchange, routing_key="mykey", channel=conn, # message_ttl=600, # queue_arguments={ # "x-queue-type": "classic" # }, durable=True ) queue1.declare() queue2 = kombu.Queue( name="myotherqueue", exchange=exchange, routing_key="mykey", channel=conn, # message_ttl=600, # queue_arguments={ # "x-queue-type": "classic" # }, durable=True ) queue2.declare() class MyConsumer1(bootsteps.ConsumerStep): def get_consumers(self, channel): return [ kombu.Consumer( channel, queues=[queue1], callbacks=[self.handle], accept=["json"] ) ] def handle(self, body, message): print(f"\n### 1 ###\nBODY: {body}\nCONS: {self.consumers}\n#########\n") message.ack() class MyConsumer2(bootsteps.ConsumerStep): def get_consumers(self, channel): return [ kombu.Consumer( channel, queues=[queue2], callbacks=[self.handle], accept=["json"] ) ] def handle(self, body, message): print(f"\n### 2 ###\nBODY: {body}\nCONS: {self.consumers}\n#########\n") message.ack() app.steps["consumer"].add(MyConsumer1) app.steps["consumer"].add(MyConsumer2) But when I run worker passing -Q myqueue I get this: (venv) ➜ src git:(rabbitmq-experiment) ✗ celery -A settings worker -X myotherqueue --hostname 1@%h -------------- 1@gonczor v5.0.5 (singularity) --- ***** ----- -- ******* ---- Linux-5.11.0-37-generic-x86_64-with-glibc2.31 2021-10-14 19:37:26 - *** --- * --- … -
How can I run a bot in loop 24 hours a day in Django?
I have developed a bot which needs to be 24 hours online and I set the website up in namecheap (Just a hosting) and it kills my process when it has been running for 2 hours or something like that. [UID:3232][2228262] Killing runaway process PID: 2228339 with SIGTERM [UID:3232][2228262] Child process with pid: 2228339 was killed by signal: 15, core dump: 0 This is what it returns and I would like to avoid this, I have been reading about django-background-tasks but I'm not sure if I can make it run for the whole day. -
django.db.utils.OperationalError: no such table: Recruiter_jobs table not found error?
I Am doing a project in Django and I have created some models in my project and after migrating it gives me something error like Django.db.utils.OperationalError: no such table: Recruiter_jobs, but I think I have all the tables registered in admin also. but still, it showing an error... here's my models.py class empDetail(models.Model): cmpName=models.CharField("Company Name ",max_length=30) role=models.CharField("role ",max_length=20) def __str__(self): return self.empEmail class jobs(models.Model): location=models.CharField("Location ",max_length=30) desc=models.CharField("Descriptions ",max_length=3000) role=models.CharField("role ",max_length=10) sal=models.CharField("salary ",max_length=20) def __str__(self): return self.desc class candetail(models.Model): location=models.CharField("Locations ",max_length=30,default="") role=models.CharField("Role ",max_length=100,default="") cv=models.FileField(upload_to="media/canDetails/") def __str__(self): return self.location class availablejob(models.Model): cmpny=models.CharField("Company Name",max_length=100,default="") location=models.CharField("Location ",max_length=30) desc=models.CharField("Descriptions ",max_length=3000) role=models.CharField("Role ",max_length=100) sal=models.CharField("Salary ",max_length=20) def __str__(self): return self.role class empDetails(models.Model): cmpName=models.CharField("Company Name ",max_length=30) role=models.CharField("role ",max_length=20) cv=models.FileField(upload_to="media/empDetails/") def __str__(self): return self.empEmail heres the logs below (env) PS C:\Users\ashwi\Documents\GitHub\AMCH\AMCH_Recruiter> python manage.py migrate Operations to perform: Apply all migrations: Recruiter, admin, auth, contenttypes, sessions Running migrations: Applying Recruiter.0008_delete_jobs...Traceback (most recent call last): File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: Recruiter_jobs The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\ashwi\Documents\GitHub\AMCH\AMCH_Recruiter\manage.py", line 22, in <module> main() File "C:\Users\ashwi\Documents\GitHub\AMCH\AMCH_Recruiter\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\core\management\__init__.py", … -
502 Bad Gateway on Nginx When Trying to Deploy two different services on same url but different ports
I am trying to deploy a build version of React JS and Django Server on different ports. React JS serves on port 3000 and Django Server should serve on 8000. React JS works perfectly fine however URL to Django server says 502 bad gateway. Here is error logs of nginx. 2021/10/14 23:47:31 [error] 4250#4250: *2 connect() failed (111: Connection refused) while connecting to upstream, client: 127.0.0.1, server: example.com, request: "GET / HTTP/1.1", upstream: "uwsgi://127.0.0.1:8001", host: "localhost:8000" Here is my localhost file present in /etc/nginx/sites-available # mysite_nginx.conf # the upstream component nginx needs to connect to upstream django { # server unix:///path/to/your/mysite/mysite.sock; # for a file socket server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name example.com; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { alias /var/www/runbackend/backend/media; # your Django project's media files - amend as required } location /static { alias /var/www/runbackend/backend/static; # your Django project's static files - amend as … -
ImportError: No module named django.core.wsgi for Apachein CentOS 7
I am deploying a Django app on Apache in CentOS 7. My project is within a virtual environment created with pipenv shell. Django is installed in that virtual environment only and not globally. Below is the location of this virtual environment (as in where I run pipenv shell): /home/centos/proj/my_app And my app folder structure which contains wsgi.py is as following: /home/centos/proj/my_app/my_app/my_app/wsgi.py When I deployed, I see the following error in Apache log file: [Thu Oct 14 18:02:47.599843 2021] [:error] [pid 2999] [remote xx.x.xx.xx:116] mod_wsgi (pid=2999): Target WSGI script '/home/centos/proj/my_app/my_app/my_app/wsgi.py' cannot be loaded as Python module. [Thu Oct 14 18:02:47.600490 2021] [:error] [pid 2999] [remote xx.x.xx.xx:116] mod_wsgi (pid=2999): Exception occurred processing WSGI script '/home/centos/proj/my_app/my_app/my_app/wsgi.py'. [Thu Oct 14 18:02:47.600510 2021] [:error] [pid 2999] [remote xx.x.xx.xx:116] Traceback (most recent call last): [Thu Oct 14 18:02:47.600528 2021] [:error] [pid 2999] [remote xx.x.xx.xx:116] File "/home/centos/proj/my_app/my_app/my_app/wsgi.py", line 15, in <module> [Thu Oct 14 18:02:47.600610 2021] [:error] [pid 2999] [remote xx.x.xx.xx:116] from django.core.wsgi import get_wsgi_application [Thu Oct 14 18:02:47.600626 2021] [:error] [pid 2999] [remote xx.x.xx.xx:116] ImportError: No module named django.core.wsgi This thread here described a similar issue, but for uwsgi. It said that because Django is installed locally in the virtual environment, the PYTHONPATH is therefore incorrect … -
Trying to open a new template with django queryset data and show just one entry
I have a dashboard for a manufacturer that lists a snapshot of the products info based on if that product is made by their company. I want to be able to open the product snapshot into another html page so that updates can be made to it. I can filter the products in the dashboard and it clicks through and opens up the correct info on the new html page, but the problem is that it opens up all of the products on the page and lists them as well. My View: def product_info(request): manufacturer = Manufacturer.objects.get(user) company = manufacturer.company products = Products.objects.filter(manufacturer=company).all return render(request, 'My_app/product-expanded.html', {'products': products}) The HTML {% for product in products %} <div class="product-name"> <h3 style="text-decoration: underline;">{{ product.name|default:'Product'}}</h3> </div> {% if product %} <div class="product-expanded"> <ul> <li class="product-card"><br> <div id="product-price"> Community: {{ product.price }} </div> </li> </ul> </div> {% else %} <div class="no-products"> <h2>You have no current products.</h2> </div> {% endif %} {% endfor %} Any help would be greatly appreciated. Thank you. -
Annotate only returns specified grouping values - Django
I'm trying to sum column values of some rows with the a specific column value (currency_id) using annotate. My rows look like this: id | amount | currency_id | info1 | info2 1 | 14 | 1 | xxx | xxx 2 | 25 | 1 | xxx | xxx 3 | 92 | 2 | yyy | yyy And I want to get this: id | amount | currency_id | info1 | info2 1 | 39 | 1 | xxx | xxx 3 | 92 | 2 | xxx | xxx Here is my code: items = Item.objects.values('currency_id').annotate( Sum('amount'), ) Which works but I only get the column currency_id and the amount sum in the result: <QuerySet [{'currency_id': 1, 'amount__sum': 39}, {'currency_id': 2, 'amount__sum':92] This is because I use values() to specify the column to group. How can I get all other columns values? -
PermissionError: [Errno 13] Permission denied on Windows with WSL2 and Docker
I have a Docker dev setup that works fine on Mac and Windows with Hyper-V but not on Windows with WSL2. When Python attempts to execute a makedirs command, we get a PermissionError: [Errno 13] Permission denied error. For example, when attempting to make /code/static, we get: PermissionError: [Errno 13] Permission denied: '/code/static' Similarly for Django's makemigrations command, which attempts to make a migrations directory at /code/website/migrations we get: PermissionError: [Errno 13] Permission denied: '/code/website/migrations' But our Dockerfile clearly gives the apache user permission to the /code/ folder. Here's the full Dockerfile: # All Dockerfiles must start with a 'FROM' instruction, which specifies a base image # See: https://docs.docker.com/engine/reference/builder/#format # Note, some online sources say that you should put FROM django here (e.g., https://runnable.com/docker/python/dockerize-your-django-application) # but, in fact, you should NOT do this according to the official docs (as this approach has been deprecated). # See: https://hub.docker.com/_/django/ FROM python:3.8 # Sometimes we get warnings about old pip, so take care of that here RUN pip install --upgrade pip # See: https://www.quora.com/How-does-one-install-pip-in-a-Docker-container-using-a-Dockerfile RUN apt-get update && apt-get --assume-yes install imagemagick ghostscript sqlite3 # The ENV instruction sets the environment variable <key> to the <value> in ENV <key> <value>. # See: https://docs.docker.com/engine/reference/builder/#environment-replacement … -
how to show posts for a specific hour from its publishing time
I'm trying to show my posts for a specific time here is my models.py class Booking(models.Model): check_in = models.DateTimeField(default=timezone.now) check_out = models.DateTimeField(blank=True,null=True) i want display object for 12 hours after check out for example if we have an object its check out is 14/10/2021 10AM then show that post till 10PM ! i tried it , but didnt work Booking.objects.filter(check_out__hour=12) is it possible please ? thank you in advance -
No suggestion (autocomplete) for relation filed (1-to-many) in Django Model
For example two models: from django.db import models from datetime import datetime class Account(models.Model): date_field = models.CharField( max_length=255, verbose_name='Дата', help_text='Поле даты в BigQuery' ) class Lead(models.Model): account = models.ForeignKey( Account, on_delete=models.CASCADE, default=None, verbose_name='ID аккаунта BigQuery', ) def __str__(self): iso = self.data.get(f'{self.account.date_field}') date = datetime.fromisoformat(iso).strftime('%d-%m-%Y, %H:%M') return f'Lead by «{self.account}», created at {date}' VS Code doesn't see date_field in Lead.account. I have installed the Django, Python and Intellisense VS Code extension. Can i fit ix? -
Why static files giving not found error in django app?
I am creating a django app and everything going good so far, but I am having trouble with the static files. I have: STATIC_URL = '/static/' STATICFILES_DIRS = [ # Tell Django where to look for React's static files (css, js) os.path.join(BASE_DIR, "frontend/static"), ] STATIC_ROOT = os.path.join(BASE_DIR, "static/") STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' When I am on home page then it is working fine, all static files are loaded perfectly but problem starts when I try to go to /dashboard Then I get Not Found error, when I debugged then the path for static files are like /dashoard/static/styles.css but it should be /static/styles.css. Why it is changing path for the static files? -
Django + Nginx corsheaders not visible for random endpoints
I am developing a web application with Django, Vue and Docker. For a while, I started to face the issue of CORS policy error. The weird thing is that the error sometimes appears and sometimes it does not appear - I can not detect what does it depend on. Usually there are some changes after rebuilding the whole project with command docker-compose up --build, however, I can not distinguish a single reason why am I getting CORS error on the server and localhost as well. The error message is as the following: Access to XMLHttpRequest at 'https://api.mywebsite.com/profile/' from origin 'https://mywebsite.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I did setup CORS for Django, here's the configuration: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] # ... CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = [ 'https://mywebsite.com', # Here's where the web application is 'https://api.mywebsite.com', # Here's Django API ] Here's nginx.conf file: server { listen 80 default_server; client_max_body_size 20M; location / { autoindex on; if ($request_method = OPTIONS) { return 204; } add_header Access-Control-Allow-Origin "https://mywebsite.com"; add_header Access-Control-Allow-Origin "https://api.mywebsite.com"; add_header Access-Control-Max-Age 3600; add_header Access-Control-Expose-Headers Content-Length; add_header Access-Control-Allow-Headers Range; } location /static/ { autoindex on; alias /static/; } … -
Django Rest Framework - process result of serializer in another serializer
I have the following two views at my django api views.py: @api_view(['GET',]) @authentication_classes([JSONWebTokenAuthentication]) @permission_classes([AllowAny]) def user(request): if request.method == 'GET': serializer = UserSerializer(request.user) return JsonResponse(serializer.data, safe=False) @api_view(['POST']) @permission_classes([AllowAny]) def user_create(request): exception_handler = UserUnavailable success_handler = UserCreated if request.method == 'POST': serializer = CreateUserSerializer(data=request.data) try: if serializer.is_valid(raise_exception=True): serializer.save() return JsonResponse({"status_code": success_handler.status_code, "default_detail": success_handler.default_detail, "default_code": success_handler.default_code, "user_object": UserSerializer(serializer.instance) }, safe=False) except APIException: return JsonResponse({"status_code": exception_handler.status_code, "default_detail": exception_handler.default_detail, "default_code": exception_handler.default_code }, safe=False) What I want to do is that after the user has been created, I would like to show the user object in the API response, thats why I have UserSerializer(serializer.instance) in place but it seems that this statement is simply wrong. Can somebody help? -
Read value of an html script element in Angular, which is of type json
In the html page, there will be a script element which is a static content ( generated from a Django backend) with an ID. <script id="hello-data" type="application/json">{"hello": "world\\u003C/script\\u003E\\u0026amp;"}</script> I wanted to get that data in an angular service ( or even component) which would have a simple getElementById is javascript. const value = JSON.parse(document.getElementById('hello-data').textContent); I did a lot of searches, found answers pointing to "ViewChild", "@Inject(DOCUMENT)", but none of these works on a 'script' tag. Any pointers to solution would be really appreciated :) -
Object of type '' is not JSON serializable in DRF
I have this code in Django using the REST framework. Here are my models, serializer, views: model: class Car(AbstractTimeTrackable, models.Model): production_type = models.ForeignKey( 'cars.CarProductionType', on_delete=models.PROTECT, related_name='cars', verbose_name=_('production_type') ) warehouse = models.ForeignKey( 'warehouses.Warehouse', on_delete=models.SET_NULL, verbose_name=_('warehouse'), related_name='cars', blank=True, null=True, ) class Meta: verbose_name = _('Auto') verbose_name_plural = _('Auto') def __str__(self): return str(self.id) class Reservation(AbstractTimeTrackable, models.Model): is_active = models.BooleanField( default=False, verbose_name=_('is_active') ) cars = models.ManyToManyField( 'cars.Car', verbose_name=_('ID cars') ) class Meta: verbose_name = _('Reservation') verbose_name_plural = _('Reservation') def __str__(self): return str(self.id) serializer: class ReservationSerializer(serializers.ModelSerializer): days_count = serializers.IntegerField(required=True) cars = serializers.PrimaryKeyRelatedField(queryset=Car.objects.all(), many=True) class Meta: model = Reservation fields = [ 'id', 'is_active', 'cars' ] extra_kwargs = { 'id': {'read_only': True} } def create(self, validated_data): cars = validated_data.pop('cars') instance = super().create(validated_data) if cars: instance.cars.add(*cars) return instance view: class ReservationViewSet(CreateModelMixin, GenericViewSet): serializer_class = ReservationSerializer queryset = Reservation.objects.all() def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(status=status.HTTP_201_CREATED, data=serializer.validated_data) I am getting this error message: TypeError at /api/v1/reservations/ Object of type Car is not JSON serializable I need only PrimaryKey of Cars; that's why I use PrimaryKeyRelatedField. How can I resolve this error? -
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable
I had to reinstall my pycharm and now when I try to run my Django server I get the following error: (card_companion_venv) PS N:\My Drive\Projects\Card Companion\card_companion> python website/manage.py runserver 0.0.0.0:8000 --settings=website.settings.base Traceback (most recent call last): File "N:\My Drive\Projects\Card Companion\card_companion\website\manage.py", line 9, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "N:\My Drive\Projects\Card Companion\card_companion\website\manage.py", line 20, in <module> main() File "N:\My Drive\Projects\Card Companion\card_companion\website\manage.py", line 11, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? The interpreter has the correct packages installed: and the terminal is using the virtual environment: (card_companion_venv) PS N:\My Drive\Projects\Card Companion\card_companion> -
Django: Prefill the values of a Django form with the values of another one in another template(view)
I'm stuck on this problem of prefilling the values of a Django form of a specific template with the values of another form that is in another html page. What I have is an administration panel with a table with all the users (every row is a user) and I have a button called Edit to edit these ones. What I would like to do is to, when this button is clicked, redirect the user to another page where there is a form that needs to be prefilled with the values of the row of the table related to that specific user. I have tried session already but it didn't work. Here's what I tried. Template with the table <form method="POST" action="/administration/modify" id="update_form"> {% csrf_token %} <input type="hidden" value="{{i.email}}" name="update_email" /> <button type="submit" name="update_user" class="btn btn-primary"> Update</button></td> View of the page with the table where the values of the form need to come: update_email=request.POST["update_email"] request.session["modify_user"]=update_email return redirect("modify") View of the page with the form that needs to be filled: if request.method=="POST": form_update_user=UpdateUserForm(request.POST) #when the user fill the form .... else: update_email=request.session.get("modify_user") user_update=Utente.objects.get(email=update_email) print("******************************************") print(user_update.name) form_update_user=UpdateUserForm(initial={"name":user_update.name, "surname":user_update.surname,"email":user_update.email,"role_name":user_update.ruolo,"ente_name":user_update.ente,"password":"","confirm_password":""}) What i have is this: Page with the form that needs to be prefilled … -
How to iterate 3 nested lists on django template
I have 3 lists on my views and I want to iterate it with django template with nestedly. Eg: here I have 3 lists name card_postings,arrays and post_content card_postings = ['Indicatif', 'Subjonctif', 'Conditionnel', 'Participe', 'Impératif', 'Infinitif'] arrays = [['Présent', 'Imparfait', 'Futur', 'Passé simple', 'Passé composé', 'Plus-que-parfait', 'Passé antérieur', 'Futur antérieur'], ['Présent', 'Imparfait', 'Plus-que-parfait', 'Passé'], ['Présent', 'Passé première forme', 'Passé deuxième forme'], ['Présent', 'Passé composé', 'Passé'], ['Présent', 'Passé'], ['Présent', 'Passé']] post_content = [["j'ai", 'tu as', 'il/elle a', 'nous avons', 'vous avez', 'ils/elles ont'], ["j'avais", 'tu avais', 'il/elle avait', 'nous avions', 'vous aviez', 'ils/elles avaient'], ["j'aurai", 'tu auras', 'il/elle aura', 'nous aurons', 'vous aurez', 'ils/elles auront'], ["j'eus", 'tu eus', 'il/elle eut', 'nous eûmes', 'vous eûtes', 'ils/elles eurent'], ["j'ai eu", 'tu as eu', 'il/elle a eu', 'nous avons eu', 'vous avez eu', 'ils/elles ont eu'], ["j'avais eu", 'tu avais eu', 'il/elle avait eu', 'nous avions eu', 'vous aviez eu', 'ils/elles avaient eu'], ["j'eus eu", 'tu eus eu', 'il/elle eut eu', 'nous eûmes eu', 'vous eûtes eu', 'ils/elles eurent eu'], ["j'aurai eu", 'tu auras eu', 'il/elle aura eu', 'nous aurons eu', 'vous aurez eu', 'ils/elles auront eu'], ["que j'aie", 'que tu aies', "qu'il/elle ait", 'que nous ayons', 'que vous ayez', "qu'ils/elles aient"], ["que j'eusse", … -
AssertionError at /graphql/ A Schema is required to be provided to GraphQLView
I have a Django API with a GraphQL route. Here is my models.py: class MyBook(models.Model): id = models.BigAutoField(primary_key= True) book_name = models.CharField(max_length= 200) title = models.CharField(max_length= 200) In my Schema.py: import graphene from graphene_django.views import GraphQLSchema from graphene_django import DjangoObjectType from publishing_house_app.models import * class BookType(DjangoObjectType): class Meta: model= MyBook fields= "__all__" class RootQuery(graphene.ObjectType): books = graphene.List(BookType) def resolve_books(self, root, info, **kwargs): MyBook.objects.all() MyBookSchema = graphene.Schema(query= RootQuery) in urls.py: from .views import * from rest_framework.urlpatterns import path from graphene_django.views import GraphQLView from .GraphQL import Schema urlpatterns = [ path("graphql/", GraphQLView.as_view(graphiql= True, schema= Schema)), ] I am getting the following error: File "C:\Python39\lib\site-packages\graphene_django\views.py", line 127, in init assert isinstance. AssertionError at /graphql/ A Schema is required to be provided to GraphQLView. -
Where to put a code that interacts with DB and should run once on the project startup in django 2.2 or higher?
I'm trying to write some code that checks on something, if exists then cool and if not creates it. The problem is, where to put this code? Django doesn't recommend putting anything that deals with DB at an app's ready() function - this is what I'm currently doing but it gives me an error on debugging and give an error too on the beginning but works later on-. Also, what I have found seems outdated and a bit hacky like putting it at urls.py or wsgi.py. I feel there must be a better way to do it. Thank you all. -
I need some help guys
TypeError at /admin/catalog/book/ display_genre() takes 1 positional argument but 2 were given Request Method: GET Request URL: http://127.0.0.1:8000/admin/catalog/book/ Django Version: 3.2.8 Exception Type: TypeError Exception Value: display_genre() takes 1 positional argument but 2 were given Exception Location: C:\Users\User1\Envs\my_django_environment\lib\site-packages\django\contrib\admin\utils.py, line 274, in lookup_field Python Executable: C:\Users\User1\Envs\my_django_environment\Scripts\python.exe Python Version: 3.6.1 Python Path: ['C:\Users\User1\Desktop\django_projects\locallibrary', 'C:\Users\User1\Envs\my_django_environment\Scripts\python36.zip', 'c:\users\user1\appdata\local\programs\python\python36\DLLs', 'c:\users\user1\appdata\local\programs\python\python36\lib', 'c:\users\user1\appdata\local\programs\python\python36', 'C:\Users\User1\Envs\my_django_environment', 'C:\Users\User1\Envs\my_django_environment\lib\site-packages'] Server time: Thu, 14 Oct 2021 15:56:29 +0000 -
Error in Django 3.2.7 - TemplateSyntaxError at /blog/ 'menus_tags' is not a registered tag library
While messing a little with routable pages and latest posts config, i ran into this error and i have no idea of how to fix it. Error is shown here Django 3.2.7 Python 3.9.6 debug_toolbar 3.2.2 Taggit 1.5.1 Wagtail core 2.14.1 -
'int' object has no attribute 'save' while I am trying to update multiple row
I am trying to update multiple row depends on multiple data. But while I submit, only one row update and got this error 'int' object has no attribute 'save'. I think the problem is in my view. My view are given bellow: def saleForm(request): stb = [] if request.method == 'POST': for stb_array in request.POST.getlist('stb_sl'): stb.append(stb_array) i = 0 for stb_ho in stb: stb_update = StpDetails.objects.filter(stp_sl=stb_ho).update( sale_date=date, sales_invoice=invoice, status='Sold') stb_update.save() i += 1 messages.success(request, 'You have successfully save data.') return render(request,'sale/invoice_details.html',{}) My Model: class StpDetails(models.Model): id = models.AutoField(primary_key=True) entry_date = models.DateField(default=date.today) stp_sl = models.CharField(max_length=50, unique=True) stp_name = models.CharField(max_length=30) sale_date = models.DateField(auto_now=False, null=True) sales_invoice = models.CharField(max_length=20, blank=True) install_date = models.DateField(auto_now=False, null=True) installer = models.CharField(max_length=50, blank=True) house = models.CharField(max_length=100, blank=True) status = models.CharField(max_length=7, default='Unsold') def __str__(self): return self.stp_sl -
Limit the user to give the test only once per course
I want to limit the student to attempt specific test once per course. There can be multiple quizzes but each student should be giving test once only. The student field is one to one field with user views.py has :- @login_required(login_url='studentlogin') @user_passes_test(is_student) def start_exam_view(request,pk): course=QMODEL.Course.objects.get(id=pk) questions=QMODEL.Question.objects.all().filter(course=course) """ Update Status of exam taken """ status = models.Student.objects.get(user_id=request.user.id) status.taken_status = True status.save() if request.method=='POST': pass response= render(request,'student/start_exam.html',{'course':course,'questions':questions}) response.set_cookie('course_id',course.id) return response @login_required(login_url='studentlogin') @user_passes_test(is_student) def calculate_marks_view(request): if request.COOKIES.get('course_id') is not None: course_id = request.COOKIES.get('course_id') course=QMODEL.Course.objects.get(id=course_id) total_marks=0 questions=QMODEL.Question.objects.all().filter(course=course) for i in range(len(questions)): selected_ans = request.COOKIES.get(str(i+1)) actual_answer = questions[i].answer if selected_ans == actual_answer: total_marks = total_marks + questions[i].marks student = models.Student.objects.get(user_id=request.user.id) result = QMODEL.Result() result.marks=total_marks if result.marks >= course.cutoff_marks: student.result_status = True student.save() else: student.result_status = False student.save() result.exam=course result.student=student result.save() return HttpResponseRedirect('view-result') Quiz Model :- class Course(models.Model): course_name = models.CharField(max_length=50) question_number = models.PositiveIntegerField() total_marks = models.PositiveIntegerField() cutoff_marks = models.PositiveIntegerField(default=0) def __str__(self): return self.course_name class Question(models.Model): course=models.ForeignKey(Course,on_delete=models.CASCADE) marks=models.PositiveIntegerField() question=models.CharField(max_length=600) option1=models.CharField(max_length=200) option2=models.CharField(max_length=200) option3=models.CharField(max_length=200) option4=models.CharField(max_length=200) cat=(('Option1','Option1'),('Option2','Option2'),('Option3','Option3'),('Option4','Option4')) answer=models.CharField(max_length=200,choices=cat) class Result(models.Model): student = models.ForeignKey(Student,on_delete=models.CASCADE) exam = models.ForeignKey(Course,on_delete=models.CASCADE) marks = models.PositiveIntegerField() date = models.DateTimeField(auto_now=True) Student Model:- class Student(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) profile_pic= models.ImageField(upload_to='profile_pic/Student/',null=True,blank=True) address = models.CharField(max_length=40) mobile = models.CharField(max_length=20,null=False) taken_status = models.BooleanField(default=False) result_status = models.BooleanField(default=False) @property def get_name(self): return self.user.first_name+" "+self.user.last_name @property def … -
How to route many paths to one url in django python
I would like to route all paths ending in 'search/' to one url. I have tried many ways, But nothing worked. the following is the last that I tried. path(r'^search/$', views.search, name="search"), Can you please help?