Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Displaying value in the Frontend (React component) which is a foreign key in django models
I am learning django rest framework. I want to get author full name in JSON and not id, Below is GET request, is there a way if any? Created the Articles from admin site. I am trying to get the value in the Frontend with article.author [ { "id": 1, "article_title": "Premier League", "description": "The Premier League is the top level of the English football league system. Contested by 20 clubs, it operates on a system of promotion and relegation with the English Football League. The Premier League is a corporation in which the member clubs act as shareholders.", "created_at": "2019-10-02T08:59:24.883450Z", "author": 1 }, { "id": 2, "article_title": "Cricket in England", "description": "Cricket is one of the most popular sports in England, and has been played since the 16th century. Marylebone Cricket Club, based at Lord's, developed the modern rules of play and conduct.", "created_at": "2019-10-02T08:59:57.075912Z", "author": 2 }, ] Render function of a react component. article.author_id gives blank and article.author_id displays the author id as an integer. What should i return to display author full name? render() { return ( <Fragment> <h2>Articles</h2> <div > { this.props.articles.map(article => ( <div className="card" key={article.id}> <div className="card-body"> <div className="card-title"> <b>{article.article_title}</b></div> <div className="card-text"> {article.description}</div> … -
Image name get changed automatically for my Django project on Heroku
I had deployed my Django project on Heroku but when I am adding data to database then It changes my image to some other name but I don't know why it is happening. For ex. image name is img.jpg then after upload the new image name will be img_c34f.jpg ... some extra name is added automatically and due to this my image is not displaying on heroku website. My website is https://kharidarikaro.herokuapp.com/shop Please help..... -
Caching model properties in Django
In my Django app, I have a very repetitive query calling for item in self.schemaitem_set.all() very often. I feel this code is vastly inefficient. I am looking for a way to cash the query. Do you guys know how I could make the code below better? @property def gross(self): gross_sum = Decimal('0') for item in self.schemaitem_set.all(): gross_sum += item.gross return gross_sum @property def net(self): net_sum = Decimal('0') for item in self.schemaitem_set.all(): net_sum += item.net return net_sum @property def deposit(self): deposit_sum = Decimal('0') for item in self.schemaitem_set.all(): deposit_sum += item.deposit return deposit_sum @property def service_cost(self): service_cost = Decimal('0') if self.net > Decimal('150'): pass else: service_cost += Decimal('9.99') return service_cost @property def service_cost_vat(self): service_cost_vat = Decimal('0') if self.net > Decimal('150'): pass else: service_cost_vat += Decimal(f'{9.99*0,19}') return service_cost_vat @property def vat(self): vat = Decimal('0') for item in self.schemaitem_set.all(): vat += item.vat return vat -
How to solve "Account_user" not found in Django
I recently joined with an ongoing project which has done using the Django framework. When I run the following command it didn't create any migration file. py manage.py makemigrations --settings=hopster.settings.local When I run the following command as described in the readme file in the project. py manage.py migrate --settings=hopster.settings.local I receive the following error "django.db.utils.ProgrammingError: relation "Account_user" does not exist" It has local.py, dev.py, prod.py files base.py files instead of settings.py file. enter image description here enter image description here -
Link that does not exist
When I create new project in Django I have link from previous project. (I do not have "catalog" in new project... I create new db, may be it is problem with Chrome?) -
Looping through two arrays and adding the collection of each into new array without dups
I have two arrays that I want to loop through. Array A and Array B. I want to add the elements of both array into a new Array that contains the collection of all elements in that array without any duplication. This will be written in python. For Example A = [1,2,3,4] B = [1,5,6,7] Collection = [1,2,3,4,5,6,7] I was wondering if there's a faster and more efficient to do it without looping through each indexes and comparing it and then storing it. Because that's what I'm planning to do but I think it will take really long time given that I have about a couple thousand elements in each array. -
Image won't load to template in Django, but is stored to Media file
I'm trying to get a posted image to display on a Listview Blog application. Models.py from django.db import models class Post(models.Model): image = models.ImageField(upload_to='Post_images',null=True) title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) success_url = "post-detail" template_name = 'post_form.html' urls.py from django.conf.urls.static import static from django.conf import settings if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) home.html {% extends "blog/blogbase.html" %} {% block content %} {% for post in posts %} {% if Post.image %} <img src="{{ post.image.url }}" class="img-responsive"> {% else %} <span class="text-muted">No cover</span> {% endif %} {% endfor %} I see "No cover printed" on all of the posts indicatign that Post.image is not registering. settings.py MEDIA_ROOT = os.path.join(BASE_DIR, '/media') MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, '/static') STATIC_URL = '/static/' I think it has to do with the media root, because when I upload the image it saves to the media file. I think the html/urls/settings connection is messed up. -
Python / Django / channels.exception.ChannelFull() error
We constantly get a channels.exception.ChannelFull() error when we run our setup. Traceback Our setup consists of: Server Computer Client Computer The Client connects via websocket to the Server. It sends and receives to the Server over this link. The Server runs Django with Redis (channels-redis) and Channels2 in ASGI mode. When a client connects, the specific.channel_id is stored in our database. When a client disconnects, it is removed from our database. We run a BackgroundScheduler Job at 5 second intervals. This Job gets the clients in the DB and sends each one (via specific.channel_id) a message. The Client receives this message over websocket, processes it, and sends the requested data back to the Server where it is processed through a WebsocketConsumer. When developing, we ran short tests (<2 min). It wasn't until later when we were running longer tests (2+ mins) that we started to encounter this error. What might we have missed? -
Django Model matching query does not exist on newly created instances
So I been seeing the same question posted in different scenarios and I am unable to get mine to work. Basically trying to find a model instance if it already exists and create a new one if it doesn't - based on if the instance have the same field as the user's username I tried get_object_or_404 and even changing the primary key to a field in the model class. this is the models.py class Cart(models.Model): user = models.CharField(max_length=30) @classmethod def create(cls, user): user = cls(user=user) return user def __str__(self): """String for representing the Model object.""" return f'{self.id} {self.user}' this is the views.py def cart(request, pk): try: pizza = PizzaInstance.objects.get(id=pk) # get the topping(s) topping_1 = int(request.POST["topping1"]) topping = PizzaTopping.objects.get(pk=topping_1) # get the username user = request.user.username # check if the user already has an order try: order = Cart.objects.get(user=user) except KeyError: order = Cart.create([user]) order.save() I expected to see the order being saved and a new instance being created or even new instances added to the cart. error is get is - Cart matching query does not exist. Thank you! -
Django Rest Framework custom Permission Class with ManyToManyField
I am trying to write a permission class for django rest api view. this is my models from django.db import models from django.contrib.auth.models import User class Profile(models.Model): name = models.CharField(max_length=50) auth_user = models.OneToOneField(User, on_delete=models.CASCADE) class Group(models.Model): admin = models.ManyToManyField(Profile, related_name='g_admin') members = models.ManyToManyField(Profile, related_name='g_mess') I want only group admin can perform an action in particular pages, for this i am writing a permission class: class IsGroupAdmin(BasePermission): """ Allows access only to Group Admin. """ def has_permission(self, request, view): # return bool() do something here I am going through trouble to write the permission class to check if group admin or not. i am facing issue coz, this is many to many field. can anyone help me to write this? -
Datatables: How to show a message while data is exported (Excel, PDF, etc)?
I use DataTables buttons plugin to export my data to Excel, PDF, etc. But when many rows of data have to be exported the process sometimes takes a lot of time while the file is created, I like to show a message that indicates the download is in progress until the 'save as' window appears. I only have implemented the standard buttons configuration in the inicialization of datatable. Many thanks in advance for any idea or suggestion. -
Model field to hold any number of possible values from a finite list of choices
Say I have an abstract Product model with 'shipping' field on it, and I want that field to hold any number of possible values from a finite list of choices. So, if my choices list is: [ ('fedex', 'FedEx'), ('company2', 'Company 2'), ('company3', 'Company 3'), ... ] ...the model field should be able to hold one or more (or all) values from the list. What field should I use and how should I design my model? -
Django Student-Teacher ManyToMany relationship
I'm trying to model a Many to Many Teacher/Student relationship. Both the teachers and the students are objects of class Users (I edited out some unrelated fields). I'm having problems in understanding how the relationship should work. Basically, I want to be able to do something like u1 = User.objects.get(pk=<student pk>) u1.teachers.all() u2 = User.objects.get(pk=<teacher pk>) u2.students.all() After reading some docs and tutorials, this is how I defined the User class and the StudentTeacher relationship: class User(AbstractUser): is_student = models.BooleanField('student status', default=False) is_teacher = models.BooleanField('teacher status', default=False) teachers = models.ManyToManyField('self', through="StudentTeacher", through_fields=('student', 'teacher'), symmetrical=False) students = models.ManyToManyField('self', through="StudentTeacher", through_fields=('teacher', 'student'), symmetrical=False) class StudentTeacher(models.Model): teacher = models.ForeignKey(User, related_name='students', on_delete=models.CASCADE, limit_choices_to={'is_teacher': True}) student = models.ForeignKey(User, related_name='teachers', on_delete=models.CASCADE, limit_choices_to={'is_student': True}) This is what happens when I try to generate migrations (wiscom is the name of my application): wiscom.StudentTeacher.student: (fields.E302) Reverse accessor for 'StudentTeacher.student' clashes with field name 'User.teachers'. HINT: Rename field 'User.teachers', or add/change a related_name argument to the definition for field 'StudentTeacher.student'. wiscom.StudentTeacher.student: (fields.E303) Reverse query name for 'StudentTeacher.student' clashes with field name 'User.teachers'. HINT: Rename field 'User.teachers', or add/change a related_name argument to the definition for field 'StudentTeacher.student'. wiscom.StudentTeacher.teacher: (fields.E302) Reverse accessor for 'StudentTeacher.teacher' clashes with field name 'User.students'. HINT: Rename … -
User defined template Django
Is there a way to enable application users to create their own template within the django app? One example would be how MailChimp enables users to create their own custom email template. Currently i'm thinking of creating a model that captures information the user wants to display. that model can point to a template and populate it with the information the user wants to display. But is there a better way? -
Can't start gunicorn.service on VirtualBox with CentOS 8, Nginx and Django-Rest-Framework
Trying to deploy django application using gunicorn and nginx on CentOS. Following DigitalOcean tutorial: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-centos-7 But I have CentOS 8. I can run my application localy from virtualenv using: python manage.py runserver gunicorn --bind 0.0.0.0:8000 app.wsgi:application but then I try to run gunicorn.service I have status - failed. inside of systemctl status gunicorn.service I have started gunicorn deamon gunicorn.service: main process exited, code=exited, status=203/EXEC gunicorn.service: failed with result 'exit-code' Without this file I can't bind app.sock file as it not being created. My gunicorn.service looks like this app - is fictional application name :) admin - is a real user of this system [Unit] Description=gunicorn daemon After=network.target [Service] User=admin Group=nginx WorkingDirectory=/home/admin/app/portal/app ExecStart=/home/admin/app/env/bin/gunicorn --workers 3 --bind unix:/home/admin/app/portal/app/app.sock app.wsgi:application [Install] WantedBy=multi-user.target There is a tree of my project: app - env - portal -- client -- app --- documents --- fixtures --- images --- app ---- __init__.py ---- settings.py ---- urls.py ---- wsgi.py --- app_project ---- ... --- manage.py --- requirements.txt What can be done to make it work and that chan I check to find more clues why it doesn't work? Any input is welcome. Thanks -
Django using custom HTML form without Form model
I'm trying to use a custom login page and HTML form with Django but I'm not sure how to configure the application's urls.py. Here is my HTML form: <form method="POST" action="{% url 'users:login' %}"> {% csrf_token %} <div class="field"> <div class="control"> <select class="bureau_select" name="bureau" autofocus=""> <option value="FNC">Finance</option> <option value="HR">HR</option> <option value="CRT">Creative</option> </div> </div> <div class="field"> <div class="control"> <input class="input" type="text" name="username" placeholder="Name" autofocus=""> </div> </div> <div class="field"> <div class="control"> <input class="input" type="password" name="userpassword" placeholder="Password"> </div> </div> <button class="button">Login</button> </form> users is the application I've made to handle things like auth, changing user profile, etc. My users app looks like this: urls.py from django.urls import path from . import views app_name='users' urlpatterns = [ path('login/', views.CustomLoginView.as_view(), name='login'), ] views.py from django.shortcuts import render from django.urls import reverse_lazy from django.contrib.auth.views import LoginView from django.contrib.auth.forms import ( AuthenticationForm, PasswordChangeForm, PasswordResetForm, SetPasswordForm, ) from django.contrib.auth import authenticate, login class CustomLoginView(LoginView): # form_class = AuthenticationForm template_name = 'users/login.html' def login_user(request, user_id): if request.POST: username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. ... else: # Return an 'invalid login' error message. ... (following Django docs) I'm aware I can create this … -
Fix bootstrap table in weasyprint generated PDF
I'm trying to create a PDF table with Weasyprint in my Django website. The same table is shown in a html page and with Weasyprint. When I use bootstrap colors in the html version it shows correctly, but the colors are lost on the Weasyprint version. That is the only feature missing on the Weasyprint version, which works otherwise. views.py @login_required def scale_answer_pdf(request, scale_id): scale = get_object_or_404(UserScale, pk=scale_id) if scale.user == request.user or request.user.is_superuser: if scale.scale_meta.title == "Now": choices = NowLegend class ScaleForm(forms.ModelForm): class Meta: model = NowModel fields = labellist(NowLabels) labels = NowLabels if scale.scale_meta.title == "Child": choices = NowLegend class ScaleForm(forms.ModelForm): class Meta: model = ChildModel fields = labellist(ChildLabels) labels = ChildLabels form = ScaleForm(instance=scale) **html = render_to_string('diagnosis/scale_answer_pdf.html', {'form': form, 'scale':scale, 'choices':choices}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="{} - {} - {}.pdf"'.format(scale.scale_meta.title, scale.user.username, scale.created.strftime('%Y-%m-%d')) weasyprint.HTML(string=html, base_url=request.build_absolute_uri()).write_pdf(response, presentational_hints=True, stylesheets= [weasyprint.CSS(settings.STATIC_ROOT + '/css/sb-admin-2.min.css'), weasyprint.CSS(settings.STATIC_ROOT +'/css/all.min.css')]) return response** else: raise Http404 html for the PDF - the boostrap CSS works, and the table is also showing. But the colors from the table don't. I highlight the table parts that don't show colors {% extends "base_pdf.html" %} {% load i18n %} {% load staticfiles %} {% load get_item %} {% block content … -
During TestCase execution django.db.connection.cursor() SQL query returning data from main DB, not from the test one
Dears, I'm facing a problem which I have no more ideas how to resolve. I have need to test data which is returned by direct query from database. During execution of TestCase django.db.connection.cursor() is returning data from main database, not from test one, which contain fixtures prepared for this test purposes. I've tried to use both TestCase and TransactionalTestCase. I've tried debugging, checking variables values and found out that connection is pointed onto test database for sure. Do you know why it's returning data from main database? Is there any case when Django is copying data from main database to this created for tests purposes? I'm using: Python 3.6.5, Django 2.1, pytest 4.6.3, pytest-django 3.5 Thanks in advance for any support. -
How may seconds may an API call take until I need to worry?
I have to ask a more or less non-typical SO question and hope you don't mind. Right now I am developing my very first web application. I did set up an AJAX function that requests some data from a third party API and populates my html containers with the returned data. Right now I query one single object and populate 3 html containers with around 15 lines of Javascript code. When i activate the process/function by clicking a button on my frontend, it needs around 6-7 seconds until the html content is updated. Is this a reasonable time? The user experience honestly will be more than bad considering that I will have to query and manipulate far more data (I build a one-site dashboard related to soccer data). There might be very controversal answers to that question, but what would be a fair enough time for the process to run using standard infrastructure? 1-2 seconds? (I will deploy the app on heroku or digitalocean and will implement a proper caching environment to handle "regular visitors"). Right now I use a virtualenv and django server for the development and a demo server from the third party API which might be slowed … -
Problems with nginx+gunicorn resolving static content
I am setting up an environment with a django application (askbot opensource project), gunicorn and nginx. With nginx and gunicorn in different docker containers. This is my nginx configuration. server { listen 80; location /static { alias /askbot/static; } location /m { alias /askbot/static; } location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://askbot:8080/; } } If I run the django app on debug mode, everything is ok, I can go through nginx and I see how nginx is only invoking gunicorn for the dynamic content, and the static content is resolved locally. But, when I run the django application with debug false, nginx does not revolve the static content, and if I see the source code for the web page, I can see all the paths for the static content have changed, using somethign like "/m/CACHE...". I guess this is the reason why nginx cannot resolve the static content anymore. For example, when using debug mode equals false, this is one fragment of the html source code. <link rel="stylesheet" href="/m/CACHE/css/9275d0e5b87f.css" type="text/css" /> <link href="//fonts.googleapis.com/css?family=Open+Sans+Condensed:700&amp;subset=latin-ext" rel="stylesheet" type="text/css" /> <link href="//fonts.googleapis.com/css?family=Open+Sans+Condensed:700&amp;subset=cyrillic-ext" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="/m/default/media/jslib/modernizr.custom.js?v=1"></script> <script type="text/javascript"> And when running with debug equals false, … -
Backend in a hosting using Django and cpanel
I need help with my project, I am working on an application using Django as a backend and Angular as a fronted, I would like to know how to upload my Django backend to the hosting cpanel using MYSQL or PostgreSql. Or do I have to upload the full backend, or can I only upload the database? Thank you -
django rest framework offline documentation
I need to get the documentation for django rest framework for offline usage, Why? b/c I live in Ethiopia and the internet is too damn slow for me to go online just to the doc of APIView. So does anybody know of a link where I can find the offline version of the documentation? The pdf on readthedoc is outdated and empty and I can't seem to find any other alternative. Can anyone help? -
Django filter with manytomanyfield
This is my models class Person(models.Model): name = models.CharField(max_length=50) is_group_member = models.BooleanField(default=False) class Group(models.Model): members = models.ManyToManyField(Person) @receiver(post_save, sender=Group) def set_group_member_type(sender, instance, created, **kwargs): if created: # change the all group members' type I am trying to update is_group_member field with signal. When a group is created with members, then i will filter and retrieve all the person who are group member, then i will change the is_group_member value to True Can anyone help me to achieve this? -
Get response empty fields error after passing form to django rest api
I'm trying to build passing formdata to api page. But, the response is empty fields error. This is my vue template. <b-form @submit.prevent="postImitagram" id="post-form"> <b-form-input id="words" v-model="content" :state="state" trim /> <b-form-file accept="image/*" id="image" v-model="file" :state="Boolean(file)" /> <b-button block class="mt-5" type="submit" variant="primary">submit </b-button> </b-form> data() { return { content: "", file: null, error: '' } }, methods: { postImitagram(e) { let endpoint = "/api/posts/"; let method = "POST"; let formData = new FormData(); formData.append('title', this.content); formData.append('image', this.test, this.test.name); let context = {'title': this.content, 'image': this.file}; apiService(endpoint, method, formData).then(data => { }) } } function apiService(endpoint, method, data) { const config = { method: method || "GET" body: data, headers: { 'content-type': 'multipart/form-data', 'X-CSRFTOKEN': CSRF_TOKEN } }; return fetch(endpoint, config) .then(handleResponse) .catch(error => console.log(error)) } api model { "title": "", "image": null } and response status 400 bad request and 'title' and 'image' field are required. Creating a new one works fine when i post things in api page itself. What did I miss? Thank you in advance -
Django API Chart.js
Im would like to change the Chart Type from Bar Chart to Line Chart with an ajax call. For a start I saved the Chart Types (Bar, Line, Scatter) in a Model as follows: class Chart(models.Model): ctype = models.CharField(max_length=20, choices=choices, default='bar') choices = ( ('line', 'line'), ('bar', 'bar'), ('radar', 'radar'), ('bubble', 'bubble'), ('scatter', 'scatter'), ) and I pass them to view, serialising them and passing them on class ChartData(APIView): def get(self,request,format=None): dataset = Mobiles.objects.all() serializer = TypeSerializer(dataset,many=True) ctype = serializer.data data = { "ctype":[item["ctype"] for item in ctype], } return Response(data) to the api which returns: "ctype": [ "bar", "bar", "bar", ] And finally I retrieve them from the api, and set them equal to the chart type. var endpoint = '/api/chart/data/' var price = [] var labels = [] var ctype = [] $.ajax({ method: 'GET', url: endpoint, success: function(data){ labels = data.labels price = data.price ctype = data.ctype setChart() }, error:function(error_data){ console.log("error") console.log(error_data) } }) function setChart(){ var ctx = document.getElementById("myChart"); var myChart = new Chart(ctx, { type: ctype, data: { labels: labels, datasets: [{ label: '#', data: price, }] } }) } But the chart does not work Thank you for any help