Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Modelling a 'web' in a Django database
I have a use case where I have a 'web' with the following relationships; what's the best way to model this in Django? There is a logical top layer (could be modelled as a single 'very top' node if required) There are logical leaves at the bottom Nodes can have relationships to nodes in the layer above and/or below but never to siblings So like that chinese game with a coin dropping through pins, there are multiple routes from top to bottom but a traversal will always work, albeit in some manner determined elsewherre (actually user input in my case). I have tried using ManyToMany relationships but can't see how to spot the top and bottom of the relationships; do I need to switch to many OneToMany relationships for independent child and parent relationships? -
Why don't I obtain tag instance attached to my question instance?
I'm beginner in django and new to DRF. So, the problem is within my create() method in my nested serializer. The thing is that it creates new tags instances but don't attach them to question instance which I`d like to send on server in my POST request. Here is my model: class Question(models.Model): title = models.CharField(max_length=100) content = models.CharField(max_length=500, default="Write your question") # HTMLField() look TinyMCE tags = models.ManyToManyField("Tag") pub_date = models.DateField(auto_now=False, auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) answers = models.ManyToManyField("Answer") comment_cnt = models.IntegerField(default=0) like_cnt = models.IntegerField(default=0) def __str__(self): return self.title def get_absolute_url(self): return reverse('questions', args=[self.title]) class Meta: ordering = ['pub_date'] class Answer(models.Model): content = models.CharField(max_length=500, default="Write the answer") # HTMLField() look TinyMCE pub_date = models.DateField(auto_now=False, auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) like_cnt = models.IntegerField(default=0) def __str__(self): return self.author.username class Tag(models.Model): name = models.CharField(max_length=50) discription = models.CharField(max_length=500, default="This is description") use_cnt = models.IntegerField(default=0) def __str__(self): return self.name Here is serializer: class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = '__all__' read_only_fields = ['use_cnt'] class AnswerSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = '__all__' class QuestionSerializer(serializers.ModelSerializer): tags = TagSerializer(many=True ) answers = AnswerSerializer(many=True, read_only=True) class Meta: model = Question fields = '__all__' def create(self, validated_data): tags_data = validated_data.pop('tags') question = Question.objects.create(**validated_data) for tag_data … -
Filter a querryset in Django based on a changing value
I build a Blogpost App with Django and want comments under the blogpost. I can allready post new comments, and see comments, but i see every comment under every blogpost. In the database every comment is linked to the correct blogpost. class blogpost(models.Model): user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL) title = models.TextField() slug = models.SlugField(unique=True) content = models.TextField(null=True, blank=True) class blogcommment(models.Model): user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL) post = models.ForeignKey(blogpost, default=1, null=True, on_delete=models.SET_NULL) title = models.TextField() content = models.TextField(null=True, blank=True) def blogpost_detail_view (request, slug): # Blogeintrag anzeigen obj = blogpost.objects.get(slug=slug) form = blogcommentform(request.POST or None) qs = blogcommment.objects.filter(***What should stay here and why?***) if form.is_valid(): comment = blogcommment.objects.create(**form.cleaned_data) form = blogcommentform template_name = 'blogpost_detail.html' context = {"object": obj,'form': form,'object_list': qs} return render(request, template_name, context) -
Django get_queryset filtering with multiple select
I doing a form of filtering by the foreignkey field with two search conditions: OR and AND and multiple choices. forms.py class EmployeeSkillFilter(forms.ModelForm): skills = forms.ModelMultipleChoiceField(queryset=Technology.objects.all(), ) class Meta: model = Employee fields = ['skills'] templates.py <form method="get" enctype="multipart/form-data"> {% csrf_token %} <input type="checkbox" name="and" value="AND"> Choice and<br> <input type="checkbox" name="or" value="OR"> Choice OR<br> {{ skill_filter }} <button type="submit" class="btn btn-info" type="button">Go!</button> </form> views.py class AccountList(AuthorizedMixin, ListView): model = Employee template_name = 'employee_list.html' def get_queryset(self, *args, **kwargs): condition_and = self.request.GET.get('and', None) condition_or = self.request.GET.get('and', None) skill = self.request.GET.get('skills', None) if condition_and and skill: object_list = self.model.objects.filter(skills__name_id=skill) ?????? if condition_or and tech: object_list = self.model.objects.filter( Q(skills__name_id=skill) | Q(skills__name_id=skill) ) ????? else: object_list = self.model.objects.all() My urls looks like localhost://....or=OR&skills=5&skills=4&skills=3 The problem is that when I select multiple objects in a form, I don't know how to pass them all to the condition skills__name_id=skill -
How can i set a Django render block value in the "with template tag"?
I am displaying dynamic title based on different views in the Django application, i want to set the same title on the 3 meta tags in my base.html file, which gets extended in all other templates. This works correctly, when i set a string on title variable: {% with title='TEST'%} <title>{% block page-title %}{% block title %}{% endblock %} | {{ agency.name }}{% endblock %}</title> <meta property="og:title" content="{{title}}" /> <meta name="twitter:title" content="{{title}}" /> {% endwith %} I want to set this dynamic title like: {% with title="{% block page-title %}{% block title %}{% endblock %} | {{agency.name }}{% endblock %}"%} <title>{{title}}</title> <meta property="og:title" content="{{title}}" /> <meta name="twitter:title" content="{{title}}" /> {% endwith %} But when i do like this, then i don't get the value in title variable: How can i set it to a variable in with template tag and then re-use that variable in other tags? or is there any other way of doing it ? -
How to connect from my PC to multi-tenant django project on remote PC
I have a PC at work and we started to use for our testing purposes before deploying our code to production server. The problem is that our django project is built with django-tenant-schemas. So, I deployed project on local (remote) PC, with docker with postgres and nginx containers. It works on that PC, but when I want to connect to the project from my PC or my colleague's one, it throws 404 error, stating no such tenant. I've tried nginx configuration, changed several times my /etc/hosts/ file, tried to change firewall on remote desktop (i just opened port, on which dockerized nignx works). My nginx config. backend:8000 and auth:8000 are names of docker containers in my docker-compose.yml and their ports. server { server_name test.backend; location /v1/ { proxy_pass http://backend:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Scheme $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } server { server_name test.auth; location /v1/auth/ { proxy_pass http://auth:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Scheme $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } It should work this way. On remote PC project opened on http://test.localhost/v1/ URL and it works. The IP of remote PC is stored in my /etc/hosts file with … -
How to use session id in an ecommerce application for helping anonymous users use functionalities that logged in users can use?
I am making an E-commerce application, the final problem I have to solve is giving anonymous users access to use the cart, wishlist, billing and doing pretty much everything a logged in user can do. I know I have to use sessions But to be honest I don't get the document clearly, so please if anybody can help me solve the problem by writing the answer down below and showing me if there's a way to store session id's in models and then a user exits the browser the model objects get deleted. But if the user logins then all this information gets saved to his account id. If this way of handling the situation exists. Kindly show me how with examples, that would help you earn more points and better a chance to get respect from my side. Thank you, -
Message framework: Add message when saving Page class in Wagtail
So I would like to check if a certain field has changed and if so, display a info-message to the user that they should review other datapoints. I feel that the Django messages framework should be ideal for this, but I cant find where to hook in to the wagtail Page class to get this to work. Right now I have the check on the save method for the page like below, but I do not have access to the request object here, so I cant use massage.add_message (since this uses the request object as a parameter). What am I missing? def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.pk is not None: original = EventDetail.objects.get(pk=self.pk) if ( original.start_date != self.start_date and self.messages.all().count() > 0 ): messages.add_message( request, messages.INFO, _( "You have just changed starting time on an event that contains messages, please review the times for the message sends." ), ) -
Problem with saving a property of an object after validation
In my CreateView class I created an instance of my Wholesale_Client model. Inside form_valid() function I am fetching from my form some information which I will use in create_woocommerce_client_individually() function in order to post this record in my woocommerce website. Every user in woocommerce website has a post id which I have it as attribute in my Wholesale_Client model. My aim is after storing the wholesale client instance in my db and in woocommerce website(successfully), to fetch the current stored wholesale client record in order to update the post id of this user(from null to post id). How can I update information after fetching the record? Here is my code: Function for creating a woocommerce client in the website def create_woocommerce_client_individually(wcapi,name,surname,email): data = { "first_name": name, "last_name": surname, "email": email, } wcapi.post("customers", data).json() Function for giving the customer id from woocommerce website , using the api, to my record. def give_cid_to_client_individually(wcapi,email): r=wcapi.get("customers?email="+str(email)).json() post_id=r[0]['id'] fetched_client=Wholesale_Client.objects.get(email=email) fetched_client.cid=int(post_id) fetched_client.save() Here (is the problem) despite the fact that the record is fetched successfully the post_id is not saved to the cid attribute of my model. My CBV class WholesaleClientCreateView(LoginRequiredMixin, CreateView): model = Wholesale_Client form_class = WholesaleClientForm success_url = reverse_lazy('wholesale_clients_list') template_name='wholesale_clients/wholesale_client_create_form.html' def form_valid(self, form): print("Inside … -
why does Admin panel not show users in django admin site?
i login with supers user account but it shows me nothing . why ? [admin panel shows nothing ] https://i.stack.imgur.com/490OM.png -
why the output of subprocess.Popen is not the same as expected?
I have a Django server which trying to run with subprocess.Popen and store all the logs on a file, this is my code: with open('thefile.log', 'a') as the_file: p1 = subprocess.Popen(['python', os.getcwd() + '\\mySite\\manage.py', 'runserver'], stdout=the_file, stderr=the_file, universal_newlines=True) and this is the result in the thefile.log: Watching for file changes with StatReloader [26/Jul/2019 13:10:05] "GET / HTTP/1.1" 200 16348 [26/Jul/2019 13:10:05] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 [26/Jul/2019 13:10:06] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 85692 [26/Jul/2019 13:10:06] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 86184 [26/Jul/2019 13:10:06] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 85876 Not Found: /favicon.ico [26/Jul/2019 13:10:08] "GET /favicon.ico HTTP/1.1" 404 1976 Not Found: /fs [26/Jul/2019 13:10:11] "GET /fs HTTP/1.1" 404 1949 Performing system checks... System check identified no issues (0 silenced). July 26, 2019 - 13:09:44 Django version 2.2.3, using settings 'mySite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. but it should be like this: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). July 26, 2019 - 13:09:44 Django version 2.2.3, using settings 'mySite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [26/Jul/2019 13:10:05] "GET / HTTP/1.1" 200 16348 [26/Jul/2019 13:10:05] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 [26/Jul/2019 13:10:06] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" … -
how to receive modelform_instance.cleaned_data['foreign key field'] in view when form field is ModelMultipleChoiceField?
Here is the situation: I have a model as below: class School(Model): name = CharField(...) Permit model has three objects: School.objects.create(name='school1') # id=1 School.objects.create(name='school2') # id=2 I have another model: Interest(Model): school_interest = ManyToManyField(School, blank=True,) I then build a ModelForm using Interest: class InterestForm(ModelForm): school_interest = ModelMultipleChoiceField(queryset=School.objects.all(), widget=CheckboxSelectMultiple, required=False) class Meta: model = Interest fields = '__all__' I have a view: def interest(request): template_name = 'interest_template.html' context = {} if request.POST: interest_form = InterestForm(request.POST) if interest_form.is_valid(): if interest_form.cleaned_data['school_interest'] is None: return HttpResponse('None') else: return HttpResponse('Not None') else: interest_form = InterestForm() context.update({interest_form': interest_form, }) return render(request, template_name, context) and in interest_template.html I have: <form method="post"> {% csrf_token %} {{ interest_form.as_p }} <button type="submit">Submit</button> </form> I expect to see None when I check no one of the form fields and submit it. I expect to see 'Not None' when I check any or all of the form fields and submit the form. However, I do not see what I expect to happen. -
Getting Undefined when making requests with the built-in interactive API documentation support of Django Rest Framework
I tried to make a simpleGET request but I get Undefined in the pop up. What could be the problem? -
Hi Which is The Best For Professional Website django or flask?
I'm confused which one I want to learn Django or flask for a highly professional website I'm confuse and i want to earn money to for your opinoin which is best for me? -
django how to transfer sum value to another model field each time user input is happened
enter image description herei want to transfer the sum value of stok_masuk as total_masuk,which then it will become the value of another model. The problem is,aggregate sum can only update the value to the same model. Which is why i make onetoonefield for the other model. But the value is not the accumulated total, but still a piece that must be chosen manually by admin, not automatically because this code is not working. def t_masuk(self): jaya = Pergerakanstokgudangatas.objects.aggregate(Sum('stok_masuk')) jaya.save(update_fields=['total_masuk']) return self.t_masuk def t_keluar(self): joyo = Pergerakanstokgudangatas.objects.aggregate(Sum('stok_keluar')) joyo.save(update_fields=['total_keluar']) return self.t_keluar The expected result would be,in picture 45454545, the total value of stok_masuk and stok_keluar will become a value as total_masuk and total_keluar in another fieldenter image description here -
Django queryset how to aggregate (ArrayAgg) over queryset with union?
from django.contrib.postgres.aggregates import ArrayAgg t1= Table1.objects.values('id') t2= Table2.objects.values('id') t3= Table3.objects.values('id') t = t1.union(t2, t3) t.aggregate(id1=ArrayAgg('id')) This raises error {ProgramingError} column "__col1" does not exist Equivalent raw SQL SELECT array_agg(a.id) from ( SELECT id FROM table1 UNION SELECT id FROM table2 UNION SELECT id FROM table3 ) as a -
Why do Django developers use Django builtin admin panel? is it said that must to use instead of a html theme?
I want to develop full functional web application in python django. I want to use bootstrap admin theme to develop admin site. I want to know is it required to use django admin while you are a django developer? or it's just a optional function if some one interested to complete tasks fast? -
Django Admin Inline field No foreign key error
I have two models,linked through Foreign key. What I exactly want is I have created Table hobbies which has some hobbies and user can select hobbies listed in hobbies table inform of checkbox.When editing model 'UserModel', on admin site in field where I have applied FK it shows dropdown to 'Hobbies' Model.On admin site I want hobbies to be displayed in form of checkbox instead of opening a new popup window and selecting hobbies.While searching I found Inline. I have tried to use them but I'm unsuccessful so far. I don't know what I'm doing wrong. models.py from django.db import models from django.contrib.auth.models import User from multiselectfield import MultiSelectField from tagulous import * import tagging class hobbies(models.Model): hobbies_choices = ( ('CRR', 'Cricket'), ('POL', 'Politics'), ('FBL', 'FootBall'), ('TV', 'Television'), ('MOV', 'Movies') ) table_id=models.AutoField(primary_key=True) hobbies = MultiSelectField( choices=hobbies_choices, verbose_name='Hobbies', default=None ) def __str__(self): return str(self.hobbies) class UserModel(models.Model): username=models.ForeignKey( User, related_name='UserModel', on_delete=models.CASCADE, ) name=models.CharField( max_length=50, verbose_name='Full Name', ) gender=models.CharField( choices=( ('M','Male'), ('F','Female'), ), max_length=1, verbose_name='Gender', default='M' ) hobbies=models.ForeignKey(hobbies,on_delete=None,related_name='of_user') admin.py from django.contrib import admin from .models import hobbies,UserModel from django.forms import CheckboxSelectMultiple from .forms import * from django.utils.safestring import mark_safe from django.utils.html import format_html from django.contrib.auth.models import User #from django.contrib.sites.models import Site from django.contrib.auth.models … -
Requested runtime (Python-3.7.3) is not available for this stack (heroku-18)
I'm using django 2.2.3 and I'm getting this error. But, heroku's python-support says that python-3.7.3 should be available in stack heroku-18. runtime.txt contains Python-3.7.3. FULL ERROR Counting objects: 100% (43/43), done. Delta compression using up to 4 threads Compressing objects: 100% (36/36), done. Writing objects: 100% (43/43), 10.70 KiB | 996.00 KiB/s, done. Total 43 (delta 6), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Requested runtime (Python-3.7.3) is not available for this stack (heroku-18). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed -
How to convert uploaded html file to pdf? (django rest framework)
I have already made html file template in the frontend, and by sending it to the backend I want it to be converted and saved as pdf, I'm newbie in django but I did tried some searching, here's what I found : https://www.codingforentrepreneurs.com/blog/html-template-to-pdf-in-django/ , If I go with this approach, it will be unnecessary to get multiple data from the user, since the form is very detailed, and frontend is enough to fill. I also did this approach but I don't know what I am missing (https://www.codingforentrepreneurs.com/blog/save-a-auto-generated-pdf-file-django-model) , here is my code so far: (utils.py) from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src): # template = get_template(template_src) # html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(template_src.encode("ISO-8859-1")), result) if not pdf.err: print(pdf) return HttpResponse(result.getvalue(), content_type='application/pdf') return None //============= (models.py) class Questionary(models.Model): date = models.DateField(auto_now_add=True) title = models.CharField(max_length = 100) file = models.FileField(upload_to='Documents/%Y/%m/%d/', blank = False, null = False) def generate_obj_pdf(self): obj = Questionary.objects.get(file=self.id) pdf = render_to_pdf(obj) filename = "YourPDF_Order{}.pdf" %(obj.title) return obj.pdf.save(filename, File(BytesIO(pdf.content))) I expect the html file to be auto converted to pdf, but it still saving it as html. -
Migrate data from django-media-tree to django-filer
We have a DjangoCMS with more than 1000 pages that has been live for many years now and we have been using django-media-tree for a long time, but have now also installed django-filer. I would now like to migrate all of my files from django-media-tree and into django-filer and at the same time, migrate the usage of the files (plugins in articles), so that I eventually can uninstall django-media-tree and make the site look the same for the end user. Has anyone tried to do this and perhaps have some pointers? Maybe someone has written a tool for this already? Regards, Erlend Dalen -
CommandError: No model or app named in elastic search
Here I am creating indices for a django model using django_elasticsearch_dsl but getting error while creating the one. My django app name where the code lies is press_publication django_elasticsearch_dsl = 0.5.1 elasticsearch = 6.6.1 I have tried rebuilding indexes with some already existing indices that working prefectly fine and tried replacing the fields with the new model field and that also working fine. But when creating separate file throwing error. from django_elasticsearch_dsl import DocType, Index, fields from pressads.models import FmPressads posts = Index('fmpressads') @posts.doc_type class FmPadsDocument(DocType): class Meta: model = FmPressads fields = [ 'description_visual', 'cr_qual', 'country', 'agency_cobranch_namelu', 'preprep_cs', 'id_agency_cobranch', 'id_client' ] when running the command python manage.py search_index --rebuild --models=press_publication Actual output is CommandError: No model or app named press_publication Expected output is creating index -
Django - FileField won't upload to database
I'm trying to upload some file with a FileField but when I hit the submit button and run the form.save() I have a new line in my database table but the file I tried to upload is not there. I've been searching for some time to solve my problem but the only thing I've seen is about the enctype="multipart/form-data", but as you can see in the files bellow, I already have it ... views.py class AdminFichiersPhyto(CreateView): template_name = 'phyto/phyto_admin_fichiers.html' model = models.PhytoFile fields = ['general_treatment', 'other'] def form_valid(self, form): print("GONNA SAVE") form.save() if self.request.POST.get('autre'): print("autre") # gonna add some code to read the 'other' file if self.request.POST.get('trtm_gen'): print("traitement généraux") # gonna add some code to read the 'general_treatment' file phyto_admin_fichiers.html {% block forms %} {% if user.is_staff%} <form method="post" action="" enctype="multipart/form-data"> <fieldset> <div style="display: inline-block; margin-left: 22%; text-align: center"><b>Traitements généraux</b>{{ form.general_treatment }}</div> <div style="display: inline-block; text-align: center"><b>Autres traitements</b>{{ form.other }}</div> </fieldset> </form> <p style="margin-top: 2%"> <input id="submit" class="btn btn-primary" type="submit" value="Synchronisation Traitements généraux" name="trtm_gen"/> <input id="submit" class="btn btn-primary" type="submit" value="Synchronisation Autre" name="autre"/> </p> {% endif %} {% endblock %} forms.py class PhytoFileForm(forms.ModelForm): class Meta: model = models.PhytoFile fields = ['general_treatment', 'other'] def __init__(self, *args, **kwargs): super(PhytoFileForm, self).__init__(*args, **kwargs) models.py class … -
Custom authentication in djangorestframework-jwt
I have two types of user. for one of them which is main user that it's model is available from get_user_model() is ok and the endpoint for that is: Import: from rest_framework_jwt.views import obtain_jwt_token path: path("api/token/", obtain_jwt_token, name="user_jwt") http://127.0.0.1:8000/users/api/token/ Everything is pretty find when I provide my main user credentials for generate token. but for the other type user Teacher it needs some changes in djangorestframework-jwt core codes. I know that it uses username as the default field to login. for main user is Ok, because it takes that this way: username_field = get_user_model().USERNAME_FIELD that in this case is email. I've defined that in model. but for the other type of user it tries to get username this way: def get_username(user): try: username = user.get_username() except AttributeError: username = user.username return username that because the user doesn't have get_username() attribute, because It's a regular model and does not inherit from any model. so I need to edit: username = user.username to username = user.email now when I refer to the custom authentication method it generates the token. but for access/request methods that need Authentication It returns 401 Unauthorized, Invalid signature. What is the problem? How should create a custom authentication … -
Atomic transactions in Django app in a for loop
In my django app I have a celery task which handles user-uploaded XLS file. Its being used to do something like "mass import" of data. In for loop I am processing each row - from each row I want to create one model instance object (so I will have multiple Model.objects.create(...) calls - for one row its possible that I will create multiple objects and its foreign keys). Is is possible in django to have an atomic transaction for whole for-loop? For example, if XLS contains 100 rows - and 90 of them are successful but 91 is not (because data in row is wrong) - is it possible to rollback previous 90 (or more) DB saves? My code looks like: workbook = xlrd.open_workbook(importobject.file.path) worksheet = workbook.sheet_by_index(0) processed_rows = [] omitted_rows = [] print('Mass import rows: ', worksheet.nrows) startrange = 0 if str(worksheet.cell(0, 0).value) == 'header': print('Omit first row as header row') startrange = 1 for rowno in range(startrange, worksheet.nrows): logger.info('Processing row {}:'.format(rowno)) for colno in range(worksheet.ncols): cell = worksheet.cell(rowno, colno) print('Row {}, Col {}:'.format(rowno, colno), str(cell.value)) # process call and row # validate and save object here - if not valid - rollback whole mass import #MyModel.objects.create()