Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Give name to object model in Django Rest Framework
I need help to give name "Product" to every object in "Products" array. But I can't find way to do it. I'm using ViewSets and ModelSerializer What I want: products: [ Product: {id: 1, name: 1}, Product: {id: 2, name: 2}, ] What I have: products: [ {id: 1, name: 1}, {id: 2, name: 2}, ] models.py class Product(models.Model): image = models.FileField(blank=True) name = models.CharField(max_length=120) volume = models.DecimalField(decimal_places=0, max_digits=1000) collection = models.ForeignKey('Collection', on_delete=models.CASCADE) def __str__(self): return self.name serializers.py class ProductSerializer(serializers.ModelSerializer): collection = CollectionInProductSerializer() combination = CombinationInProductSerializer(many=True) recomendations = RecomendedProductSerializer(many=True) class Meta: model = Product fields = '__all__' -
Django - Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
Why i am getting this error? Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'> how do i solve this ? my Homepage/api/views.py from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view from Homepage.models import EducationLevel from Homepage.api.serializers import EducationLevelSerializer @api_view(['GET', ]) def api_detail_educationlevel(request): try: education = EducationLevel.objects.all() except EducationLevel.DoesNotExist: return Response(status=status.HTTP_400_BAD_REQUEST) if request.method == "GET": serializer = EducationLevelSerializer(education) return Response(serializer.data) Homepage/api/serializers.py from rest_framework import serializers from Homepage.models import EducationLevel class EducationLevelSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = EducationLevel field = ('Sequence', 'Description', 'Status') my Homepage/api/urls.py from django.urls import path from Homepage.api.views import api_detail_educationlevel app_name='educationlevel' urlpatterns = [ path('', api_detail_educationlevel, name="detail"), ] my main urls.py urlpatterns = [ path('api/educationlevel/', include('Homepage.api.urls', 'educationlevel_api')), ] -
How to call asynchronous function in Django?
The following doesn't execute foo and gives RuntimeWarning: coroutine 'foo' was never awaited # urls.py async def foo(data): // process data ... @api_view(['POST']) def endpoint(request): data = request.data.get('data') // How to call foo here? foo(data) return Response({}) -
Integrate legacy MongoDB into Django
I have an existing MongoDB that has over 18k objects. Each object is of 23 fields, some of them have a multilevel nesting. I don't have experience working with Mongo in Django RF but from my experience working with SQL, I know I need to have models defined. There is an introspect function in Django that can create models.py from a legacy DB but it does not seem to work with NoSQL. My question is: how can I introspect my existing MongoDB into a Django model? if the first method is not an option, what is the right way to solve this issue in Django? -
Cannot loaddata to Django (MySQL) DB
I'm trying to load django data which I took backup using the below command ./manage.py dumpdata --exclude auth.permission --exclude contenttypes > django_db_backup.json When I'm trying to load the data back using ./manage.py loaddata django_db_backup.json I'm getting the below error. django.db.utils.OperationalError: Problem installing fixture 'path/to/django_db_backup.json': Could not load auth.User(pk=5): (1205, 'Lock wait timeout exceeded; try restarting transaction') Can anyone please help me with this? -
multiple form gerated jquery doesn't submit
I'm building a website (e-commerce like) with Django. At some point I display a list of items and for each item there is a form with submit button Order and Quantity picker. I've implemented filter function that delete the html code of my items list and rebuild it with the matching items with jquery. The new forms generated by this function do nothing when the submit button is clicked Here is a part of the code I use in my function (I use an ajax call to generate a json of matching items and then I display them in the table list) : $.each(code_json, function(index, value){ var string = "<tr id="+ value.material +"><td>"+ value.manufNo +"</td><form method='POST' action='/add_to_cart/"+value.material+"/"+ value.node+"/{{language}}'><td><input type='submit' class='btn' value='Commander' style='color:blue;'></td><td><input id='qty' type='number' name='qty' class='form-control' value='1'></td></form></tr>"; $("#header").after(string); }); I know that usually with Django you have to add {% csrf_token %} for each form. However it throw an error page usually when missing and here it doesn't show anything Thank you for your help -
overriding get_fields in ModelAdmin return this fiels on all model
I need to add languages related fields to ModelAdmin, for save as json after. But these fields appear in all the models of my applications. Why? For example with a simple app: models.py: from django.db import models class TestModel2(models.Model): txt_field = models.TextField() class TestModel(models.Model): txt_field = models.TextField() admin.py: from moduleadmin.models import TestModel, TestModel2 from django.conf import settings from django import forms class TestModelAdmin(admin.ModelAdmin): def get_fields(self, request, obj=None): my_fields = super(TestModelAdmin, self).get_fields(request, obj) new_fields = [(lang[0], forms.CharField(max_length=50, required=(lang[0] == settings.LANGUAGE_CODE)) ) for lang in settings.LANGUAGES] for f in new_fields: if f[0] not in my_fields: my_fields.append(f[0]) self.form.declared_fields.update({f[0]: f[1]}) return my_fields admin.site.register(TestModel, TestModelAdmin) admin.site.register(TestModel2) and in settings.py I've added: LANGUAGES = ( ('fr', 'French'), ('en', 'English'), ) So if I try to add one TestModel2 entry, It's ok. But if i go to TestModel add entry form, and return to TestModel2 add, I've the two fields appear in forms. Can you help me? Or maybe there's a better approach? Thanks. -
Changing the way the admin panel looks when I am viewing a model object
I am learning Django and have a question around changing the way something looks in the admin panel. Right now when I click on an object of one of my models it looks like this.. enter image description here I am using an ArrayField with a Postgresql database to allow that. But what I want to do is change it to look like this: enter image description here I believe I need to override something in the admin panel but I am not sure which template it is or if this is possible. -
Queryset ordering for nested objects
I need to build a simple nested comment system in my project with REST api. There are some requirements: The page should contain the pagination of all comments, not just the parent ones. So, if there are 1 comment and 20 nested comments from other users, then on the first page should be displayed, like so: -Comment 1 -- Sub comment 1 -- ... -- Sub comment 9 On the second page: -- Sub comment 10 -- ... -- Sub comment 19 On the third page: -- Sub comment 20 And it should be an optimal solution in terms of the least database access. I was wondering about custom Queryset ordering, when after each comment follows nested comments, like so: // Note, that ids follow in chaotic order { id: 1, text: "Comment 1", parent: null }, { id: 5, text: "Sub comment 1 for Comment 1", parent: 1 }, { id: 6, text: "Sub comment 2 for Comment 1", parent: 1 }, { id: 2, text: "Comment 2", parent: null }, { id: 3, text: "Sub comment 1 for Comment 2", parent: 2 }, { id: 4, text: "Sub comment 2 for Comment 2", parent: 2 }, I've also … -
Custom authentication_classes in Django Rest Framework with Knox
I have a Django Rest Framework API, in this API I use Knox to connect / disconnect my users. I have a view (PollViewSet) which if the user is connected my view returns his personal data, if the user is anonymous my view returns the basic data. So, when an user logs in, Knox create a token for this user for 10 hours, connect my user, and so my view return his personal datas. But after 10 hours, the token is destroyed, and if my user refreshes his web page, he sends the request with an old token. Because of this, my view does not return basic data as an anonymous user, but returns Invalid Token. I would like that if I send an invalid token to my view, my request is treated as an anonymous user and does not trigger an "invalid token" error. I tried to create a custom authentication_classes but I have a problem with the token_key, and that doesn't seem like a good way to do it. I am interested in any help to help me with this problem ! Here my code with the important parts: settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'knox.auth.TokenAuthentication', ) } … -
'WSGIRequest' object has no attribute 'profileaccount'
I am getting the following error and I want to return a model profileaccounts.id but it is not within WSGIRequest. Is there a way to find all the objects with WSGIRequest? ERROR LOG AttributeError at /2/detail/ 'WSGIRequest' object has no attribute 'profileaccount' Views.py class ProfileAccountDetailView(LoginRequiredMixin, DetailView): model = ProfileAccount fields = [ 'first_name', 'family_name', 'email', 'account_active', ] def get_success_url(self): return reverse( "profiles:detail", kwargs={'pk': self.request.profileaccount.id}, ) def get_object(self): return ProfileAccount.objects.get( pk=self.request.profileaccount.id ) -
Using Nibabel in Django
I am making a web app that converts .nii files to png(zip). I have implemented the main logic in python but am facing problems porting it to the web app. So I want to create a form that accepts a .nii file and outputs a zip file containing all the .png slices. So far I've written a simple view: Views.py from django.shortcuts import render from .forms import SharingForms from django.http import HttpResponse import imageio,nibabel,numpy from zipfile import ZipFile from .models import NII def index(request, **kwargs): if request.method == 'POST': form = SharingForms(request.POST,request.FILES) if form.is_valid(): for field in request.FILES.keys(): for formfile in request.FILES.getlist(field): file = NII(file = formfile) file.save() response = HttpResponse(content_type='application/zip') zip_file = ZipFile(response, 'w') image_array = nibabel.load(file).get_fdata() if len(image_array.shape) == 4: # set 4d array dimension values nx, ny, nz, nw = image_array.shape total_volumes = image_array.shape[3] total_slices = image_array.shape[2] for current_volume in range(0, total_volumes): slice_counter = 0 # iterate through slices for current_slice in range(0, total_slices): if (slice_counter % 1) == 0: # rotate or no rotate data = image_array[:, :, current_slice, current_volume] #alternate slices and save as png print('Saving image...') image_name = file[:-4] + "_t" + "{:0>3}".format(str(current_volume+1)) + "_z" + "{:0>3}".format(str(current_slice+1))+ ".png" imageio.imwrite(image_name, data) print('Saved.') zip_file.write(image_name) zip_file.close() response['Content-Disposition'] … -
Django Multi Tenant Schemas Media Files Path
I am using Django with Multi Tenant Schemas. Everything is working well on production, but I am having an issue with image media Path. My web server is an Apache2 installed on Ubuntu 18.04, in the site configuration file I have: ''' ServerName qibot.com.br ServerAlias tenant1.qibot.com.br tenant2.qibot.com.br tenant3.qibot.com.br ServerAdmin webmaster@localhost DocumentRoot /var/www/html Alias /static /var/www/qibot_system/static <Directory /var/www/qibot_system/static> Require all granted </Directory> Alias /media /var/www/qibot_system/media/ <Directory /var/www/qibot_system/media/> Require all granted </Directory> ... </VirtualHost> ''' In this way, if the media (image or video) file is requested, django looks for /var/www/qibot_system/media/ instead of /var/www/qibot_system/media/tenant1 or /var/www/qibot_system/media/tenant2 or /var/www/qibot_system/media/tenant3 My question is, there is a way to set the variable on the end of /var/www/qibot_system/media/XXXXXXXXX to provide right path to django? Best Regards -
Django Admin raw_id)fields pop-up selector outside Django admin
Is there a way to implement the pop-up selector of raw id fields outside of django admin? -
Dependent Dropdown form in Admin
I want to build a dependent dropdown form in Admin which has fileds Tag1, Tag2, Tag3, Title and Deadline. It should be such that the user selects some Tag1 and based on it he can select Tag 2. Also Tag3 depends on tag1 choice and the title choice depends on all the above tags in the form. The deadline value is based on the title selected. However if the selected title is "OTHER" he can add add a title manually and also the deadline manually. Here is an approach I tried: Created 4 different models, c1, c2, c3 and task(which saves title and deadline). Error 1: If i use c1's foreign key in c3, it does not run. Error 2: even if i set c3 dependent of C2 I dont get the list of objects in the dropdown for either of them. Error 3: Even after entering the values for new objects, I am unable to make it work. I am working on this since 4 days but I am unable to figure a way out. here's my Code models.py: class c1(models.Model): name = models.CharField(max_length=30, default="Other") def __str__(self): return self.name class c2(models.Model): '''c1_choice=(('Support Staff','Support Staff'), ('Consumables', 'Consumables'))''' c1 = models.ForeignKey(c1, … -
Django and highcharts , making querys
I have two models, here the first model have the prices and the second have the amount of the products. it is like model1 = contract , and model2 = invoice. Model 1 class Model1(models.Model): year = models.PositiveIntegerField(verbose_name="year") price_field1 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) price_field2 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) price_field3 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) price_field3 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) price_field4 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) def __str__(self): return str(self.id) Model 2 class Model2(models.Model): model1=models.ForeignKey(Model1,on_delete=models.CASCADE,verbose_name="Model1",related_name='Model1Objects') amount_field1 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) amount_field2 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) amount_field3 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) amount_field3 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) amount_field4 = models.DecimalField(blank=True,null=True,decimal_places=2,max_digits=8) def __str__(self): return str(self.id) One Model1 ,can have a lot of model2 related to model1 , it is a relationship 1-N i want to do a statistics about model1 per year , so i want to sum all the objects model2 and multiply to the price in model1, something like this: ((sum all amount_field1 related to year 2019) * (price_field1 related to year 2019) + (sum all amount_field2 related to year 2019) * (price_field2 related to year 2019) + ....... ). after that put the result on highcharts. i already have the template , and the values pass to the template in view . VIEW def Estatisticas(request): values = [results here] context = {'values': values} return render(request, 'dashboard/index.html', context=context) When i put the … -
stick footer to bottom django template
Good day, I am trying to stick footer to bottom django template layout, flex box and grid doesn`t help. May be in Django template another way? -
User has no attribute profile
I am currently trying to create a user profile whenever they register and the user is created, the error message shows: RelatedObjectDoesNotExist User has no profile. signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def create_profile(sender, instance, **kwargs): instance.profile.save() views.py from django.shortcuts import render, redirect from .forms import UserRegisterForm from django.contrib.auth import login from django.contrib.auth.decorators import login_required def register(request): if request.method != 'POST': form = UserRegisterForm() else: form = UserRegisterForm(data=request.POST) if form.is_valid(): new_user = form.save() login(request, new_user) return redirect('blog:home') context = {'form': form} return render(request, 'user/register.html', context) @login_required def profile(request): return render(request, 'user/profile.html') models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return self.user.username -
Save relation between anonymous user and a file with user login with foreign key - Django
I am a beginner with programming and trying to make a web app that creates a video programmatically on button click in browser and displays it in the same browser for the user once it's created. I want it to be something like this but the button runs a moviepy script to create the video and upload it to a django model and pass it through a view. Now I am trying to create the relationship between person who clicks the button and the video that is created with foreign key. I want to do this without a login and I see a lot of tutorials about associating a user that is logged in but not so much about anonymous users. Is my approach the right one? I am trying like below and receive the error - video_upload_detail_page() missing 1 required positional argument: 'user_id' .html {% load static %} <html> <head> <title>Title of the document</title> </head> <body> <video width="320" height="240" controls> <source src= "{{ MEDIA_URL }}{{ object.videofile }}" type='video/mp4'> </video> <p></p> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <button id="myClickButton" type="button">Click</button> <div id="myOutput"></div> <input id="id_holder" type="hidden" value="{{ request.user.id }}"> <script> $("#myClickButton").click(function() { // catch and send user id to use in get request // in … -
Call pop up bootstrap modal from another html file
I want to pop up a delete alert message when a delete icon is pressed. The problem is delete pop up modal is in one html file and delete icon is in another html. As I am using django modelform I can not keep bothe of them in a signle html. That's why I have make two different html files. I am trying to connect both of them. But I dont know how to that. I followed an instruction but it is not showing as popup rather it is showing as a normal html. employee_list.html: {% extends "base.html" %} {% block content %} {% load static %} <link rel="stylesheet" href="{% static 'employee/css/master.css' %}"> <div class=""> <div class="table-wrapper"> <div class="table-title"> <div class="row"> <div class="col-sm-6"> <h2><b>Employees</b></h2> </div> <div class="col-sm-6"> <a href="{% url 'employee:employee-add' %}" data-target="exampleModal" class="btn btn-success" data-toggle="modal"> <span ></span> <i class="material-icons"></i> <span data-feather="plus"></span>Add New Employee </a> <!--<a href="#deleteEmployeeModal" class="btn btn-danger" data-toggle="modal"><i class="material-icons">&#xE15C;</i> <span>Delete</span></a>--> </div> </div> </div> <table class="table table-striped table-hover"> <thead> <tr> <th> <span class="custom-checkbox"> <input type="checkbox" id="selectAll"> <label for="selectAll"></label> </span> </th> <th>ID</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> <th>Address</th> <th>Phone</th> <th>Department</th> <th>Designation</th> <th>Actions</th> </tr> </thead> <tbody> <!-- Loop for showing employee list in a table--> {% for employee in object_list %} … -
No access to the Django server at http://127.0.0.1:8000/
I have installed Django to build apps and following the official documentation. Before installing it I have check my Python version (3.5), installed virtualenv and activate it. Everything ok but I can't access the developpement server at 127.0.0.1:8000 in my web browser despite of a successfull python manage.py runserver command. I read this post, but it's not better when I change my settings.py file. Am I missing something ? How can I access 127.0.0.1:8000 in my web browser ? Here is Django message in terminal : Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). June 15, 2020 - 12:27:55 Django version 2.2.13, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. -
convert MySQL query into Django
SELECT category, COUNT(*) FROM front_end_post_job WHERE post_type = 'job' GROUP BY category i have this query i want to use this in Django how to use this -
Django gets killed on redhat server (Out of memory)
I have a Django project running on a redhat 7.7 server which is a service for training spacy models.(-python v2.7.5 -spacy v2.0.18 -django v1.11.29 -djangorestframework v3.9.4 -django-apscheduler v0.3.0) Redhat kills the entire django process after 3-10 iterations during execution of the training job. The code: def train_spacy_model(model_id, storage_path, file_id, call_back_url): status = "fail" try: if os.path.isfile(os.path.join(storage_path, "spaCy_model_" + model_id + ".pkl")): pickle_file: BinaryIO = open(os.path.join(storage_path, "spaCy_model_" + model_id + ".pkl"), "rb") nlp = pickle.load(pickle_file) else: nlp = spacy.load("en_core_web_sm") pickle_file: BinaryIO = open(os.path.join(storage_path, "dataset_" + model_id + ".pkl"), "rb") training_data = pickle.load(pickle_file) pickle_file.close() ner = nlp.get_pipe('ner') for _, annotations in training_data: for ent in annotations.get('entities'): ner.add_label(ent[2]) other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner'] with nlp.disable_pipes(*other_pipes): optimizer = nlp.begin_training() for i in range(100): print("Starting iteration " + str(i)) print(sys.getrefcount(nlp)) losses = {} for text, annotations in training_data: nlp.update( [text], [annotations], drop=0.2, sgd=optimizer, losses=losses ) print(losses) fname = os.path.join(storage_path, "spaCy_model_" + model_id + ".pkl") with open(fname, "wb") as f: pickle.dump(nlp, f) status = "success" os.remove(os.path.join(storage_path, "dataset_" + model_id + ".pkl")) except Exception as e: print(e) train_call_back(model_id, file_id, call_back_url, status) The error code in redhat logs (/var/log/messages) is : Jun 15 11:12:26 AZSG-D-CTBT03 kernel: Out of memory: Kill process 20901 (python) score 618 or … -
How To Access Many Field In One-To-Many Relationship
I have two different user types, Teachers and Students. My students have a one-to-many relationship with a Teacher (a student can have one teacher / a teacher can have many students). I am able to access a student's Teacher in templates like this user.student.teacher, but I dont know how to access a list of a Teacher's Students? From a teacher's profile page id like to print a list of their students. # override default User model class User(AbstractUser): user_type = models.CharField(choices=USER_TYPES, max_length=255, default='student') class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE, default=None, null=True) Thank you. -
y-a t-il un moyen de lier un champ d'un formulaire a un autre? [closed]
bonjour , je m'interesse à django depuis peu! et aujourdhui suis dans la creation de mon apps, et jaimerai avoir un formulaire dans lequel on pourra saisir par exemple l'username d'un membre et directement on obtient un deuxieme champ qui repete les données entrees. j'ai pu voir ce que notre collegue a fait et j'avoue que je comprend pas tres bien