Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Arranging data from django model in chartsJS
I have a chartsJS chart that takes numbers from a django model and uses the values to populate the chart. Is it possible to perform data organisation that will organise the values from highest to lowest in the data section of chartsjs: datasets: [{ axis: 'y', label: false, data: [ {% for number in numbers_in_sModel %} {{number.L1_Full_Sum}}, {{number.L2_Full_Sum}}, {{number.L3_Full_Sum}}, {{number.L4_Full_Sum}}, {{number.L5_Full_Sum}}, {{number.L6_Full_Sum}}, {{number.L7_Full_Sum}}, {{number.L8_Full_Sum}}, {{number.L9_Full_Sum}}, {{number.L10_Full_Sum}}, {% endfor %} ], -
Foreign Key Constraint Failure - Django. Manual assignment of Foreign Key to Model via POST Request
I'm working on a timesheet based system currently. I am getting a Foreign Key constraint failure when I am trying to assign the foreign key of one model to the other one. Here are the two models class Timesheet(models.Model): id = models.CharField(primary_key=True, max_length=50, blank=True, unique=True, default=uuid.uuid4) First_Name = models.CharField(max_length=32) Last_Name = models.CharField(max_length=32) Date_Created = models.DateField(auto_now_add=True) Creator = models.ForeignKey(User, on_delete=models.DO_NOTHING) Approved = models.BooleanField(default=False) #Work_Week = models.DateField() Company_Relationship = ( ('Supplier', 'Supplier'), ('Contractor', 'Contractor'), ('Employee', 'Employee') ) Worker_Type = models.CharField(max_length=32, choices=Company_Relationship) Total_Days_Worked = models.DecimalField(decimal_places=2, max_digits=3) class Meta: ordering = ['-id'] #unique_together = ['Creator', 'Work_Week'] def get_absolute_url(self): return reverse('timesheet-detail', kwargs={'pk': self.pk}) class InternalSheet(models.Model): id = models.CharField(primary_key=True, max_length=50, blank=True, unique=True, default=uuid.uuid4) Timesheet_id = models.ForeignKey(Timesheet, on_delete=models.DO_NOTHING) Working_For = ( ('7', 'Seven'), ('i', 'intelligent'), ('S', 'Sata'), ) iPSL = ( ('R16.1', 'Release 16.1'), ('R16', 'Release 16') ) Company_name = models.CharField(max_length=5, choices=Working_For) Company_name_change = models.CharField(max_length=5, choices=Working_For) Internal_Company_Role = models.CharField(max_length=10, choices=iPSL) DaysWorked = models.DecimalField(decimal_places=2, max_digits=3) Managers = ( ('GW', 'Greg Wood'), ('JC', 'Jamie Carson') ) ManagerName = models.CharField(max_length=8, choices=Managers) Approved = models.BooleanField(default=False) def get_absolute_url(self): return reverse('sheet-detail', kwargs={'pk': self.pk}) My issue is that I am getting a foreign key failure using this post request. class TimesheetCreateView(LoginRequiredMixin, CreateView): """ Creates view and send the POST request of the submission to … -
Tracking user activity on video on website
I am building a web application with React frontend and Django backend. There is a sign in option, and for each user, there is a video to see after they sign in. Since the video is long, not everyone will be seeing the video fully. How to track which sections of the video were watched by a particular user? For example, suppose a user A watched the video from 0:00 to 0:30, and then skipped to 1:30 and saw the video again from 1:30-3:00. How to get this information? Can this be done using some react library, or shall I use some feature of Django to do this. Any insight will be appreciated. -
django block content inside react component
i want to use a django html template that uses the header and footer of a react component i need the block content to show in between those two index.html : <body> {% block content %} {% endblock %} <div id="main"> <div id="root"> </div> </div> </body> with the above example i can only either render it above or below both. the Header and footer are both here import React from 'react'; import { Layout } from 'antd'; import { withRouter } from 'react-router-dom'; import { connect } from 'react-redux'; import * as actions from '../store/actions/auth'; const { Header, Content, Footer } = Layout; class CustomLayout extends React.Component { render() { return ( <Layout className="layout"> <Header> .... </Header> <Content > <div> {this.props.children} </div> </Content> <Footer> .... </Footer> </Layout> ); } } export default withRouter(connect(null, mapDispatchToProps)(CustomLayout)); -
How to constraint and validate Django m2m and foreign key fields
I have these models: class Client(models.Model): name = models.CharField(_('name'), max_length=255) info = models.OneToOneField('ClientInfo', verbose_name=_('info'), related_name='client', on_delete=models.PROTECT) is_active = models.BooleanField(_('is active'), default=False) class ClientInfo(models.Model): address = models.CharField(_('name'), max_length=255) other fields... class Result(models.Model): RESULT_CHOICES = (('N', _('Notified')), ('NL', _('No located'))) created_by= models.ForeignKey(OfficeEmployee, verbose_name=_('created by'), on_delete=models.PROTECT) result_type = models.CharField(_('result type'), max_length=2, default='N', choices=RESULT_CHOICES) other fields... class Visit(models.Model): client = models.ForeignKey(Client, verbose_name=_('client'), related_name='visit', on_delete=models.PROTECT) results = models.ManyToManyField(Result, verbose_name=_('results'), related_name='visit', blank=True) other fields... I want to add certain restrictions but I have difficulties with those models, since I hardly even see the need to add restrictions to related fields: How to avoid having "ClientInfo" entries if a "Client" has not created a relationship with it? How to prevent a "Result" entry of type "NL" being adde to existing "Visit" if the client it is related to is marked as not active I was thinking about using django built-in signals but, I don't know if the wanted restrictions can be defined in the class itself by overriding some validation methods or using Meta class. This last is because I'm affraid about if the use of signals is very expensive in terms of performance -
Django CSRF Token present but still getting 403 Forbidden Error
I am trying to set up a Django API that receives POST requests with some JSON data and basically sends emails to a list of recipients. The logic is rather simple: First I have the view for when I create a blog post. In the template, I include the csrf_token as specified on the Django Documentation. When I hit the submit button, behind the scene the create-post view, in addition to creating the post, makes a request (I am using the requests module) to the API which is charged with sending the emails. This is the piece of logic the sends the request to the API: data = { "title": new_post.title, "summary": new_post.summary, "link": var["BASE_URL"] + f"blog/post/{new_post.slug}" } csrf_token = get_token(request) # print(csrf_token) headers = {"X-CSRFToken": csrf_token} requests.post(var["BASE_URL"] + "_api/send-notification/", json=data, headers=headers) As you can see I am adding the X-CSRFToken to the headers which I generate through the get_token() method, as per the Django docs. However, the response in the API is a 403 Forbidden status CSRF Token not set. I have checked the headers in the request and the token is indeed present. In addition, I have been providing other routes to the API and I have been … -
Turn Django project into MVC(Model, View, Control) Structure by move all the apps model, view file in different folder
I want to Change my project structure so that my project follows MVC structure. Currently my project Structure: My_Ecom_project App_Login admin.py apps.py forms.py models.py urls.py views.py App_Order admin.py .... views.py App_Shop .... My_Ecom_Project init.py settings.py urls.py wsgi.py static ... templates ... mange.py I want to change this to: My_Ecom_project App_Login admin.py apps.py forms.py models.py urls.py views.py App_Order admin.py .... views.py App_Shop .... MVC Structure Model App_Login models.py App_Order models.py View Templates Controller App_Login views.py App_Order views.py My_Ecom_Project init.py settings.py urls.py wsgi.py static ... templates ... manage.py I want to add a MVC Structure folder like above and keep all models.py in a model folder, views.py in controller folder, templates in view folder -
Page not found for the template returned by TemplateResponse in Django
I have an app which is called sitepages which have three models I wanna pass their objects to a html page called listing.html which is inside templates/sitepages the sitepages urls.py contains: from django.views.generic import TemplateView from django.urls import include from django.urls import path from sitepages import views app_name = "sitepages" urlpatterns = [ path("news-events-listing/", views.view, name='listing'), ] the sitepages/views.py: from .models import Listing, Details1, Details2 from django.template.response import TemplateResponse def view(request): return TemplateResponse(request, 'sitepages/listing.html', { 'first_pages': Details1.objects.all(), 'seconde_pages': Details1.objects.all(), 'listing_page': Listing.objects.first(), }) in the root urls.py I added: path("", include("sitepages.urls", namespace='sitepages')) when I put in any template the following: <a href="{% url 'sitepages:listing' %}">Listing</a> it redirects me to the url /news-events-listing but no page is found and it gives me 404 error...what am I doing wrong? why the template is not returned? I should mention that I'm using wagtail for the whole site (I don't know if it's related) -
django static files not found-404
Could someone help me have a look at errors below: enter image description here my settings.py: ... STATIC_URL='/staic/' STATICFIELS_DIRS=[ os.path.join(BASE_DIR,'static') ] STATIC_ROOT=os.path.join(BASE_DIR,'static') my urls.py: ... urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) ... my project structure : [enter image description here][2] enter image description here I load static files this way: {% load static %} I have run 'python manage.py collectstatic' in cmd. Have tried many answers but still failed Could you help give some advice. Many thanks -
Django filter by related fields
I have some Django models like this: class Customer(models.Model): name = models.CharField(max_length=100) class Order(models.Model): title = models.CharField(max_length=100) ... customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='orders') I want get queryset with orders of particular customer. Should I use it?: Order.objects.all().filter(customer_id) Or it?: customer_object.orders.all() And why? -
Cannot login to ejabberd using ejabber_django bridge.py
I'm trying to authenticate ejabberd against django by using django-ejabberd-bridge.py method and always failed. I am using django management command Here is the code.. import struct import sys from django.core.management.base import BaseCommand class Command(BaseCommand): def read(self): (pkt_size,) = struct.unpack('>H', sys.stdin.read(2)) pkt = sys.stdin.read(pkt_size) cmd = pkt.split(':')[0] if cmd == 'auth': u, s, p = pkt.split(':', 3)[1:] if u == "wrong": self.write(False) else: self.write(True) self.read() def write(self, bool): if bool: sys.stdout.write('\x00\x02\x00\x01') else: sys.stdout.write('\x00\x02\x00\x00') sys.stdout.flush() def handle(self,*args, **options): try: while True: self.read() if not options.get("run_forever", True): break except Exception: self.stdout.write("Uups") It says that authentication failed for me. But, this code below works, and I am able to log in to xmpp client.. import sys import struct def read(): (pkt_size,) = struct.unpack('>H', sys.stdin.read(2)) pkt = sys.stdin.read(pkt_size) cmd = pkt.split(':')[0] if cmd == 'auth': u, s, p = pkt.split(':', 3)[1:] if u == "wrong": write(False) else: write(True) elif cmd == 'isuser': u, s = pkt.split(':', 2)[1:] write(True) elif cmd == 'setpass': u, s, p = pkt.split(':', 3)[1:] write(True) elif cmd == 'tryregister': u, s, p = pkt.split(':', 3)[1:] write(True) elif cmd == 'removeuser': u, s = pkt.split(':', 2)[1:] write(True) elif cmd == 'removeuser3': u, s, p = pkt.split(':', 3)[1:] write(True) else: write(False) read() def … -
Django jquery form validation without submit
I am developing a Django web application and am using Form with custom Validators (eg. for IP address). My web layout is a sidebar with list of some items (Models) which on click open the item editor in the main div (= changes the content of div). Something like this: <li class="nav-item"> <a class="nav-link" onclick="changeMainContent('{% url "edit" pk=item.id %}')"> {{ item.name }} </a> </li> The changeMainContent script looks like this: function changeMainContent(url) { $("#main-wrapper").load(url); } After clicking the link in sidebar div, the main-wrapper div content gets changed. No problem there. The form: class Item(forms.ModelForm): class Meta: model = models.Item fields = ['ip_subnet'] ip_subnet = IPAddrSubnetField(widget=forms.TextInput(attrs={'placeholder': 'IP subnet'})) IPAddrSubnetField has it's own validation implemented. In the first version of web, I had the linking without changing the content of one div, so whole page would reload. Therefore every subpage (.html file) had to contain all the elements (sidebar, main div, footer etc. ). With this new approach, the edit.html only contains the form, becauese sidebar/footer etc is already present. The problem is in the Django validation. In the first version it worked nicely, because it returned a filled form with possibly invalid fields in red, which was perfect. In this … -
How can I change the Procfile to run the Gunicorn process in a non-standard folder on Heroku?
This is my folder structure: george-paintings | application | george_paintings | george_paintings | - wsgi.py - Procfile In procfile i specify wsgi like web: gunicorn --pythonpath application.george_paintings george_paintings.wsgi And i got erorr while deploying my project to Heroku ModuleNotFoundError: No module named 'george_paintings' T tried different combinations of path in procfile and none of then worked -
pip freeze returning me warnings on windows 10
I am learning how to work on a django project. I have already created a project folder named my_first_project. Upon changing into the directory, I have then run the command django-admin startproject mywebsite. I am using anaconda and have set up a virtual environment using conda create --name mywebsite python=3.6. Activated it using activate mywebsite and did pip install django. However, when I do pip freeze, I get the following warnings: ***WARNING: Could not generate requirement for distribution -ip 20.2.3 (c:\python39\lib\site-packages): Parse error at "'-ip==20.'": Expected W:(abcd...) WARNING: Could not generate requirement for distribution - p (c:\python39\lib\site-packages): Parse error at "'-===p'": Expected W:(abcd...)*** Can anybody tell me what is wrong? Thank youuu -
Include a function with render in another view function
I want to design an error handler function in view and use it in different main functions in view. This error handler function will gather required error info, log the error to the system, and render those info to an error handler page. Codes in view.py look like: def error_manage(request, error_title, error_detail): error_time = datetime.now() info_table = {'error_title': error_title, 'error_detail': error_detail, 'error_time ': error_time , } logger.error(str(error_detail)) return render(request,'home/error_manage.html', {'error_title': error_title, 'info_table ': display_table}) def my_page_1(request): try: var1 = my_calculation_func() except Exception as ex: error_manage(request, "Unexpected Error Happened.", ex) var2 = my_calculation_func2() var3 = my_calculation_func3() return render(request,'home/my_page_1.html', {'var1': var1 ,'var2': var2 ,'var3': var3}) The problem here is that when the error occurs in var1, the program will jump into error_manage but will not stop in the return of this function and also will not successfully render into error_manage.html. it will later jump out of this function and continue run var2 and var3 until it meets the final return in my_page_1(). I know I can simply put the return statement in error_manage to my_page_1 under Exception. But this error handler will be used in many other functions in view.py and I don't want to repeat it over and over again. Is … -
django select_for_update deadlock issue
I am struggling with select_for_update() in django. I have code similar to this where each update statement uses select_for_update. It creates deadlocks. My questions is when the lock created by update_statement 1 will get release? Once the transaction get committed or when update_statment is completed. with transaction.atomic(): update_statement 1 update_statement 2 update_statement 3 update_statement 4 update_statement 5 -
Django /admin is redirecting me to another link without prior url admin customization
I am trying to set up django all-auth but it seems like after I logged out every attempt to access any page is failing. After I access 'admin/' for some reason is redirecting me to 'admin/login/?next=/admin/'. These are my urlpatterns: from django.contrib import admin from django.urls import path,include from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('account/',include('allauth.urls')), path('',TemplateView.as_view(template_name='All-auth/index.html')), ] -
What is the ideal number of workers in django-rq and python-rq?
I have a question regarding django-rq. It is pip-installed library that functions as a small layer on top of python-rq, which runs on a redis instance. Currently, I run all of the jobs on the default queue that uses database 0 on my local redis instance. I spin up workers by running the following script x times for x workers on the default queue: nohup ~/.virtualenvs/prod/bin/python3 manage.py rqworker default & nohup rq resume --url="redis://localhost:6379/0" I am operating on an 8 core / 32GB RAM machine. For every incoming request, a worker is required to process the job, which can often take anywhere from 3 to 60 minutes in a background process, that uses OpenCV, Tesseract and a few other APIs, making a few HTTP requests along the ay. How do I know the ideal number of rq workers I should be using? I am looking at the administrative panel and it says 8 workers. Is this the ideal number of workers that I should be using? Should I use 20? How about 100? How do I account for the following variables, in order to choose the correct number of workers I should spin up: number of incoming requests amount of … -
Get all tags posts that are liked by user
I am building a BlogApp and I am stuck on a Problem. What i am trying to do :- I am trying to show all the posts that contains all tags of posts that are liked by user. For Example If user_1 liked post_1 and that post contains tags of #test1,#test2,#test3 then show all the posts that contains these tags. models.py class BlogPost(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) post_title = models.CharField(max_length=500,default='') tags = TaggableManager() views.py def get_posts(request): posts = Post.objects.filter(tags__user__in=[user_id]) context = {'posts':posts} return render(request, 'mains/get_posts.html', context) BUT unfortunately this didn't work for me. I don't know what to do. Any help would be much Appreciated. -
Nedd To add Logo as a Watermark on Video in Python 2.7
I need to add a watermark on video. The Watermark will be the logo that is png file. I am using python 2.7 as project is built in Python 2.7 and Django. -
Do we have to host our Django site for our Flutter App backend?
Suppose I am creating a todo list app in Flutter. I have used Django to connect flutter's backend with the local host database. Now my API's(Django Rest Framework) are working fine if the is on local machine. But what if I deploy my Flutter app to Play Store? Then I need to host my Django site as well or it can be upon the local machine? -
How to make CRUD on a model through related model in Django Rest Framework?
For example: models class User(models.Model): nickname = models.CharField(max_length=30) email = models.CharField(max_length=60) class Group(models.Model): name = models.CharField(max_length=60) user = models.ForeignKey(User, on_delete=models.CASCADE) I have simplest serializers and view sets and I need to make CRUD part which on url would look like this: GET POST api/groups/{group_id}/users/ PUT PATCH DELETE api/groups/{group_id}/users/{user_id} so I can just see users which are related to the pointed group. Is there any provided or common way for such case? Thanks :) -
Django is not serving staticfiles
I would like to use django staticfiles, but unfortunately I can't get it to serve to images locally. This is what I have done so far: settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'content.apps.ContentConfig', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) When I do a print(os.path.join(BASE_DIR, 'staticfiles')) I see the correct local path. urls.py: from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.urls import path import content.views urlpatterns = [ path('admin/', admin.site.urls), path('', content.views.index, name='index'), path('/about', content.views.about, name='about'), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) templates: {% load static %} ... {% static "css/master.css" %} resolves to /static/css/master.css I am maybe missing something, just need an additional pair of eyes. Thanks. -
jsonb join not working properly in sqlalchemy
I have a query that joins on a jsonb type column in postgres that I want to convert to sqlalchemy in django using the aldjemy package SELECT anon_1.key AS tag, count(anon_1.value ->> 'polarity') AS count_1, anon_1.value ->> 'polarity' AS anon_2 FROM feedback f JOIN tagging t ON t.feedback_id = f.id JOIN jsonb_each(t.json_content -> 'entityMap') AS anon_3 ON true JOIN jsonb_each(((anon_3.value -> 'data') - 'selectionState') - 'segment') AS anon_1 ON true where f.id = 2 GROUP BY anon_1.value ->> 'polarity', anon_1.key; The json_content field stores data in the following format: { "entityMap": { "0": { "data": { "people": { "labelId": 5, "polarity": "positive" }, "segment": "a small segment", "selectionState": { "focusKey": "9xrre", "hasFocus": true, "anchorKey": "9xrre", "isBackward": false, "focusOffset": 75, "anchorOffset": 3 } }, "type": "TAG", "mutability": "IMMUTABLE" }, "1": { "data": { "product": { "labelId": 6, "polarity": "positive" }, "segment": "another segment", "selectionState": { "focusKey": "9xrre", "hasFocus": true, "anchorKey": "9xrre", "isBackward": false, "focusOffset": 138, "anchorOffset": 79 } }, "type": "TAG", "mutability": "IMMUTABLE" } } } I wrote the following sqlalchemy code to achieve the query first_alias = aliased(func.jsonb_each(Tagging.sa.json_content["entityMap"])) print(first_alias) second_alias = aliased( jsonb_each( first_alias.c.value.op("->")("data") .op("-")("selectionState") .op("-")("segment") ) ) polarity = second_alias.c.value.op("->>")("polarity") p_tag = second_alias.c.key _count = ( Feedback.sa.query() .join( CampaignQuestion, … -
How to retrieve data from comma separated values in Django admin
I am using a legacy database where many to many values are stored in an array like 1,2,3,4.. In django forms I am trying to use the below custom field to read multiple values. However they are getting stored as ['1','2'] instead of 1,2. Since it is an already existing database, I cannot go with many to many field. I have to store and retrieve values in the said format. class MultiSelectFormField(forms.MultipleChoiceField): widget = forms.CheckboxSelectMultiple def __init__(self, *args, **kwargs): self.max_choices = kwargs.pop('max_choices', 0) super(MultiSelectFormField, self).__init__(*args, **kwargs) def clean(self, value): if not value and self.required: raise forms.ValidationError(self.error_messages['required']) # if value and self.max_choices and len(value) > self.max_choices: # raise forms.ValidationError('You must select a maximum of %s choice%s.' # % (apnumber(self.max_choices), pluralize(self.max_choices))) return value I have changed my modelfield from ManytoManyField to Charfield in the process of achieving this functionality. In django admin page, if the dbtable has 1 value in the multiselectfield, django admin edit form page is showing the selected value, but if there are multiple values, nothing is getting populated... How do I achieve manytomany kind of functionality in this way--- like the column in the db field should have array of id's of the selected values.