Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to use mixins in Django templates like in Sass?
Say I have a template with a lot of repeated code. Very simply: <tr> <td>ITEM 1</td> <td>ITEM 2</td> </tr> Is there a way in Django to create a shortcut or a mixin that allows me to define a structure and pass a variable to it? E.g. {% mixin 'mymixin' %} <td>$value</td> {% end mixin %} And then use this in the html such as: <tr> {% use_mixin 'mymixin' 'ITEM 1' %} {% use_mixin 'mymixin' 'ITEM 2' %} </tr> I want to do this all in the template rather than mess about with my views so I can knock some wireframes up quickly. -
How to send token (JTW Token) headers from React Client to Django Channels2
It appears to be complex then I imagined. I am using React as client to connect websocket on Django Channels server. I have used JWT Auth for REST Api validation (using DRF). I have have not seen way to send Token using ws connection. I come across few suggestion to send as protocal - this did not work for me. There are other suggestion to send token as query string - I think it is not safe. I am looking better ways. -
integration of Django and mysql
first i have some questions :- A) can mysql and sqlite3 run on same server concurrently ? B) currently i m authenticating users using sqlite3 database. Was researching about integration of MYSQL and Django and found this. --> so After performing the steps in the link will my django app be using MYSQL db ? -->are these steps sufficient to move my database from sqlite3 to mysql ? --> if steps are performed as they are in the link, am i be using mysql db (but not sqlite3) through Django admin ? thnx for the help.! -
save() not updating the table in database
I have to update 2 tables in database every time user visit a page. this is working: order_order = OrderTable.no_objects.get(order_number=order_id) order_order.status = 'updated status' order_order.save() This is not working: (related with first table through foreign key) order_item = ItemsTable.objects.filter(order_id__order_number=order_id) for i in range(order_item.count()): order_item[i].qty = i + 5 order_item[i].qty_nextMonth = i + 30 order_item[i].save() Can anyone tell what's wrong in 2nd part of code. It's not updating the database. -
How to Show Navigation menu from Database in Django?
My category are not showing on header menu, Please let me the process for this. If i use code on home.html file then all category are showing on homepage but when i click on any category page it's not showing. Here are the models.py file... class WebCategory(models.Model): name = models.CharField(max_length=50, unique=True, verbose_name='Category name') slug = models.SlugField(verbose_name='Slug') title = models.CharField(max_length=165, null=True) metadesc = models.TextField(max_length=165, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'WebCategory' def save(self, *args, **kwargs): self.slug = slugify(self.name) super(WebCategory, self).save(*args, **kwargs) def __str__(self): return self.name class WebSubCategory(models.Model): category = models.ForeignKey('WebCategory', related_name='websubcategory', on_delete=models.CASCADE, blank=True, null=True, verbose_name='Select category') name = models.CharField(max_length=50) slug = models.SlugField(unique=True, null=True) title = models.CharField(max_length=100, null=True) metadesc = models.TextField(max_length=165, null=True) description = RichTextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'WebSubCategory' def __str__(self): return self.name class SubChildCategory(models.Model): subcat=models.ForeignKey('WebSubCategory', related_name='subchild', on_delete=models.CASCADE, blank=True, null=True, verbose_name='Select Subcategory') name=models.CharField(max_length=50) slug=models.SlugField(unique=True, null=True) title=models.CharField(max_length=100, null=True) metadesc=models.TextField(max_length=165, null=True) description=RichTextField(blank=True, null=True) created_at=models.DateTimeField(auto_now_add=True, null=True) updated_at=models.DateTimeField(auto_now=True) class Meta: verbose_name_plural="SubChildCategory" def __str__(self): return self.name And here are my views.py file def header(request): category_list = WebCategory.objects.order_by('-created_at')[:5] context_dict={'webcat':category_list,} return render(request, 'layouts/header.html', context_dict) Here are y urls.py file.. from django.urls import path, re_path from . import views from django.conf.urls.static import static from django.conf … -
Prints Invalid data on the screen
I have retrieved some data from model queries in django-python. I made a dictionary with all three results i queried. Now I want to convert it to json and pass it to FusionCharts object. I did so, but it prints out "invalid data" in place of the chart. How can I solve it? all_count = Offenses.objects.all().count() open_status = Offenses.objects.filter(status__iexact='OPEN').count() closed_status = Offenses.objects.filter(status__iexact='CLOSED').count() hidden_status = Offenses.objects.filter(status__iexact='HIDDEN').count() high1 = Offenses.objects.filter(magnitude=7).count() high2 = Offenses.objects.filter(magnitude=6).count() high3 = Offenses.objects.filter(magnitude=8).count() high4 = Offenses.objects.filter(magnitude=9).count() medium1 = Offenses.objects.filter(magnitude=5).count() medium2 = Offenses.objects.filter(magnitude=4).count() medium3 = Offenses.objects.filter(magnitude=3).count() low1 = Offenses.objects.filter(magnitude=1).count() low2 = Offenses.objects.filter(magnitude=2).count() total_high = high1+high2+high3+high4 total_medium = medium1+medium2+medium3 total_low = low1+low2 status_data = { 'open_status': open_status, 'closed_status': closed_status, 'hidden_status': hidden_status, } status_data_json = json.dumps(status_data) status = FusionCharts('doughnut2d', 'ex3', '600', '400', 'chart-2', 'status_data_json', """{ "chart": { "caption": "Offense Status", "showpercentvalues": "1", "aligncaptionwithcanvas": "0", "captionpadding": "0", "decimals": "1", "plottooltext": "<b>$percentValue</b> of offenses are <b>$label</b>", "centerlabel": "# Users: $value", "theme": "fusion" }, "data": [ { "label": "Opened offense", "value": "$open_status" }, { "label": "Closed offense", "value": "5300" } ] }""") -
Heroku failed to serve django admin static files - other static files work
I'm having trouble serving django admin static files from Heroku. Receiving 404 error for /static/admin/css/base.css - I have the same dir structure and the file base.css is inside it. Non admin static files work great This is how I serve static files: urlpatterns += patterns('', url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT, 'show_indexes': True}), url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}) Does anyone know how to solve this issue? -
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 …