Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No module named 'config.settings' while deploying Django app on heroku (STILL NOT ANSWERED FROM OTHER QUESTION)
First of all, the question already asked here is still not answered. Secondly, this link is for an Apache server. The problem that I am having is with a website that builds and deploys with no errors. However, there is an application error and this is the Heroku logs: 2021-09-17T03:34:09.334126+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2021-09-17T03:34:09.334126+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2021-09-17T03:34:09.334126+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked 2021-09-17T03:34:09.334127+00:00 app[web.1]: ModuleNotFoundError: No module named 'config.settings' 2021-09-17T03:34:09.334298+00:00 app[web.1]: [2021-09-17 03:34:09 +0000] [9] [INFO] Worker exiting (pid: 9) 2021-09-17T03:34:09.367176+00:00 app[web.1]: [2021-09-17 03:34:09 +0000] [4] [WARNING] Worker with pid 9 was terminated due to signal 15 2021-09-17T03:34:09.462499+00:00 app[web.1]: [2021-09-17 03:34:09 +0000] [4] [INFO] Shutting down: Master 2021-09-17T03:34:09.462582+00:00 app[web.1]: [2021-09-17 03:34:09 +0000] [4] [INFO] Reason: Worker failed to boot. 2021-09-17T03:34:09.609202+00:00 heroku[web.1]: Process exited with status 3 2021-09-17T03:34:09.666279+00:00 heroku[web.1]: State changed from starting to crashed 2021-09-17T06:31:35.431068+00:00 heroku[web.1]: State changed from crashed to starting 2021-09-17T06:31:44.765393+00:00 heroku[web.1]: Starting process with command `gunicorn td-auth-master.wsgi --log-file -` 2021-09-17T06:31:46.007394+00:00 app[web.1]: [2021-09-17 06:31:46 +0000] [4] [INFO] Starting gunicorn 20.1.0 2021-09-17T06:31:46.007831+00:00 app[web.1]: [2021-09-17 06:31:46 +0000] [4] [INFO] Listening at: http://0.0.0.0:13306 (4) 2021-09-17T06:31:46.007879+00:00 app[web.1]: [2021-09-17 06:31:46 +0000] [4] [INFO] Using worker: sync 2021-09-17T06:31:46.011232+00:00 app[web.1]: [2021-09-17 … -
user input and text choice as well in django model
In django model, user input and text choices to be filled to a field name. class Store(models.Model): class Size(model.TextChoices): MEDIUM = "M", "Medium" LARGE = "L","Large" shirt_size = models.CharField("Shirt Size", choices=Size.choices, default=Size.MEDIUM) When django is run with admin to add records to table, it will show drop down to choose Size which are available and at the same time, i want to have custom fill as well for user input(S, XXL, etc..) -
how to render list directory tree structure using python in django?
[enter image description here][1] i tried to print list of directories in html web page using python-Django but facing error. Python code run perfectly in pycharm but while i render the same it's shows error. Kindly help on this [1]: https://i.stack.imgur.emphasized textcom/e5q8M.png -
ParseError at /api/ JSON parse error - Expecting value: line 1 column 1 (char 0)
''' Internal Server Error: /api/ Traceback (most recent call last): File "C:\Users\Biswojit\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\parsers.py", line 65, in parse return json.load(decoded_stream, parse_constant=parse_constant) File "C:\Users\Biswojit\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\utils\json.py", line 31, in load return json.load(*args, **kwargs) File "C:\Users\Biswojit\AppData\Local\Programs\Python\Python38\lib\json_init_.py", line 293, in load return loads(fp.read(), File "C:\Users\Biswojit\AppData\Local\Programs\Python\Python38\lib\json_init_.py", line 370, in loads return cls(**kw).decode(s) File "C:\Users\Biswojit\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\Biswojit\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Biswojit\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Biswojit\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Biswojit\AppData\Local\Programs\Python\Python38\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Biswojit\AppData\Local\Programs\Python\Python38\lib\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "F:\Projects\DRF\fpro\firstapp\views.py", line 17, in get data=JSONParser().parse(stream) File "C:\Users\Biswojit\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\parsers.py", line 67, in parse raise ParseError('JSON parse error - %s' % str(exc)) rest_framework.exceptions.ParseError: JSON parse error - Expecting value: line 1 column 1 (char 0) [17/Sep/2021 12:06:07] "GET /api/ HTTP/1.1" 500 102139 F:\Projects\DRF\fpro>json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) ''' -
How to insert values in user table and to map the user table and role table and store the user_id and role_id into the role_user table using django
I need to get the user values from postman by using "POST" method and to map the role values into all the users and save user_id and role_id into role_user table. The way i inserted the values: { "email": "sk@hara.com", "phone": "1234567890", "roles": { "id": 1, "name": "Lab User", "is_deleted": false }, } usermodel.py class user(AbstractBaseUser): email = models.EmailField(max_length=255, blank=False, null=False, unique=True) phone = models.CharField(max_length=20, blank=True, null=True) roles = models.ManyToManyField('Role', related_name="role_user", db_table="role_user") class Meta: db_table='user' userserializer.py class Adduser(serializers.ModelSerializer): email = serializers.CharField(max_length=255, required=True, validators=[user_exists]) roles = serializers.PrimaryKeyRelatedField(queryset=Role.objects.all(), many=True, default=None) class Meta: model = User fields = ['email', 'roles', 'phone'] rolemodel.py class Role(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100, blank=False, null=False) is_deleted = models.BooleanField(default=False, null=False) class Meta: db_table = "role" roleserializer.py class RoleSerializer(serializers.ModelSerializer): class Meta: model = Role fields = ['id', 'name', 'description'] -
Filtering and grouping over many-to-many relationship Django
How can I write the code below with the .filter() method in the best way? These are my models class RoomCategory(models.Model): price = models.CharField(max_length=1000, default='', blank=True, verbose_name=_("Price")) title = models.CharField(max_length=1000, default='', blank=True, verbose_name=_("Title")) description = RichTextField(default='', blank=True, verbose_name=_("Description")) class Room(models.Model): category = models.ForeignKey(RoomCategory, verbose_name=_("Room category"), related_name="rooms", on_delete=models.CASCADE, null=True) class Reservation(models.Model): forename = models.CharField(verbose_name=_('First name'), max_length=20, blank=True,) surname = models.CharField(verbose_name=_('Last name'), max_length=20, blank=True,) reservation_status = models.CharField(max_length=10,verbose_name=('Reservation status'), choices=( ('pending', _('Waiting')), ('accept', _('Accept')), ('reject', _('Reject')), ),default=('pending'),blank=True, null=True) rooms = models.ManyToManyField(Room) To better express my intentions. I want something that I would achieve in pure python with something like this: def check_availability(room, check_in, check_out): available_list = [] reservation_list = room.reservation_set.all().filter(reservation_status="accept") for reservation in reservation_list: if reservation.date_from > check_out or reservation.date_until < check_in: available_list.append(True) else: available_list.append(False) return all(available_list) Views.py room_list = Room.objects.all() available_rooms = {} for room in room_list: if check_availability(room, data['date_from'], data['date_until']): if room.category.title in available_rooms: available_rooms[room.category.title] += 1 else: available_rooms[room.category.title] = 1 I need to get output like this: <QuerySet [{'RoomCategory': <RoomCategory>, 'count': 14}, {'RoomCategory': <RoomCategory>, 'count': 25}, {'RoomCategory': <RoomCategory>, 'count': 13}, {'RoomCategory': <RoomCategory>, 'count': 2}, {'RoomCategory': <RoomCategory>, 'count': 17}, '... (remaining elements truncated)...']> -
How to get only most recents objects?
I have an option object that contains a list of options that I keep track of. I would like to retrieve the most recent values of this option. My model: class MachineOption(models.Model): name = models.CharField(max_length=200) value = models.CharField(max_length=80) value_type = models.CharField(max_length=10) date_time = models.DateTimeField(auto_now_add=True) machine = models.ForeignKey( "machine.Machine", verbose_name=_("machine"), related_name="machine_options", on_delete=models.CASCADE ) class Meta: verbose_name = _("MachineOption") verbose_name_plural = _("MachineOptions") ordering = ["machine", "name"] def __str__(self): return self.name Each time the value of an option must be modified, I don't overwrite the previous value but I add a new MachineOption object which will have the most recent date_time. I can retrieve the value of a single most recent option with this request: MachineOption.objects.filter(name="threshold temp").latest("date_time") But I don't know how to get the values of all the most recent options. For example, I can have 4 objects: { "id": 6, "name": "name", "value": "m1", "value_type": "string", "date_time": "2021-09-17T07:12:15.446282Z", "machine": 1 }, { "id": 7, "name": "name", "value": "m1.0", "value_type": "string", "date_time": "2021-09-17T07:12:19.904487Z", "machine": 1 }, { "id": 1, "name": "threshold temp", "value": "20", "value_type": "int", "date_time": "2021-09-17T06:57:37.881934Z", "machine": 1 }, { "id": 5, "name": "threshold temp", "value": "30", "value_type": "int", "date_time": "2021-09-17T07:12:06.128011Z", "machine": 1 } I want to be able to … -
The most pythonic way of handling exceptions
I've got this code: normalize_data['key1'] = json.loads(normalize_data.get('key1', '')) normalize_data['key2'] = [key for key in json.loads(normalize_data.get('key2', '[]'))] normalize_data['key3'] = [json.loads(normalize_data.get('key3', ''))] normalize_data['key4'] = [json.loads(normalize_data.get('key4', ''))] As you can see, every key processes differently. If any key will be missing, it will raise JSONEncodeError. If any value of any key will be in wrong format, it will raise TypeError. What is the most pythonic way of handling those? I tried putting this before the code above: for key in ['key1', 'key2', 'key3', 'key4']: if key not in normalize_data: raise serializers.ValidationError({'error': f'Field {key} is missing'}) try: json.loads(normalize_data[key]) except TypeError: raise serializers.ValidationError({'error': f'Wrong format of {key}'}) But I don't really like it. Thanks everybody. -
i am unable to login as an organization in django views
I have requirement to build a crm . In that i have 3 things 1 is super user who is there by default second organization in which i use a foreign key of user bcoz i dont want to create a custom user and re write a lot of things third agent who is user as foreign key and connected to an organization no i want to login as organization in the dashboard if i am using the super user as login credential it is telling me required organization instance if i am login using organization account it is giving error NoReverseMatch at /leads/login_handle here is my views.py login and sign up handle code def signup_handle(request): if request.method == "POST": name = request.POST.get('name') email = request.POST.get('email') pass1 = request.POST.get('pass') pass2 = request.POST.get('re_pass') pass2 = request.POST.get('re_pass') check = request.POST.get('agree-term') if(pass1 != pass2): return HttpResponse("Babe your passwod does not matches please try again") else: x = User.objects.create(email = email,username = email,first_name = name,is_staff = False) # x = User.objects.create(name,email,pass1) x.set_password(pass1) x.save() y = Organization(user = x,name = name) y.save() # print(f"lets varify the data name = {name},{check}") return HttpResponse("Babe you have succesfully created your account") else: return HttpResponse("Babe something goes wrong") def … -
How to unit test a blanck field form in Django?
I spent quite a lot of time to set some unit test, and one of the issues was the setting of some fields that I defines to be nullable and blankable. Putting dummy values was not an issue, but I wonder: how to deal with fields that need to be blank, in particular for numbers? Let me write as an example an extract of my code. The model: class Company(models.Model): company_name = models.CharField("nom", max_length=200) comp_slug = models.SlugField("slug") street_num = models.IntegerField("N° de rue", null=True, blank=True) street_cplt = models.CharField("complément", max_length=50, null=True, blank=True) address = models.CharField("adresse", max_length=300) The form: class CompanyForm(forms.ModelForm): company_name = forms.CharField(label="Société", disabled=True) class Meta: model = Company exclude = [] The view: def adm_options(request, comp_slug): ''' Manage Company options ''' company = Company.get_company(comp_slug) comp_form = CompanyForm(request.POST or None, instance=company) if request.method == "POST": if comp_form.is_valid(): comp_form.save() return render(request, "polls/adm_options.html", locals()) A very simple unit test: def create_dummy_company(name): return Company.objects.create( company_name=name, comp_slug=slugify(name), street_num=1, street_cplt='', address='dummy address' ) def test_adm_options_update(self): self.company = create_dummy_company("Test company") url = reverse("polls:adm_options", args=[self.company.comp_slug]) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.company.address = 'new address' response = self.client.post( reverse("polls:adm_options", args=[self.company.comp_slug]), self.company.__dict__, ) self.company.refresh_from_db() self.assertEqual(response.status_code, 200) Of course, the key part is posting the form after the update. The different cases … -
how can I get user of id when user.is_active=False in django
views.py User Register Class Base in views.py UserRegister need to get id of user when user.is_active = False views.py Verify function base -
Erroneous custom field of the one-to-one User model in the Admin Panel
I created the custom Subscriber one-to-one model to extend the existing Django's User model. (I know that it's better to use an AbstractUser, but I just wanted to try this out for the sake of learning) I can create a new User successfully through the shell, and I can edit (in the admin panel) the custom fields that User has after the creation. However, I can't create new users in the admin panel without the usage of shell, because of an error. I suppose there is something wrong with admin.py? Error: IntegrityError at /admin/auth/user/add/ UNIQUE constraint failed: app_subscriber.user_id models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Subscriber(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) location = models.CharField(max_length=30, blank=True) @receiver(post_save, sender=User) def create_user_subscriber(sender, instance, created, **kwargs): if created: Subscriber.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_subscriber(sender, instance, **kwargs): instance.subscriber.save() admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User from . import models # Define an inline admin descriptor for Subscriber model # which acts a bit like a singleton class SubscriberInline(admin.StackedInline): model = models.Subscriber can_delete = False verbose_name_plural = 'subscribers' # Define a new User admin class UserAdmin(BaseUserAdmin): inlines = (SubscriberInline,) … -
Uploading generated PDF file from React to Django (without <input type="file">)
I'm trying to upload a generated PDF file from React to Django but it won't work. I tested my django end-point using postman and it works properly. I know how to do that with <input type="file"> but, in that case, the user doesn't provide any input because the file is generated as PDF by React. Here's my Django View: class quizPdfView(APIView): parser_classes = [MultiPartParser, FormParser] def post(self,request): try: print(request.data) quizPDF.objects.create(user=request.user,pdf=request.data['pdf']) return Response(status=status.HTTP_200_OK) except Exception as e: print(e) return Response(status=status.HTTP_400_BAD_REQUEST) And here's how i send the data from React (the file that i'm sending is just for test, i will change it later with the one that must be sended): const config = { header: {'Content-Type': 'multipart/form-data'} }; const URL = 'http://127.0.0.1:8000/api/uploadpdf/'; let formData = new FormData(); var doc = new jsPDF(); doc.text(20, 20, 'Hello world!'); doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.'); doc.addPage(); doc.text(20, 20, 'Do you like that?'); formData.append('pdf',doc) axios .post(URL,formData,config) .then((res) => { console.log(res.status) }) .catch((err) => console.log(err)); And, when i send the request, i get this error in django: <QueryDict: {'pdf': ['[object Object]']}> Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x7f47fe90c6d0>": "quizPDF.user" must be a "User" instance. Bad Request: /api/uploadpdf/ [17/Sep/2021 06:54:43] "POST /api/uploadpdf/ HTTP/1.1" 400 … -
Mypy Error : json.decoder.JSONDecodeError: Unterminated string starting at: line x column y (char z)
I am running mypy against my django project in a docker container. Using this command: mypy --install-types --non-interactive --config-file=../setup.cfg "$@" It has been working wonderfully for the past 6 months or so, but sometimes this error arise: Traceback (most recent call last): File "/usr/local/bin/mypy", line 11, in <module> sys.exit(console_entry()) File "/usr/local/lib/python3.6/dist-packages/mypy/__main__.py", line 11, in console_entry main(None, sys.stdout, sys.stderr) File "mypy/main.py", line 96, in main File "mypy/main.py", line 165, in run_build File "mypy/build.py", line 179, in build File "mypy/build.py", line 254, in _build File "mypy/build.py", line 2697, in dispatch File "mypy/build.py", line 3014, in process_graph File "mypy/build.py", line 3089, in process_fresh_modules File "mypy/build.py", line 1975, in load_tree File "/usr/lib/python3.6/json/__init__.py", line 354, in loads return _default_decoder.decode(s) File "/usr/lib/python3.6/json/decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python3.6/json/decoder.py", line 355, in raw_decode obj, end = self.scan_once(s, idx) json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 4925 (char 4924) ERROR: 1 All I could do to fix this issue is fully rebuild the container. Could it be I have misconfigured something ? -
Celery Beat Task Hangs With Out Any Errors
I have a Django app, and I'm using Celery Beat to run a task periodically. If I call the task when running Celery, it runs without errors: app/tasks.py ... @task(name='task1') def func(): # Some code func.run() ... If I then start Celery celery -A project worker -l info, the task runs without errors. The issue comes when I try to run that same task with Celery Beat, imagine I have this schedule: app.conf.beat_schedule = { 'some_task': { 'task': 'task1', 'schedule': crontab(minute=30, hour='22') } } This task should run every day on 22:30, and it does, the task starts but then hangs without logging anything, I cannot figure out the root of the issue, this is not a memory error, I have already checked that, and the task runs fine on my local machine using Celery Beat. I have also tried to use Celery Beat Daemon, but the task keeps hanging whenever it starts. I can't figure out what is happening, any suggestions? -
CSS SVG BackGround image in Django
i used en template who use bootstrap 5, in the css i can find : background-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'/><path fill='none' stroke='%23343a40' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/></svg>"); it seems django don't find this url The bootstrap 5.0 css for select form didn't work and show a standard select box not a bootstrap 5 look . thx for help -
Heroku not actually copying static files over?
I recently changed the directory structure of my django app, which has forced me to set DISABLE_COLLECTSTATIC and specify collectstatic to run on release. Looking at the deployment logs- I see nothing wrong: /app/.heroku/python/lib/python3.8/site-packages/environ/environ.py:637: UserWarning: Error reading /app/.env - if you're not configuring your environment separately, check this. warnings.warn( Adding $DATABASE_URL to default DATABASE Django setting. Adding $DATABASE_URL to TEST default DATABASE Django setting. Applying Heroku ALLOWED_HOSTS configuration to Django settings. Applying Heroku logging configuration to Django settings. Adding $SECRET_KEY to SECRET_KEY Django setting. 548 static files copied to '/app/static', 1574 post-processed. However, when I try to go to my site, I am unable to access any static files. Additionally, if I open a shell into heroku with heroku run bash, the static directory (I have an empty static directory committed to git) is completely empty. So heroku says that it copied over the static files, but as far as I can tell- it did not. Does anyone have an ideas on how this could be happening? I am using webpack and whitenoise to serve the static files. -
App not compatible with buildpack , django heroku
Using buildpack: heroku/python but still it says not compatible Please Help i am a beginner in django Here is build log : -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed And here is the project :https://github.com/Shadow-Knight503/Meme_Site -
when i install wagtailtrans it shows error
Moving to c:\users\hp\appdata\local\programs\python\python39\lib\site-packages\pil from C:\Users\hp\AppData\Local\Programs\Python\Python39\Lib\site-packages~il Moving to c:\users\hp\appdata\local\programs\python\python39\lib\site-packages\pillow-8.3.2.dist-info from C:\Users\hp\AppData\Local\Programs\Python\Python39\Lib\site-packages~illow-8.3.2.dist-info ERROR: Command errored out with exit status 1: 'c:\users\hp\appdata\local\programs\python\python39\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\hp\AppData\Local\Temp\pip-install-r132d9vs\pillow_2201a7b052fc4b8aa3f08901eaf540e4\setup.py'"'"'; file='"'"'C:\Users\hp\AppData\Local\Temp\pip-install-r132d9vs\pillow_2201a7b052fc4b8aa3f08901eaf540e4\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(file) if os.path.exists(file) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\hp\AppData\Local\Temp\pip-record-ll058sa9\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\hp\appdata\local\programs\python\python39\Include\Pillow' Check the logs for full command output. -
Django ORM bulk create_or_update + delete not updated
class Item(Model): article = CharField owner = ForeignKey(User) price = IntegerField stock = IntegerField Hello, pls me help with bulk create_or_update_or_delete logic. I have an Items in db. Then I have a new list of items. items = (Item, Item, Item...) but without price field i want to bulk create items that already not in DB (using article and owner) with price = Null bulk update existing items(but not update price) bulk delete those items, that previously existed in db, but not updated in step 2. I know how to bulk create_or_update but idk how to add in step 3 and make all of that efficient. I cant just delete all owner's items and then bulk_create cuz I lost price data. -
Undesired/wrong URL using Django Paginator
I'm trying to use Django Paginator in my webpage but the generated URL is wrong Here is my code: <div class="row"> <div class="col-auto"> <ul class="pagination"> {% if tickets.has_previous %} <li class="page-item"><a class="page-link" href="{{current_uri}}?p=1">&lt;&lt;</a></li> <li class="page-item"><a class="page-link" href="{{current_uri}}?p={{ tickets.previous_page_number }}">&lt;</a></li> {% else %} <li class="page-item disabled"><a class="page-link" href="">&lt;&lt;</a></li> <li class="page-item disabled"><a class="page-link" href="">&lt;</a></li> {% endif %} {% for page_number in tickets.paginator.page_range|pagination_limit:tickets.number %} {% ifequal tickets.number page_number %} <li class="page-item active"><a class="page-link" href="{{current_uri}}?p={{page_number}}">{{page_number}}</a></li> {% else %} <li class="page-item"><a class="page-link" href="{{current_uri}}?p={{page_number}}">{{page_number}}</a></li> {% endifequal %} {% empty %} No pages {% endfor %} {% if tickets.has_next %} <li class="page-item"><a class="page-link" href="{{current_uri}}?p={{ tickets.next_page_number }}">&gt;</a></li> <li class="page-item"><a class="page-link" href="{{current_uri}}?p={{ tickets.paginator.num_pages }}">&gt;&gt;</a></li> {% else %} <li class="page-item disabled"><a class="page-link" href="">&gt;</a></li> <li class="page-item disabled"><a class="page-link" href="">&gt;&gt;</a></li> {% endif %} </ul> </div> <!-- .col-auto --> </div> <!-- .row --> And this is what happened: Let's say I visit my webpage, example.com and by default the pagination page is 1. If I click on page 2, I'll get this url: https://example.com/tasks/?p=2 If I click on page 3, this is the generated url: https://example.com/tasks/?p=2?p=3 Which is wrong, and it should be: https://example.com/tasks/?p=3 Also if I click back to page 1, I'm getting this url: https://example.com/tasks/?p=2?p=3?p=1 I would like to know how … -
How to assign specific groups to users on Registration in Django
I am new to Django. I am developing a school online app. I have few user groups like sectional-head, teacher, subject-leader, class-monitor, etc. I need to let the user to choose their group and assign each user to these groups at the time of registration. I don't know-how. Please help me to learn this. Thanks. This is my view. def register(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() user_group = Group.objects.get(name='group_name') user.groups.add(group) username = form.cleaned_data.get('username') messages.success(request, f'Profile details updated {username}.') return redirect ('login') else: print(form.errors) # return redirect ('login') group = Group.objects.all() context = { 'group': group, 'form':form } return render (request, 'register.html', context) this is my form from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'password1', 'password2'] My template <form method="POST" action=""> {% csrf_token %} <div class="input-group mb-3"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-user"></i></span> </div> <select name="user-group" > {% for group in group %} <option value="1">{{group.name}}</option> {% endfor %} </select> {{group.name}} </div> <div class="input-group mb-3"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-user"></i></span> </div> {{form.username}} </div> <div class="input-group mb-2"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-key"></i></span> </div> {{form.password1}} … -
<built-in function imread> returned NULL without setting an error in django views
i want to create a qr scanner in django.for that i have a model with a field call "image" and a form views.py: @login_required def scan_qr(request): if request.method == 'POST': form = QrScannerForm(request.POST,request.FILES) if form.is_valid(): scanner = form.save(commit=False) scanner.save() image = scanner.image print(scanner) print(image) img=cv2.imread(image) det=cv2.QRCodeDetector() val, pts, st_code=det.detectAndDecode(img) print(val) return HttpResponseRedirect(val) else: form = QrScannerForm() return render(request,'profile/scan_qr.html',{'form':form}) i am getting the image but the line is not working "img=cv2.imread(image)" it is throwing error " returned NULL without setting an error" how can i fix this ? -
image upload works locally, but the deployed version on heroku crashes, paartial credentials messing
i have a python/django project deployed on heroku with aws s3 image upload, I can upload the image and post them on the website locally, but the deployed version on heroku is givinig me that error PartialCredentialsError at /teams/1/add_photo Partial credentials found in env, missing: AWS_SECRET_ACCESS_KEY I have the configuration file on my computer and it works locally with both aws_Secret_id & AWS_SECRET_ACCESS_KEY any help with that?! -
Why does django cache.set() store weird characters
When I save the string via django's cache framework from django.core.cache import cache cache.set('host_cache_key_81e44325-c046-44c6-88d7-bad7cd91ec13', ""brown.example.com:8006") And try to get the value out: 127.0.0.1:6379> get :1:host_cache_key_81e44325-c046-44c6-88d7-bad7cd91ec13 "\x80\x05\x95&\x00\x00\x00\x00\x00\x00\x00\x8c\"brown.example.com:8006\x94." I get some weird characters around it, why is that and how to make it not do it?