Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trouble sorting JSON results with django rest framework and dynamic rest
I am trying to sort my results by either date or primary key, newer entries in the database first. models.py class Notifications(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField('date transacted') read = models.BooleanField(default=False) message = models.CharField(max_length=300) views.py class getnotifications(viewsets.ModelViewSet): # Database model queryset = User.objects.all() # Serializer - this performs the actions on the queried database entry serializer_class = NotificationsSerializer # What field in database model will be used to search lookup_field = 'username' serializers.py class NotificationsSerializer(DynamicModelSerializer): notifications_set = DynamicRelationField('ListNotificationsSerializer', many=True, embed=True) class Meta: model = User fields = ['notifications_set'] class ListNotificationsSerializer(DynamicModelSerializer): class Meta: model=Notifications name='notifications_set' fields=['pk','date','read','message'] URL accessing request http://localhost:8000/pm/getnotifications/<omitted>/?sort[]=-notifications_set.pk JSON results { "notifications_set": [ { "pk": 1, "date": "2022-10-10T17:11:33.821757Z", "read": false, "message": "A user with the phone <omitted> has submitted a restock request for 5 of airpods" }, { "pk": 2, "date": "2022-10-10T00:00:00Z", "read": false, "message": "A user with the phone <omitted> has submitted a restock request for 5 of airpods" }, { "pk": 3, "date": "2022-10-10T17:25:11.824385Z", "read": false, "message": "A user with the phone <omitted> has submitted a restock request for 5 of airpods" } ], "links": { "notifications_set": "notifications_set/" } } Whether I use -notification_set.pk or notification_set.pk it displays the results in Postman the same way, … -
Temporizador cuenta regresiva para quiz , Django
Estoy buscando un temporizador ya que tengo un quiz y quisiera que al terminar el tiempo se enviara el quiz, soy nuevo en Django eh revisado algunas paginas en ellas dice que podría ser con JavaScript o Ajax, pero cuento con conocimiento muy básico sobre ello, quisiera que esta cuenta regresiva se mostrara en la pantalla para que asi puedan ver cuanto tiempo les queda antes de que se envié el examen automáticamente, les agradecería si me pudieran apoyar con este tema views: @login_required(login_url='testinglogin') @user_passes_test(is_testing) def start_exam_view(request, pk): course = QMODEL.Course.objects.get(id=pk) questions = QMODEL.Question.objects.all().filter(course=course) if request.method == 'POST': pass response = render(request, 'testing/start_exam.html', {'course': course, 'questions': questions}) response.set_cookie('course_id', course.id) return response Models: class Course(models.Model): course_name = models.CharField(max_length=50) question_number = models.PositiveIntegerField() total_marks = models.PositiveIntegerField() time = models.IntegerField(help_text="duracion de examen en minutos") profile_pic = models.ImageField(upload_to='static/profile_photo/icono/', null=True, blank=True) nivel = models.ForeignKey(Nivel, on_delete=models.CASCADE) lenguaje = models.ForeignKey(Lenguaje, on_delete=models.CASCADE) 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) html: <form class="form" autocomplete="off" onsubmit="return saveAns()" action="/testing/calculate-marks" method="POST"> {% csrf_token %} <div class="container-fluid"> <div class="col-lg-12"> … -
Not able to fetch image in django
django image fetch problem product fetch view product fetch for loop in html template product image cannot fetch from database -
How to manage multiple websites with 1 django project
Let's say I have 1 Django project where I want host multiple websites on with different domains. I managed to set it up but progressing further is where I get confused. We'll call them store1.com, store2.com I can route to both sites through a custom middleware that checks the url where the request comes from and that is working fine. Both stores have it's own apps like cart, category, product, account and so forth. What would be the best practice to structure this? Do I put everything from a store inside 1 app or is it better to have all these models and views in a separate app and keep checking the request so that the app knows which URL to serve? -
Why does adding 'User' to my Model gives me an Internal Server Error? (Django)
My Django App was working fine until I added this 'author' field to my Model: from django.db import models from django.contrib.auth.models import User class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(blank=True, null=True, max_length=280) I'm literally copying it from a article I found (from 2022), so I don't get what's wrong. This is the error the console is showing: Here's the repository -> https://github.com/mateomaza/SocialMediaProject -
Dependency installation in container fails when i add djoser to my pipfile
I'm developing project based on django rest framwork and couple of days ago i decided to add email verification. As i found out at drf's documentation, it's recommended to use djoser for it. First, i installed it locally into my virtual environment and there where no errors(i'm using pipenv as dependency manager). Then, i decided to do the same in my docker container, so i rebuilt it and came up with some crazy error logs(without djoser everything works correctly). I just have no idea what to do and how to fix it and i hope someone would help me. My Pipfile: [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] djangorestframework = "*" psycopg2-binary = "*" django-countries = "*" django = "==3.2" django-rest-swagger = "*" drf-yasg = "*" djangorestframework-simplejwt = "*" django-debug-toolbar = "==3.4.0" django-filter = "*" celery = "==5.1.2" redis = "==3.5.3" djoser = "*" [dev-packages] black = "*" [requires] python_version = "3.8" My Dockerfile: FROM python:3.8-alpine ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /app RUN python3 -m pip install --upgrade pip && pip install pipenv RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev COPY . /app/ RUN pipenv install --system --deploy And finally, my console logs … -
Problem occurs in arrays when django rest framework is form-data
django = 3.2 django rest framework = 3.12.2 When sending a one-dimensional array, the form data is passed by the parser like this: example string: arr=["car","man"] # after serializer in JavaScript arr=car arr=man If I do it in the following ways, it is not parsed; # after serializer in JavaScript arr[]=car arr[]=man or arr[0]=car arr[1]=man When I try to send a two-dimensional array, this time it accepts; arr = [["car","man"],[...]] # after serializer in JavaScript arr[0][0]=car arr[0][1]=man I want to send both one-dimensional, two-dimensional and one image file in a post data, but for this reason I cannot do it? -
Django App not reading static Javascript from <script>
Im fairly new at this and have been all through the previous answers but cant make this work. I am not getting django to read and apply my cart.js file from my base.html template. I have checked and rechecked my settings and files and just cant seem to find it. Can you help? settings.py base.html static file structure main urls.py Error from template rendering My best guess is it is somewhere in the static files settings but i just cant seem to understand where. -
How can I calculate difference of numbers in django views and send it to template ,Alish-Buy ,Satish-Sell,Mehsul-Product,Miqdar-Number,Qazanc-Earnings
enter image description here enter image description here enter image description here enter image description here enter image description here -
so i was working with session and it showed maximum recursion depth exceeded
so i was working with session and it showed maximum recursion depth exceeded . basket.py class basket(): def __init__(self,request) : self.session=request.session basket=self.session.get('skey') if 'skey' not in request.session: basket=self.session['skey']={} self.basket=basket and what does this line says-self.basket=basket context_processor.py from .Basket import basket def basket(request): return{ 'bas':basket(request) } settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR/'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'app.views.category', 'basket.context_processor.basket', ], }, }, ] error trace back PS C:\Users\hp\core> python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). October 10, 2022 - 23:22:00 Django version 4.1.1, using settings 'core.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Internal Server Error: / Traceback (most recent call last): File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\hp\core\app\views.py", line 8, in home return render(request,'home.html',{'product':products}) File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\shortcuts.py", line 24, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\backends\django.py", line 62, in render return self.template.render(context) File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 173, in render with context.bind_template(self): File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\contextlib.py", line 135, in __enter__ return next(self.gen) File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\context.py", line … -
unittests failing on import error with subdirectory `test_services` but not `test_servicess`
I have a Django app with a test directory full of test files and other test directories. If I name a subdirectory test_services, I get an import error. If I rename that same directory test_servicess (two s at the end), it passes. No other changes were made. Directory structure: user | └───tests │ │ __init__.py # empty │ │ test_something.py │ │ │ └───test_commands │ │ __init__.py # empty │ │ test_some_command.py | │ │ test_services │ │ __init__.py # empty │ │ test_some_command.py This all builds and tests pass locally. When I try to build this on CircleCI, I get an import error. Here is the stack trace: #!/bin/bash -eo pipefail source .env.test cd project python -m coverage run --source='.' manage.py test - DATADOG TRACER DIAGNOSTIC - Agent not reachable. Exception raised: [Errno 99] Cannot assign requested address Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/circleci/.pyenv/versions/3.7.14/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/circleci/.pyenv/versions/3.7.14/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/circleci/.pyenv/versions/3.7.14/lib/python3.7/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/home/circleci/.pyenv/versions/3.7.14/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/circleci/.pyenv/versions/3.7.14/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/circleci/.pyenv/versions/3.7.14/lib/python3.7/site-packages/django/core/management/commands/test.py", line 53, in handle failures = test_runner.run_tests(test_labels) File … -
Django queries for ManyToManyFields
I'm trying to make a clone of a dating app and attempting to retrieve the profiles which meet my user's condition. I've made a Profile model which is many to many with itself and a Match models which joins the 'liker' and 'likee' and adds additional fields. I'm trying to retrieve all the profiles I haven't swiped on yet. I've been able to do this with multiple database calls but want to know if there's a way of doing it with a single/fewer queries. my models look like this class Profile(models.Model): class MatchGenderChoices(models.TextChoices): FEMALE = 'FEMALE' MALE = 'MALE' ALL = 'ALL' class GenderChoices(models.TextChoices): FEMALE = 'FEMALE' MALE = 'MALE' NONBINARY = 'NONBINARY' display_name = models.CharField(max_length=30, null=True) age = models.IntegerField(null=True, blank=False) gender = models.CharField(max_length=10, choices = GenderChoices.choices, null = True, blank = False) user = models.OneToOneField(User, on_delete=models.CASCADE) liked_profiles = models.ManyToManyField('self', through= 'Match') match_distance = models.IntegerField(default = 30) match_age_max = models.IntegerField(default = 99) match_age_min = models.IntegerField(default = 18) match_gender = models.CharField(max_length=10, choices = MatchGenderChoices.choices, null = True, blank = False) city = models.CharField(max_length=30, null=True) latitude = models.DecimalField(max_digits=10, decimal_places=6, null = True) longitude = models.DecimalField(max_digits=10, decimal_places=6, null = True) age = models.IntegerField(null=True, blank=False,validators=[MinValueValidator(MIN_AGE), MaxValueValidator(MAX_AGE)]) bio = models.TextField(max_length=5000, default = "Add a bio", … -
Share moving object in django video call using webRTC
I create a multi peer video chat using Django and WebRTC. I'm able to share the entire screen but I want to share only some object on the partecipants' screens. I have a separate python script made with pygame that create a GUI in which there are moving objects (in my case is simply a ball moving from left to right at different speed). What do you suggest me to share only the pygame moving objects on the participants screens instead of the entire screen? Thank you -
django : Save Buffer in FileField
there is my code I need to save file received from an express(nodejs) server in django file field format Django==2.0 class DoctorFileUpload(views.APIView): permission_classes = (AllowAny, ) def post(self, request, *args, **kwargs): fileFromRequest = request.data['doctorfile'] newFile = dict() newFile['format'] = fileFromRequest['mimetype'] newFile['doctor'] = request.userprofile.doctoraccount.id newFile['file'] = ContentFile( fileFromRequest['buffer'], name=fileFromRequest['originalname']) doctorfile_srz = DoctorFileSrz(data=newFile) if doctorfile_srz.is_valid(): doctorfile_srz.save() return toolsViews.ResponseHandler( status.HTTP_202_ACCEPTED, { 'doctorfile': doctorfile_srz.data } ) else: return toolsViews.ResponseHandler( status.HTTP_400_BAD_REQUEST, {}, errors=doctorfile_srz.errors ) I need to save a file in a FileField Django Model, there is the request : { doctorfile: { fieldname: 'file', originalname: 'Capture d’écran 2022-10-06 à 10.33.56.png', encoding: '7bit', mimetype: 'image/png', buffer: { type: 'Buffer', data: [Array] }, size: 134774 }, category: 'OT' } I don't know how to do, i checked documentation but i didn't find the solution... Do i need to convert to b64 format or other format before saving? here is the error when i tried the code : TypeError: a bytes-like object is required, not 'dict' -
How to get data from template to javascript file in django
I am just suffering to search that how could I transfer the product id from the template to a javascript file using the Django framework. -
Use multiple databases from different servers in one query (Django)
I need to write one query that joins multiple tables from two different servers / databases in Django. What would be the best way to approach this? -
'list' object has no attribute 'get' when tryiing to extract text from image in pdf
I am using the django framework. And I have a method for reading content of a file in textarea. I am using the module wand.image So it works with extension .txt. But now I also want to have it work with extension .pdf. So I try it like this: class ReadingFile(View): def get(self, request): form = ProfileForm() return render(request, "main/create_profile.html", { "form": form }) def post(self, request): submitted_form = ProfileForm(request.POST, request.FILES) content = '' if submitted_form.is_valid(): uploadfile = UploadFile(image=request.FILES["upload_file"]) name_of_file = str(request.FILES['upload_file']) uploadfile.save() print('path of the file is:::', uploadfile.image.name) #path_to_file = uploadfile.upload_file.path #request.session['text'] = name_of_file(filetosave.file.path) with open(os.path.join(settings.MEDIA_ROOT, f"{uploadfile.image}"), 'r') as f: print("Now its type is ", type(name_of_file)) print(uploadfile.image.path) # reading PDF file if name_of_file.endswith('.pdf'): pdfFile = wi(filename= uploadfile.image.path , resolution=300) text_factuur_verdi = [] image = pdfFile.convert('jpeg') imageBlobs = [] for img in image.sequence: imgPage = wi(image=img) imageBlobs.append(imgPage.make_blob('jpeg')) for imgBlob in imageBlobs: image = Image.open(io.BytesIO(imgBlob)) text = pytesseract.image_to_string(image, lang='eng') text_factuur_verdi.append(text) return text_factuur_verdi # ENDING Reading pdf file else: content = f.read() print(content) return render(request, "main/create_profile.html", { 'form': ProfileForm(), "content": content }) return render(request, "main/create_profile.html", { "form": submitted_form, }) and the html looks like this: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> … -
How to use a serializer for different fields
I am working on a project of blog application in Django Rest Framework. But here I am facing some trouble. At first checkout my code then I will explain the question. Here is the model.py class Contact(models.Model): id_no = models.AutoField(primary_key=True, unique=True) email = models.EmailField() name = models.CharField(max_length=1000) subject = models.CharField(max_length=1000) description = models.TextField() And here is the serializer.py class AddContactSerializer(serializers.ModelSerializer): class Meta: model = Contact fields = '__all__' Now in a view function I want to use only email and name field of the Contact model and in another view function I want to use name and description field of that model. Can I use the same serializer class for different cases? Please help me. -
How do I import in django_cities_light?
I noticed I could not find Newport, Oregon in my django_cities_light django application. It is a small city with population slightly above 10k, so I downloaded cities1000.zip which contains cities with a population higher than 1k. I unzipped this file and started searching for Newport's id and indeed it is there: 5742750 Newport Newport N'juport,Newport (Oregon),Njuport,ONP,nyupoteu,nyupoto,nywbwrt,nywpwrt awrgn,Њупорт,Ньюпорт,Нюпорт,نيوبورت,نیوپورت، اورگن,نیوپورٹ، اوریگون,ニューポート,뉴포트 44.63678 -124.05345 P PPLA2 US OR ... Now, I have in my myapp/settings/development.py the following: CITIES_LIGHT_TRANSLATION_LANGUAGES = ['en'] CITIES_LIGHT_INCLUDE_CITY_TYPES = ['PPL', 'PPLA', 'PPLA2', 'PPLA3', 'PPLA4', 'PPLC', 'PPLF', 'PPLG', 'PPLL', 'PPLR', 'PPLS', 'STLMT',] CITIES_LIGHT_APP_NAME = 'jobs' CITIES_LIGHT_CITY_SOURCES = ['http://download.geonames.org/export/dump/cities1000.zip'] # <-- this added as part of this task I added CITIES_LIGHT_CITY_SOURCES following this post and the information here. I then tried to import from using the following command, which I understand downloads the cities1000 file specified in myapp.settings.development: python manage.py cities_light --settings=myapp.settings.development --force-all --progress Newport, Oregon, with id 5742750 is not found in my database. I also cannot see from the command that my settings file is used and that the value of CITIES_LIGHT_CITY_SOURCES is overridden properly. Does anyone know what I'm doing wrong and how to properly add from the source files? Thx! -
How to show hidden div that have data on edit page in Django forms
Iam trying to display an hidden div that have data, on the edit page using javascript in Django forms. This is the script const checkbox = document.getElementById('commute_id'); const box = document.getElementById('box'); checkbox.addEventListener('click', function handleClick() { if (checkbox. Checked) { box.style.display = 'block'; } else { box.style.display = 'none'; } }); </script> Checkbox code <div class="ui_kit_checkbox"> <div class="df mb20"> <span> {{form.commute_check|as_crispy_field }} </span> </div> </div> commute_check = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'id':'commute_id'})) Div to show and hide <div class="commute" ID="box" style="display:none" > <div class="mb20" STYLE=" display:inline-flex !important;" > <span style="padding-right:10px;"> {{ form.mon|as_crispy_field }} </span> </div> </div> This works when clicking the checkbox and adding data for the first time. But when in the edit page the check box is ticked but the div is hidden Need help. Please share if nay have better idea for this scenario. -
Using Django template together with React
Is it possible to use Django template together with React? If so, how should I do that? -
I'm trying to create user specific access to my todolist website with Django
I'm getting an error when I make migrations in the command line. Please help -models.py from django.db import models from django.contrib.auth.models import User class ToDoList(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="todolist", null=True) name = models.CharField(max_length=200) def __str__(self): return self.name class Item(models.Model): todolist = models.ForeignKey(ToDoList, on_delete=models.CASCADE) text = models.CharField(max_length=300) complete = models.BooleanField() def __str__(self): return self.text When I tried to make migrations in the command line, I got this error cmd-pic I used this command: python manage.py makemigrations python manage.py migrate I used the tutorial from TechWithTim(link: https://www.youtube.com/watch?v=sm1mokevMWk&t=7589s) to do this project. It works fine for him but not for me. Someone, please tell me where I went wrong. -
start primary key by 1001 in Django model, auto_increment gives error
Please describe how to start the primary key by 1001 in the Django model(database). I found some examples with auto_increment, but it gives me errors of undefined. Inside the project, we have to alter fields using migrations. So, Please notice that It does not affect our previous data. The database key must increment by 1 when we add another field or row. Thanks -
HttpResponseRedirect working properly but not redirecting to the next page, how can I solve that problem?
Currently I am building a resume builder website, but the problem is I can't redirect the user to the next page, it surely has problem with frontend, because backend worked properly and as I expected, because as you see the code down below, before the httpresponseredirect() method, it printed what I want, but it did not redirect the page to the next... This is not my first time question I gave this question before as well. I approached to the solution after my first time question, but now again problem, then I thought asking from stackoverflow was good idea! {% load static %} <!DOCTYPE html> <html style="font-size: 16px;" lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta charset="utf-8"> <meta name="keywords" content="Let&amp;apos;s start with&nbsp;personal information"> <meta name="description" content=""> <title>Page 1</title> <link rel="stylesheet" href="{% static 'css/nicepage.css' %}" media="screen"> <link rel="stylesheet" href="{% static 'css/Page-1.css' %}" media="screen"> <script class="u-script" type="text/javascript" src="{% static 'js/jquery.js' %}" defer=""></script> <script class="u-script" type="text/javascript" src="{% static 'js/nicepage.js' %}" defer=""></script> <meta name="generator" content="Nicepage 4.18.5, nicepage.com"> <link id="u-theme-google-font" rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:100,100i,300,300i,400,400i,500,500i,700,700i,900,900i|Open+Sans:300,300i,400,400i,500,500i,600,600i,700,700i,800,800i"> <script type="application/ld+json">{ "@context": "http://schema.org", "@type": "Organization", "name": "", "logo": "images/Untitled1.png", "sameAs": [ "https://facebook.com/name", "https://twitter.com/name", "https://instagram.com/name" ] }</script> <meta name="theme-color" content="#478ac9"> <meta name="twitter:site" content="@"> <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:title" content="Page 1"> <meta name="twitter:description" content=""> <meta … -
Are django rest framework tokens safe
I'm using Django Rest Framework Token authentication. After logging in, the frontend saves the token as a cookie and sends it via the authorization header with every request. If an attacker could get a hold of the cookie that contains the token and sends it themselves, it would be impossible to detect whether the original user or an attacker sent the token, right? If so, what would be the best way to prevent a token from being compromised and used in a malicious manner?