Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
How to use vuei18n-po?
i can't find a tutorial how to use package vuei18n-po in vue main.ts. Yts documentation is small, and not well descriped. https://www.npmjs.com/package/vuei18n-po. I have never use something like this inside app initiation in vue, so it is realy hard. it is my code: import { createApp } from "vue"; import App from "./App.vue"; import router from "./router"; import "jquery"; import "bootstrap"; import "bootstrap/dist/css/bootstrap.min.css"; import vuei18nPo from "vuei18n-po"; const app = createApp(App); await vuei18nPo({ po: ["django.po", "../../backend/locale/pl/LC_MESSAGES/django.po"], messagesFile: "generated/allInOne.json", messagesDir: "generated", }); app.use(router); app.mount("#app"); In my code i did not use plug it in option, because i wanted to generate it first. -
django.core.exceptions.ImproperlyConfigured: The module in NAME could not be imported: validators.NumberValidators
is there anyone who knows how to solve this error. I was trying add custom password validators in AUTH_PASSWORD_VALIDATORS. i got this following error. django.core.exceptions.ImproperlyConfigured: The module in NAME could not be imported: accounts.validators.NumberValidators. Check your AUTH_PASSWORD_VALIDATORS setting. here's what i did to add the custom NumberValidators AUTH_PASSWORD_VALIDATORS = [{ 'NAME': 'accounts.validators.NumberValidators', }, ] -
Adding CDN link to static folder of django
How can I add the cdn link for chart.js in html page to static folder so that I wont be dependent on cloudflare and I can cache it in my CloudFront distribution as well. can anyone help me on that. -
model object not saved in celery task
im trying to create Alarm object in celery task. but after calling task method, objects created in celery task is not saved. from celery import shared_task from alarms.models import Alarm from games.models import Participation @shared_task def create_alarms(game_id): participations = Participation.objects.filter(game=game_id) for participation in participations: alarm, created = Alarm.objects.get_or_create( game=participation.game, user=participation.user, valid_until=participation.game.start_datetime ) if not created: alarm.set_unsent() project/games/tasks.py from django.dispatch import receiver from django.db.models.signals import post_save, post_delete from .models import Participation, Game from .tasks import create_alarms, delete_alarm @receiver(post_save, sender=Participation) def _post_save_receiver(sender, instance, created, **kwargs): if created: game = instance.game game.increase_player() if game.is_fulfilled(): create_alarms.delay(game.id) project/games/signals.py - receiver method calling task method from __future__ import absolute_import unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings.dev') app = Celery('project', broker='amqp://miti:miti@localhost/', include=['games.tasks']) app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() project/project/celery.py [2022-10-27 16:12:11,543: INFO/MainProcess] Task games.tasks.create_alarms[b8782685-3fd3-4a39-8d58-8fdb9df1871e] received celery log telling task is received by celery worker please help me i want to save created object in celery task is applied into django db(currently using mysql) -
How to add proxy api request in react using nodejs? (using one general function only instead of a seperate func for each api)
I am hitting all of my django apis directly from react, what i want to do is to add a proxy nodejs layer so to hide the actual api. Our react application is haivng ssr so we are already running a nodejs server. As we are already having a lot of apis, is there a way by which i can create a single function to hide all the api instead of create proxy apis for all django apis one-by-one? -
form.label is not showing in django
this is my code and I try to show the label but it is not displaying this is my form file forms.py class ReviewForm(ModelForm): class Meta: model = Review fields = ['value', 'body'] labels = {'value': 'Place your vote', 'body': 'Add a comment with your vote'} def __init__(self, *args, **kwargs): super(ReviewForm, self).__init__(*args, **kwargs) for name, field in self.fields.items(): field.widget.attrs.update({'class': 'input'}) this is my views file and the function for this form views.py def project(request, pk): projectObj = Project.objects.get(id=pk) form = ReviewForm() context = { 'project': projectObj, 'form': form } return render(request, 'projects/single-project.html', context) this is the model for the review section models.py class Review(models.Model): VOTE_TYPE = ( ('up', 'Up Vote'), ('down', 'Down Vote') ) owner = models.ForeignKey(Profile, on_delete = models.CASCADE, null=True) project = models.ForeignKey(Project, on_delete=models.CASCADE) body = models.TextField(null=True, blank=True) value = models.CharField(max_length=200, choices=VOTE_TYPE) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default = uuid.uuid4, unique=True, primary_key=True, editable=False) class Meta: # every user can only have single comment on each project unique_together = [['owner', 'project']] def __str__(self): return self.value and the html file to display the form html file <form class="form" action="{% url 'project' project.owner.id %}" method="POST"> {% csrf_token %} {% for field in form %} <div class="form__field"> <label for="formInput#textarea">{{field.label}}</label> {{field}} </div> {% endfor … -
Python - Django Rest Framework - Count total row from tables in the database with a single call
I just switched to python and Django-rest-framework from java spring-boot, and I have a question below Let's say I have some tables: class table1(CommonModel): class table2(CommonModel): class table3(CommonModel): class table4(CommonModel): .... And I have an API to return total rows in these tables: { "table1": 10, "table2": 10, "table3": 10, "table4": 10, .... } My code so far is to count the total on each table with Model.objects.all().count() or Model.objects.filter(some_filter).count() And the problem here is obvious, if I have 10 tables, I will have to call 10 count query, which I think is not a good way to go because it spams too many queries to the database. I want to limit the number of the query to the database. The best would be to return all rows count for each table in a single query. I have looking for a solution like creating a custom query or so but nothing seems to solve my issue. Edit: I'm using Postgresql database -
django set initial value in form
class UserEditFormView(FormView): template_name = "edit.html" form_class = UserEditForm def get_initial(self): return {'nickname': self.request.user.nickname} class UserEditForm(forms.Form): nickname = forms.CharField(required=False, max_length=120) I tried to set initial value(placeholder) of the form but it's not working. The input field on the page is empty. -
i have created models and my views function to add the attendance of employee. But data data is not saving in database. and no error comes up
class AttendanceForm(forms.ModelForm): class Meta: model = Attendance fields = '__all__' These are he models and please let me know if nay changes are required : Models: class Employee(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) eid = models.IntegerField(primary_key=True) salary = models.IntegerField() gender = models.CharField(max_length=6, choices=GENDER_CHOICES, default=1) contactno = models.CharField(max_length=10) email = models.CharField(max_length=30) country = models.CharField(max_length=30) city = models.CharField(max_length=20) pincode = models.IntegerField() address = models.CharField(max_length=60) def __str__(self): return self.user.first_name + ' ' + self.user.last_name class Attendance(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, default=1) attendancedate = models.DateField() in_time = models.TimeField() out_time = models.TimeField() description = models.TextField() def __str__(self): return str(self.employee) These is the Views . Please let me know if any changes is required @csrf_exempt def addattendance(request): form = AttendanceForm() emp_list = Employee.objects.all() if request.method == 'POST': form = AttendanceForm(request.POST) if form.is_valid(): form.save(commit=True) return redirect('employee/detail_attendance') return render(request, 'employee/addattendance.html', {'form': form, 'emp_list': emp_list}) I tried everything but i dont know why data is not saving into database . also models are created fine and main thing is there is not error coming up.