Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Javascript plugin: if an inline formsets has no initial forms, I cannot add others
I'm using the following scritp to perform my inline formset: django-dynamic-formset If I try to use this plugin to add a new inline formset where there were none(the parent had no children) the buttons won't even show up. If I set an extra of 1 the buttons show up. How could I overcome this problem? This one my inlineformset_factory: RicaviFormSet = inlineformset_factory( Informazioni_Generali, Ricavi, form=RicaviForm, fields="__all__", can_delete=True, extra=1 ) -
Django/Postgres - column does not exist error after I made a right mess of the database
After a string of silly errors which invovled me directly importing data into a PostgreS DB then deleting the database after it caused duplicate key issues, I get an error (full traceback below) on makemigrations/migrate/runserver. I shifted back to SQLite and it works fine, however I need to get this running in PG. I have restored the database so the table structure is correct, however, I still get the same error so I'm presuming (guessing) there is some cached sql code on the Django/Python side that is causing this to fail. Note that lead_auditor_id is not referenced anywhere in my project, although there is a lead_auditor table which has the default id column. Any clues would be very welcome after a lot of hours spent searching and trying various solutions. $ py manage.py makemigrations Traceback (most recent call last): File "C:\Users\Jon\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column actionlog_action.lead_auditor_id does not exist LINE 1: ..."."action", "actionlog_action"."action_owner_id", "actionlog... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Jon\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Jon\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line … -
How to Insert data by using PUT?
I created my backend in Django so it registers users. I am trying to call my rest API from Django by http://localhost:8000/api/registerUsers You called this URL via PUT, but the URL doesn't end in a slash It seems like I needed a slash so I tried this: http://localhost:8000/api/registerUsers/ And I get an error: PUT /api/registerUsers/ HTTP/1.1" 405 40 It is weird since I am able to update my database by running a request like this: http://localhost:8000/api/registerUsers/2/ I thought that the PUT request both updates and create a "user". If I'm wrong How do I modify my code so that it encrypts the password for only the POST since I want to insert my user data. My code : Seralizer.py # Users Seralizer class UsersSerializer(serializers.ModelSerializer): def update(self, instance, validatedData): # get the password and hash it password = validatedData.get("password", instance.password) hash_password = make_password(password) instance.username = validatedData.get("username", instance.username) instance.email = validatedData.get("email", instance.email) instance.password = hash_password instance.save() return instance class Meta: model = Users fields = '__all__' Views.py #Users Viewset class UsersViewSet(viewsets.ModelViewSet): queryset = Users.objects.all() serializer_class = UsersSerializer Right now, my code only encrpyts the password when I use PUT. How do I encrpyt my password when i use POST? Thank you -
How to benchmark resources consumed by a Django application?
How to monitor resource consumption of a Django application for the backend server only, that is the resource consumption for each request and response cycle. -
Problems with larger file upload in Django admin
In my model I have to file fields: video_file_for_proc = models.FileField(upload_to=get_video_upload_path) video_file = models.FileField(upload_to=get_video_upload_path) The videos I upload are about 20MB, so 40 in summ. When I save my standard admin form it tries tries and then I get "The connection was reset" in browser. No errors in debug console :( . I played around changing DATA_UPLOAD_MAX_MEMORY_SIZE and FILE_UPLOAD_MAX_MEMORY_SIZE, but that did not help. When I experiment with smaller files (some random txt) it works. How can I fix this? -
Django rest framework simple-jwt error "detail": "No active account found with the given credentials"
I created a custom user model in Django and am using djangorestframework simplejwt for the authentication (login and signup). models: class UserAccountManager(BaseUserManager): def create_user(self, email, name, password=None): if not email: raise ValueError('Users must have unique email address') email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) user.save() return user def create_superuser(self, email, name, password): user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save() return user class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def get_full_name(self): return self.name def get_short_name(self): return self.name def __str__(self): return self.email I can signup just fine but when I try to login (using postman for this), it shows the following message: { "detail": "No active account found with the given credentials" } all my credentials were accurate and I have checked through the python shell that my users are all active. What am I doing wrong? -
Access Django variable from JavaScript variable
First of all, I will like to say this is my first question here! (pardon me if this is redundant or duplicated) I am having some problems with calling JS scripts from Django template: {% for suggestion in suggestions %} <img class="catalogue-poster" src="{{ suggestion.poster }}" alt="Portada" onclick=" document.getElementById('{{form.title.auto_id}}').value = '{{suggestion.title}}' document.getElementById('{{form.year.auto_id}}').value = '{{suggestion.year}}' document.getElementById('{{form.director.auto_id}}').value = '{{suggestion.director}}' document.getElementById('{{form.rating.auto_id}}').value = '{{suggestion.rating}}' document.getElementById('{{form.poster.auto_id}}').value = '{{suggestion.poster}}' document.getElementById('{{form.trailer.auto_id}}').value = '{{suggestion.trailer}}' document.getElementById('{{form.synopsis.auto_id}}').value = '{{suggestion.synopsis}}' document.getElementById('{{form.cast.auto_id}}').value = '{{suggestion.cast}}' " /> {% endfor %} So, first of all, how can I declare a function outside. I'm a C developer, sorry for my ignorance. I've tried to create a script outside, such as <script> function foo() { console.log('Hey'); }); </script> And invoke it this way: <img class="catalogue-poster" src="{{ suggestion.poster }}" alt="Portada" onclick="foo()"/> But this simple thing that works on pure HTML, with django templates does not seem to work... On the other hand, the real question was, is there a way to access a Django variable passed in render with a js variable? Such as: const jsVariable = 'title'; document.getElementById('{{form.jsVariable.auto_id}}').value = '{{suggestion.jsVariable}}' I have not found any way to accomplish this, maybe there is another great idea! -
Unable to uninstall django
I installed django using the command sudo apt install python3-django when i try to uninstall it using sudo pip3 uninstall Django it gives me the error Found existing installation: Django 2.2.12 Not uninstalling django at /usr/lib/python3/dist-packages, outside environment /usr Can't uninstall 'Django'. No files were found to uninstall. How can i uninstall it? -
static file are not working in django nginx
I have created one small app, and uploaded to the aws server, i can see everything is working except static folder, my static folder is under the /home/ubuntu/django-bhuriyo/mysite/ this directory, i am using nginx, i have put my code of nginx conf and settings.py, can anyone please look my code and help me to resolve this issue ? django.conf server { listen 80; server_name ****.amazonaws.com; location /static { alias /home/ubuntu/django-bhuriyo/mysite; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/django-bhuriyo/app.sock; } } settings.py STATIC_URL = 'static' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) STATIC_ROOT = '/home/ubuntu/django-bhuriyo/mysite' -
Django - How to combine select_related and prefetch_related to reduce the number of queries
I would like to generate a json which is the aggregation of data from several tables linked together (OneToOne and ManyToMany relationships). models.py Team(models.Model): staff = models.OneToOneField(Staff, on_delete=models.CASCADE, related_name='team_staff') function = models.CharField() Staff(models.Model): firstname = models.CharField() lastname = models.CharField() courses = models.ManyToManyField(Course, related_name='staff_course’) Course(models.models): name = models.CharField() begin= models.DateField() end = models.DateField() def __str__(self): return '%s - %s' % (self.name, self.begin, self.end) views.py def all_team(request): team_query = Team.objects.all().select_related('staff') team_list = [] for person in team_query: courses = Staff.objects.get(id=person.staff.id).courses.order_by('-begin') team_list.append({'fields': {'id': obj.id, 'function': person.function, 'firstname': person.staff.firstname, 'lastname': person.staff.lastname, 'last_course': str(courses.first()), }}) json_data = json.dumps(team_list, cls=DjangoJSONEncoder) return HttpResponse(json_data, content_type='application/json') As you can see, this is not very efficient. For each member of the team, you make a query to get the last course taken. Can we add something like : staff_query = Staff.objects.all().prefetch_related(Prefetch('courses', queryset=Course.objects.only('name').all())) and merge / combine it with the team_query. Thank you in advance for your advice -
Convert SQL query into Django ORM
I have SQL query, I need to use in Django with ORM technique. SELECT a.id, a.amount, SUM(b.amount) FROM cashflow_statement a, cashflow_statement b WHERE b.id <= a.id GROUP BY a.id ORDER BY a.id -
TypeError: Object of type method is not JSON serializable
when i click on like button then I get internal server error in console. the main problem in return view function . how to return value in HttpResponse so that i can access in javascripts console error: jquery.js:9837 POST http://127.0.0.1:8000/blogs/post/like/ 500 (Internal Server Error) views : class PostLikeView(generic.View): def post(self, request, *args, **kwargs): user = request.user post_id = request.POST['post_id'] post = Post.objects.get(id=post_id) user_liked, created = PostLike.objects.get_or_create(post=post, user=user) if not created: PostLike.objects.filter(post=post).filter(user=user).delete() total = post.like.count data = {'total-like':total,'user_liked':False} else : total = post.like.count data = {'total-like':total,'user_liked':True} return HttpResponse(json.dumps(data), content_type='application/json') javaScripts : <script type="text/javascript"> $('.likebutton').click(function(){ var id; id = $(this).attr("data-catid"); $.ajax( { type:"POST", url: "blogs/post/like/", data:{ csrfmiddlewaretoken: "{{ csrf_token }}", post_id: id }, dataType: 'json', }); //(function(data){ //data = JSON.parse(data) //console.log(data) // }); }); </script> errors get in terminal : Internal Server Error: /blogs/post/like/ Traceback (most recent call last): File "C:\publish\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\publish\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\publish\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\publish\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\publish\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "C:\publish\studentcollegeworld\blogs\views.py", line 114, in post return HttpResponse(json.dumps(data), content_type='application/json') File "c:\users\abc\appdata\local\programs\python\python38\lib\json\__init__.py", line 231, … -
Permission denied: '/root/.invoke.yaml' while running django app in docker
I have a django app which I am running inside a docker. The app works in my development VM. But I am getting permission denied error while using a function which uses python fabric. [Errno 13] Permission denied: '/root/.invoke.yaml' Nginx and Gunicorn is running with "www-data" user. So why is invoke trying for root? -
order_by based on condition
I have a queryset of assignment modules. i want to order the query set based on custom conditions. My view: class ListAssignmentsAsStudent(generics.ListAPIView): serializer_class = AssignmentModuleSerializer def get_queryset(self): my_enrolments = UserEnrolment.objects.filter( user=self.request.user).values_list('enrolment') my_enrolment_enrollables = Enrollable.objects.filter( enrolment__in=my_enrolments) assignment_modules = [] for enrollable in my_enrolment_enrollables: assignment_modules.extend(enrollable.course_share_item.modules.instance_of( AssignmentModule)) return assignment_modules All "UserEnrolment"s have a completion_status. "AssignmentModule"s have a due date DateTimeField field .I want to order the Queryset in this order. Assignments not submitted and due date already passed will be in overdue and these should come first. Assignments not submitted should come in order of due dates , earliest should come first. Assignments with UserEnrolment completion_status as COMPLETED should come with least priority .These will be the last in the list. After the ordering assignments will be in this order. Overdue>not submitted with due dates earliest first> submitted assignments -
SRID issues with GeoDjango on MySQL 8
GeoDjango is not respecting SRIDs with MySQL 8. I created a new column geo_code = PointField(srid=4326) and ran makemigrations. Running sqlmigrate on the generated migration gives BEGIN; -- -- Create model Location -- CREATE TABLE `locations_location` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `geo_code` POINT NOT NULL); CREATE SPATIAL INDEX `locations_location_geo_code_id` ON `locations_location`(`geo_code`); COMMIT; See how the SRID was ignored. Now anything I add to this column is using SRID 0 - which is incorrect. I get wrong results if I use the ST_DISTANCE function with SRID 0. I tried using migrations.SeparateDatabaseAndState to create the column with the correct SRID constraint with the following SQL ALTER TABLE backend_userprofile ADD COLUMN geocode_point POINT NULL SRID 4326; Now if I try inserting data into this column I get the following error django.db.utils.OperationalError: (3643, "The SRID of the geometry does not match the SRID of the column 'geocode_point'. The SRID of the geometry is 0, but the SRID of the column is 4326. Consider changing the SRID of the geometry or the SRID property of the column.") Django is still trying to insert data with SRID 0 and MySQL raises and error because the column has a constrain on SRID. Is there a … -
Original exception text was: 'Queryset' object has no attribute 'poslovnipartneri'
class RacuniizlaznifinancijskiSerializers(serializers.ModelSerializer): poslovnipartneri = PoslovnipartneriSerializers(many=True) class Meta: model = Racuniizlaznifinancijski fields = ["poslovnipartneri", "kupacid"] def create(self, validated_data): poslovnipartneri_data = validated_data.pop('poslovnipartneri') izlazniracuni = Racuniizlaznifinancijski.objects.create( **validated_data) for poslovnipartner_data in poslovniparnteri_data: Poslovnipartneri.objects.create( izlazniracuni=izlazniracuni, **poslovnipartner_data) return izlazniracuni I want to "join" two models and this is my try. I was doing this exactly like it was done on DRF official website. An error that I'm getting is in the title of this post. -
Angular make Url match well with Django for Shop filter
Currently I'm working on a Django-Angular application. The app is supposed to be a Shop for clothing. Now I have set up filters in Django, so that I can filter against multiple properties (color, category, product type, price...). django_filters is using the following Url to filter the query: for example to present all blue shoes for men http://localhost:8000/articles/?size=&category=Schuhe&color=Blue&gender=Herren&product_type=&price_min=&price_max=&sale=&search=&brand= (yes I know the names are mixed german and english, will be fixed soon) This works fine, the Django backend returns the right query. However this urlpattern isnt that fancy and not the best for SEO. So instead of using the same URL pattern for my Angular app and just make a Httprequest to Django with this url I decided something different. I wanted a Url looking like the following for the same example as above: http://localhost:8000/Herren%7CSchuhe%7CBlue?page=1 (%7C encoded is " | ") Mulitple choices for the same tag would be seperated by commmas. I managed to write a function in Angular to convert the Angular urlpattern into the Django urlpattern, to make the right Httprequest. getArticles(paramfilter: Filter | string) { this.ViewPage = this.dataService.list(paramfilter) } setUrlString(url: string, ) { // splittetUrl is an array of the Urlsegments var gender = ["array with … -
Django: How to change the model field display in admin site
I hope the title is enough to know what my problem. i have this code in my models Courses = models.ForeignKey(Course, on_delete=models.CASCADE, null=True, blank=True) and this what it looks like in admin site How do i change the display field name in my admin site, Course to Track without changing the field name in my models? -
Uploading slides and posting into database in Django
This is my view part for uploading the slides. def uploadSlides(request): if request.method == 'POST': if request.POST.get('Topic') and request.POST.get('week') and request.POST.get('lectureSlide') and request.POST.get('Subject'): post = Slide() post.Topic = request.POST.get('Topic') post.week = request.POST.get('week') post.lectureSlide = request.POST.get('lectureSlide') post.Subject = request.POST.get('Subject') post.save() return redirect('viewlectureslides') This is the view part for viewing the slides. def viewDSSlides(request): contents = Slide.objects.all() subject = Slide.Subject if subject == 'Software Engineering' and Slide.Subject == 'Software Engineering''AI' and Slide.Subject == 'Big Data''AI': print("Please select Subject") else: return render(request,'DS slides.html',{'contents':contents}) This is the template for uploading the slide. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Lecture slide</title> </head> <body> <form action="{% url 'uploadSlides' %}" method="post"> {% csrf_token %} Topic: <input type="text" name="Topic"> week: <input type="number" name="week"> <input type="file" name="lectureSlide" value="lectureSlide" id="lectureSlide"> <select name="Subject"> <option value="Data structure">Data structure</option> <option value="Software Engineering">Software E</option> <option value="AI">AI</option> <option value="Big Data">Big Data</option> </select> <input type="Submit" value="Post"> </body> </html> This is the template for viewing the slide <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Datas Structure</title> </head> <body> <h1> Data structure slides </h1> {% for content in contents %} {% if content.Subject == 'Data structure' %} <div class="Topic"> <h4> Topic: {{content.Topic}} </h4> </div> <div class="week"> Week: {{content.week}} </div> <div class="slides"> Slide: {{content.lectureSlide}} </div> {% endif %} … -
How to connect a signal to an instance method
I'm trying to use Signals to trigger a class instance method. The same setup that I have is already working with a simple function instead of the instance method, so my question is only related to using signals with classes. In ready method of my app config I'm doing the following class ConsoleConfig(AppConfig): name = 'console' def ready(self): from .test import testClass from .signals import my_signal test = testClass('first test') mysignal.connect(test.handle_signal) in signals.py I'm defining my signal like this: mysignal = Signal() And I'm triggering the signal from the save() function of one of the models: ... from console.signals import mysignal ... class BitmexTrade(models.Model): def save(self, *args, **kwargs): ... if condition: mysignal.send(sender='test') super().save(*args, **kwargs) And the most important part is the class and the receiver function: class testClass(object): def __init__(self, name): self.name = name def handle_signal(self, *args, **kwargs): print('test') When I exchange the instance method with a function it works however. I defined the other function this way. def handle_signal(sender, **kwargs): print('signal received') I tried using send_robust instead of send but it didn't throw any exceptions. -
Add interactive map of india only
I am working on django . I want to add a interactive map of inda . Interactive means when i click on any state of india then map of that state come to screen.i try many like folium and Map api . Map is similar to the website covid19india.org map of india. Please suggest me. -
How to create multiple model instances with Django Rest Framework?
I want to create multiple objects in one POST request. I've already read answers to similar questions but didn't find acceptible solution for my problem. Here's what I'm trying to do: req = requests.post(url=URL, data=json, headers=headers) # {"data": [{"id": "id123", "name": "NAME1"}, {"id": "id357", "name": "NAME2"}]} @api_view(['POST']) def many_testsCreate(request): data = request.data["data"] serializer = Test_resultsSerializer(data=data, many=True) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, safe=False) else: return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class Test_resultsSerializer(serializers.ModelSerializer): class Meta: model = Test_results fields = '__all__' But I get the following error: Internal Server Error: /api/many-tests-create/ Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\decorators.py", line 50, in handler return func(*args, **kwargs) File "C:\Users\user\Documents\FuncTestDB\ftresultsdb\api\views.py", line 102, in many_testsCreate return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST) File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\django\http\response.py", line 551, in __init__ raise … -
Error in wrong file path when saving excel file
I create a new folder in the BASE_DIR directory named temp_folder. In this folder, I want to save xlsx files for later archiving. But when I save the file, I get an error. from app.settings.base import BASE_DIR os.mkdir(os.path.join(BASE_DIR, 'temp_folder')) path_to_temp_folder = os.path.dirname(BASE_DIR) print(path_to_temp_folder) # return /home/y700/projects/solution wb = load_workbook(filename=file) ....some logic for excel file ... # Generate file name new_file_name = self.generate_file_name(u_name) wb.save(f'{path_to_temp_folder}/temp_folder/{new_file_name}') wb.save return error FileNotFoundError: [Errno 2] No such file or directory: '/home/y700/projects/solution/temp_folder/SM_2020Q2_Testdownload_20R1_1.xlsx' The path to the file that is specified in the error is correct, here I expect to see the saved file, but why is it not saved? -
Add operation on same valued record in Django
I am trying to run query that sum of the same record that on the database. It is more clear to use codes instead of words. class Track(models.Model): title = models.CharField() isrc = models.CharField() ... class Playlog(models.Model): track = models.ForeignKey(Track, on_delete=models.CASCADE) .... On database there is multiple record which has same isrc value. To get real playlog data I needed to get total playlog count which has same isrc of all Track. I tried following query but it shows me a duplicated values of Track. if there is same isrc I wanted to get sum of all playlog of same isrc record. Playlog.objects.values("track__isrc").annotate(Count("track__playlog", filter=Q(track__playlog__duration__gte=10)) -
Find table by name - Django
How I can find table by name in code python? Example: class AlexAlex(models.Model): title = models.CharField(max_length=255) message = models.TextField() dataMsg = models.DateField() fromMsg = models.CharField(max_length=255) readMsg = models.BooleanField(default=False) def __str__(self): return self.title and now I want to find the class name as it has some username. Example in code: UserLogged = "AlexAlex" or UserLogged = "Alex alex" + "s" // Example name user logged Table = functionWhichFindTablebyName(UserLogged) // Find table by name Table.objects.get.all() Can I do like this?I want that use for 'box mail users'.I have a lot of table and I don't wanna write manual in import/from.