Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to only calculate the xp earned at frist try?
So the user can take some quiz and earn xp only at first try. From the second try on I only want to calculate how many correct answer scored but not xp will be earn. My models: class ClassAttempt(models.Model): user = models.ForeignKey(to=User,on_delete= models.PROTECT, null=True) related_class = models.ForeignKey(to=Class, related_name='attempt', on_delete= models.PROTECT, null=True) collected_xp = models.IntegerField(null=True, blank=True, default=0) status = models.CharField( verbose_name='status', max_length=20, choices=( ('no-completed', 'no-completed'), ('completed', 'completed'), ), default='no-completed' ) try_num = models.IntegerField(null=True, blank=True, default=1) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class UserClassQuestionsRecord(models.Model): user = models.ForeignKey(to=User, related_name='user_class_question_record', on_delete=models.CASCADE, null=True) question = models.ForeignKey(to=ClassQuiz, related_name='question_selected', on_delete=models.PROTECT, null=True, blank=True) selected_answer = models.ForeignKey(to=QuizAnsClass, related_name='answer_selected', on_delete=models.PROTECT, null=True, blank=True) is_correct = models.CharField( verbose_name='status', max_length=10, choices=( ('True', 'True'), ('False', 'False'), ), default='' ) try_num = models.IntegerField(null=True, blank=True, default=1) xp_collected = models.IntegerField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) My View: class UserClassScore(ListAPIView): """ Get User Score at the end of each class by Class ID Get request """ queryset = ClassAttempt.objects.all() serializer_class = UserClassScoreSerializer permission_classes = [IsAuthenticated] lookup_field = 'id' def get_queryset(self): queryset = self.queryset.filter(related_class_id=self.kwargs.get('id'), try_num=1) if not queryset: self.serializer_class = UserClassScoreSerializerNoXp return queryset else: self.serializer_class = UserClassScoreSerializer return queryset My serializers : class UserClassScoreSerializer(serializers.ModelSerializer): score = serializers.SerializerMethodField() xp_collected = serializers.SerializerMethodField() def get_score(self, obj): class_data = UserClassQuestionsRecord.objects.filter(user=self.context['request'].user, question__singleclass_id=obj.related_class.id, try_num=1, … -
How to have my sitemap refreshed after a modification?
I’m using the Django sitemap framework to generate my sitemap and it is working, but I made some changes and my sitemap was not re-generated. This is my ok sitemap being generated: class StaticViewSitemap(Sitemap): protocol = "https" changefreq = "monthly" priority = 1 def items(self): return ['home'] def location(self, item): return reverse(item) <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml"> <url> <loc>https://example.io/</loc> <changefreq>monthly</changefreq> <priority>1</priority> </url> <url> <loc>https://example.io/enterprise/</loc> <changefreq>monthly</changefreq> <priority>1</priority> </url> <url> <loc>https://example.io/about/</loc> <changefreq>monthly</changefreq> <priority>1</priority> </url> <url> <loc>https://example.io/pricing/</loc> <changefreq>monthly</changefreq> <priority>1</priority> </url> <url> <loc>https://example.io/posts/</loc> <changefreq>monthly</changefreq> <priority>1</priority> </url> </urlset> However, I made some changes, I removed some links, but my sitemap is still displaying the old links. class StaticViewSitemap(Sitemap): protocol = "https" changefreq = "monthly" priority = 1 def items(self): return ['home','enterprise','about','pricing'] def location(self, item): return reverse(item) <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml"> <url> <loc>https://example.io/</loc> <changefreq>monthly</changefreq> <priority>1</priority> </url> <url> <loc>https://example.io/enterprise/</loc> <changefreq>monthly</changefreq> <priority>1</priority> </url> <url> <loc>https://example.io/about/</loc> <changefreq>monthly</changefreq> <priority>1</priority> </url> <url> <loc>https://example.io/pricing/</loc> <changefreq>monthly</changefreq> <priority>1</priority> </url> <url> <loc>https://example.io/posts/</loc> <changefreq>monthly</changefreq> <priority>1</priority> </url> </urlset> I'm trying migrate again and again to my sitemap.xml be re-generated, but this is not working. I also changed the branch and re-created, but still displays the first sitemap generation. -
show related fields in django admin panel
I have 3 django models. Requirement Model has its own fields. RequirementImage and RequirementDOc models have Requirement as foreign key in them which are used for multiple image and multiple document upload. In admin ,I want to show the Requirement along with the images and documents related to requirement. How can i show it in admin panel. I am able to show Requirement alone but i need to show the attached images and documents. Below is the exact code of models. class Requirement(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length = 5000) mobile = models.CharField(max_length=15, null=True, blank=True) email = models.EmailField(null=True, blank=True) city = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class RequirementImage(models.Model): requirement = models.ForeignKey('Requirement', on_delete=models.CASCADE) image = models.ImageField(null=True, blank=True, validators=[ FileMimeValidator() ], upload_to=settings.MEDIA_RELATIVE_ROOT + "requirements/images") class RequirementDoc(models.Model): requirement = models.ForeignKey('Requirement', on_delete=models.CASCADE) requirement_file = models.FileField(null=True, blank=True, upload_to=settings.MEDIA_RELATIVE_ROOT + "requirements/docs") Python version is 3.7.12 and django version is 3.2.14 -
Where should I include a global fixture in a django project?
I have this fixture , and I want to make it global , where should I put it in my django project @pytest.fixture def auth_client(user = None): if(user is None): user = User.objects.create() client = APIClient() client.login(username=user.username, password=user.password) return client thanks in advance. -
Encrypt Django Rest Framework API response + Decrypt response in react app
I am currently building an application. My front end is developed using React and Axios (for API call requests). It is served directly by vercel on mydomain.com My back end is developed using Django and Django Rest. It is served with apache2 on api.mydomain.com. It only serves API endpoints. So the front-end and back-end are separated. I would like to return the entire data in encrypted form as an API response and then wants to decrypt it in the frontend app(react) Do you have any idea of what I could do to achieve this? Thanks a lot in advance for your answers. -
Python dictionary simplify a bit
I have some code inside dictionary how can i simplify this a bit. template_data = { 'name': title if name is not None else None, } -
Netsuite how do I open a file in the browser (Doc, excel) without downloading
Files which are uploaded onto the system will only show in a new browser if it is an image or PDF. If it's any other file format it will automatically download the file. Is there a way around this? I have tried using SuiteScript to access the file and open it in a new browser but, it will download it once opened in a new browser. -
Getting NoReverseMatch while click the comment button
I was getting that same error while click the like button, But the error was solved.. again after creating comment view and its other staff I'm getting that error again...When I click the comment button then the error appears..I'm very new to Django,,, help me please.. My project models.py, template page, urls.py, views.py are attached herewith **models.py** from email.policy import default from django.db import models from django.contrib.auth.models import User # Create your models here. class Blog(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200, verbose_name="Put a Title") blog_content = models.TextField(verbose_name="What is on your mind") blog_image = models.ImageField(upload_to="blog_images", default = "/default.png") created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Comment(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name = "blog_comment" ) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name = "user_comment") comment = models.TextField() comment_date = models.DateField(auto_now_add=True) def __str__(self): return self.comment class Like(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name = "blog_liked") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name = "user_liked") class Unlike(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name = "blog_unliked") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name = "user_unliked") **blog_page.html** {% extends "main.html" %} {% load static %} {% load crispy_forms_tags %} {% block content %} <div style="text-align:center;"> <h2>{{blog.title}}</h2> <img src="{{blog.blog_image.url}}" alt="" width="630px" height="300px"> </div> <div style="text-align:center;"> {{blog.blog_content|linebreaks}} </div> {% if … -
How to solve Local path <path> is not registered within uploads in the request in PyCharm 2022.2.1 (Professional Edition)?
I want to set up a Django project with docker-compose and Pycharm on my PC with Ubuntu 22.04 OS. I added a python interpreter from Settings > project > Python interpreter and then add interpreter > on SSH after that entered ssh credentials and on the system interpreter finally I created the python interpreter. I have docker-compose run on another terminal. After I run the runserver command it shows this error: this is the runserver command configuration: I have recreated the interpreter, and explored the same problems on JetBrains website but couldn't solve the issue. -
cant change language using {% url 'set_language' %} in Django translation
this was actually working fine i don't know what changed or happened. suddenly {{ redirect_to }} as shown here from django documentation <input name="next" type="hidden" value="{{ redirect_to }}"> doesn't have a value when i view it from developer tools this my template code {% load i18n %} {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} <li class="mx-0 mx-lg-1"> <form action="{% url 'set_language' %}" method="post" id="lang_form" style="display: flex; margin-top: 1rem;">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select id="language_selection" onchange="ChangeLanguage(this);" class="form-control bg-primary text-white" name="language"> {% for language in languages %} <option class="text-white" value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} </option> {% endfor %} </select> </form> </li> the form is submitted using this java script code function ChangeLanguage(element){ const lang_form = document.getElementById('lang_form'); console.log(lang_form); lang_form.submit(); } and this is my main urls.py rom django.contrib import admin from django.urls import path, include from django.conf import settings #add this from django.conf.urls.static import static #add this from django.contrib.auth import views as auth_views from django.conf.urls.i18n import i18n_patterns from django.views.i18n import JavaScriptCatalog urlpatterns = [ path('admin/', admin.site.urls), path('', include('lazord.urls', namespace='lazord')), path('authentication/', include('authentication.urls', namespace='authentication')), path('booking/', include('booking.urls', namespace='booking')), path('doctors/', include('doctors.urls', namespace='doctors')), path('notifications/', include('notifications.urls', … -
unique connection lines in javascript
$('.object').draggable({ containment: "#canvas", drag: function(event,ui){ console.log("drag inside") var lines = $(this).data('lines'); //Source of line var con_item =$(this).data('connected-item'); //Destination block var con_lines = $(this).data('connected-lines'); //Destination of line if(lines) { //If you will drag source block lines.forEach(function(line,id){ $(line).attr('x1',$(this).position().left+61.9).attr('y1',$(this).position().top+102); }.bind(this)); } if(con_lines){ //If you will drag destination block con_lines.forEach(function(con_line,id){ $(con_line).attr('x2',$(this).position().left+(parseInt($(this).css('width'))/2)) .attr('y2',$(this).position().top+(parseInt($(this).css('height'))/3)+(id*5)); }.bind(this)); } var node_position = ui.position; console.log(node_position) } }); $('.object').droppable({ accept: '.connecting_button', drop: function(event,ui){ var item = ui.draggable.closest('.object'); $(this).data('connected-item',item); ui.draggable.css({top:-2,left:-2}); item.data('lines').push(item.data('line')); i want to create one to one connection between nides means one element should be connected with only one element.if new connection establish old one should be deleted -
Creating a calendar feed URL with Python
I'm trying to write a view into my Django application that an external calendar application can subscribe to. For example, in Google Calendar, you can "Add a calendar from a URL". This is what I want to create so that I can automatically add new events without my users having to download new files. As far as I can tell from other, functional URLs, the only thing such a URL needs to do is return a .ics file without having to authenticate. While I believe I've done that, Google Calendar (and other calendar applications) don't seem to be importing my feed. The interesting thing to me is that when I visit the URL in my browser, it starts downloading a .ics file right away. Even more weirdly, when I then try importing that file in Google Calendar with the Import & Export function, the application displays the events in my feed just fine. Below is an excerpt from the file that is downloaded. Its name is pre-u.ics. BEGIN:VCALENDAR VERSION:2.0 PRODID:-//UT Pre-U//Portal//NL CALSCALE:GREGORIAN METHOD:PUBLISH X-WR-CALNAME:Pre-U Agenda X-WR-TIMEZONE:Europe/Amsterdam BEGIN:VEVENT SUMMARY:Test event DTSTART;VALUE=DATE-TIME:20221104T150000Z DTSTAMP;VALUE=DATE-TIME:20221027T122423Z UID:gebeurtenis1@pre-u-portal CATEGORIES: DESCRIPTION:Test LOCATION:Unknown ORGANIZER:MAILTO:myemailaddress@gmail.com STATUS:CONFIRMED URL:https://google.com/ END:VEVENT END:VCALENDAR I generate the file with the django-ical package and the … -
how to call python function from react js
i have made a react app but now i making a sign up page but my question is how to call python function for create users. I'm trying to this. what is the next process for this?? -
Change Options Name in Django Forms
I am trying to change the name of the options in Django form, but I don't know where I change it. I was able to change it in the admin area, but in the form I can't In the form In the admin area I would like the name to be the same in the form as it is in the admin area models.py from django.db import models class Tipologia(models.Model): name = models.CharField(max_length=40) codigo = models.CharField(max_length=2, null=True) class Meta: ordering = ['codigo'] def __str__(self): return f'{self.codigo} - {self.name}' class Rubrica(models.Model): name = models.CharField(max_length=40) codigo = models.IntegerField(blank=True, null=True) tipologia = models.ForeignKey(Tipologia, on_delete=models.CASCADE) subTipo = models.CharField(max_length = 100, blank=True, null=True) codSubTipo = models.CharField(max_length = 5, blank=True, null=True) class Meta: ordering = ['tipologia'] def __str__(self): if self.codSubTipo is None: return f'{self.tipologia.codigo} - {self.name}' return f'{self.tipologia.codigo} - {self.name}, {self.codSubTipo}' class Carregamento(models.Model): #name = models.CharField(max_length=124) cliente = models.CharField(max_length=124, null=True) tipologia = models.ForeignKey(Tipologia, on_delete=models.SET_NULL, null=True) rubrica = models.ForeignKey(Rubrica, on_delete=models.SET_NULL, null=True) numOrdem = models.IntegerField(blank=True, null=True) ficheiros = models.CharField(max_length=124, blank=True, null=True) def __str__(self): return f'{self.id} - {self.cliente} | {self.tipologia.codigo} | {self.rubrica.name}' forms.py from django import forms from myapp.models import Carregamento, Rubrica class CarregamentoCreationForm(forms.ModelForm): class Meta: model = Carregamento fields = '__all__' widgets = { 'cliente': forms.TextInput(attrs={ 'class': 'form-control' … -
Restrict requests in django
So, I have a website in django, how to add restrictions that request to the website can only be made through a browser and not from terminal or scripts. I want to implement this because in my website I'm using def ip(request): a = request.META.get('HTTP_X_FORWARDED_FOR') .... -
Django PermissionDenied return error 500 instead of 403
So, in my Django 4.0 project, I have a Class-Based View that inherits UserPassesTestMixin. If the test_func returns False it throws a PermissionDenied exception which in its turn must return 403.html But instead of 403, I'm getting a 500 server error. I read in Django docs that PermissionDenied must trigger the django.views.defaults.permission_denied, but it doesn't. Please give me some advice. class PostListView(UserPassesTestMixin, HomeView, ListView): template_name = "diary/post_list.html" queryset = Post.objects.all() permission_denied_message = "Access for staff only!" def test_func(self): return self.request.user.is_staff I solved it by catching PermissionDenied exception in handle_no_permission: def handle_no_permission(self): try: return super().handle_no_permission() except PermissionDenied as e: return permission_denied(self.request, e) But it looks unnatural... -
datetime.date.today() always returns the same value
I have a Django project. I use nginx + gunicorn. The views.py file has a combined_data() function that creates and returns an HTML page. As you can see, I am passing the objects in 'rows' and the current date in 'time'. A function that returns objects looks like this The problem is that in this function, reporting_date always gets the value it got the first time it was called. For example, I do "sudo systemctl restart gunicorn" and open this page in the browser. reporting_date will be equal to today. If I open the page tomorrow, reporting_date will not change its value. Initially, I assumed that datetime.date.today () does not work correctly, so I added the 'time' parameter to views.py (first screen), but the date is always correct there. Then I thought that the default value of the parameters of the get_combined() function (second screen) is somehow cached, so I added the r_int parameter, which receives a random value, but everything works correctly here. r_int always gets a new value. Now, I have to call "sudo systemctl restart gunicorn" every day to make the page work properly (( Any ideas how to fix this problem? Thanks -
Django Rest + React + Flutter: how to restrict domain origin of requests
I am currently building a web + mobile application. My front end is developed using React and Axios (for API call requests). It is served directly by Nginx on app.mydomain.com My Mobile App is developed using the Flutter My back end is developed using Django and Django Rest. It is served with Nginx and Gunicorn on api.mydomain.com. It only serves API endpoints. So the front-end, Mobile app, and back-end are separated. I would like only my front-end (app.mydomain.com) and flutter app to be able to make API requests to my Django Rest backend. I would like to prevent any other domains, any clients such as postman, insomnia, curl, or any script to make API requests to my backend. I have already set CORS in Django Rest. However, I can still make requests to the backend using curl or any other client. Do you have any idea of what I could do to achieve this? Thanks a lot in advance for your answers. -
Display django many2many fields in different cells in xl file
I have a django model which stores the many2many field i need to display them in different cells while file is exported, let's say i have two many2many field that belongs to same record right now i am displaying them in single cell seperated by a comma, i need them to be in different cells. def get_payments_formatted(self, obj): payments = list() for i in obj.payment_data_generator(): payments.append(f'${i[0]:0,.2f}') payments = [str(payment) for payment in payments] return ", " . join(payments) -
Connect to another database and dumpdata from it in json format
My task is to populate my two existing City and Province model using two json files cities.json' and 'provinces.json. Data in these files are as below. provinces.json: [ { "model": "salesnetwork.cities", "id": "1", "name": "EA" } ] cities.json: [ { "model": "salesnetwork.cities", "id": "1", "province_id": "1", "name": "Tabriz" } ] Now I'm trying to poplulate my two models with these data. My models are as below. class Provinces(models.Model): name = models.CharField(max_length=255, db_collation="utf8mb3_unicode_ci") class Meta: db_table = "provinces" class Cities(models.Model): province = models.ForeignKey("Provinces", models.DO_NOTHING) name = models.CharField(max_length=255, db_collation="utf8mb3_unicode_ci") class Meta: db_table = "cities" (My bad for naming my model Cities instead of City and Provinces instead of 'Province'; I've created these models via inspectdb command and since I didn't know if changing these model names could cause problems or not, I decided to leave the names as they were). When I try using command py .\manage.py loaddata provinces.json I get the following error: Traceback (most recent call last): File "D:\Projects\Navid Motor\Website\Django\NavidMotor.com\.venv\lib\site-packages\django\core\serializers\json.py", line 69, in Deserializer objects = json.loads(stream_or_string) File "C:\Users\Vahid Moradi\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 335, in loads raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)", json.decoder.JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1 (char 0) The above exception was the direct … -
How to extract zip file and get files one by one in file Cabinet in Netsuite
i am using compress.gunzip is suitelet but it is not working var zipped = file.load({ id: '85515' }); log.debug("zipped", zipped); ///// file is loading here var unzipped = compress.gunzip({ file: zipped }); ///// but unzipped is getting null unzipped.folder = 31; var fileId = unzipped.save(); log.debug("fileId", fileId); Anyone please suggust me. -
My Get Api isn't working , I can't retrieve list from db as i inteded(Django)
This is the information in my db This is my model Serializers @api_view(['GET', 'POST', 'DELETE']) def student_list(request): if request.method == 'GET': student = Student.objects.all() FirstName = request.GET.get('FirstName', None) if FirstName is not None: student = student.filter(FirstName__icontains=FirstName) student_serializer = StudentSerializer(student, many=True) return JsonResponse(student_serializer.data, safe=False) elif request.method == 'POST': student_data = JSONParser().parse(request) student_serializer = StudentSerializer(data=student_data) if student_serializer.is_valid(): student_serializer.save() return JsonResponse(student_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(student_serializer.errors, status=status.HTTP_400_BAD_REQUEST) Above is my view, I have no problem with Post but when I use Get I only got a "[ ]" . I'm not sure where exactly is the mistake ... PostMan Get -
Django: HTTPResponse to JSONResponse with Traceback
I am working on a middleware where i need to convert the HTTPResponse(ex: 500 internal error) to a JSONResponse like below { "error":"some error string", "traceback":"complete traceback of exception" } Can someone please guide me how i can achieve this? -
How to filter based on friends of the logged in user?
I'm doing a leaderboard which it works when filtering from all users. But here I would like to filter based on the friends of the user. This is how I get a list of friends : users = self.request.user.friends and this is my view : class FriendsDayLeaderBoard(ListAPIView): """ List friends Leaderboard based on XP token by Day Get request """ serializer_class = UserLeaderboardSerializer queryset = UserLeaderboardTracking.objects.all() permission_classes = [IsAuthenticated] def filter_queryset(self,queryset): users = self.request.user.friends return self.queryset.filter(created_at__date=timezone.now()) \ .values('user_id', 'user', 'day_streak') \ .annotate(xp_val=Sum('xp_value')) \ .order_by('-xp_val')[:20] \ UserLeaderboardTracking keeps track of all the users in the app every time they earn xp tried to loop from a list of friends but not sure how to proceed in that direction -
Avoiding DateTime "auto_now" field to be changed when nothing actually has changed
What is the most efficient way to make sure my updated_at field- which has the auto_now param not to be changed when the object remains the same on PATCH request for example?