Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework create object with many-to-many filed serializer
i can't create project object with many-to-many field to languages model, i need the best way to implement this, i have tried the django rest framework docs but it didn't work for me, is the language objects need to be created before the project object or DRF will handle this ?, this problem apper when i add the owner field then i needed to add the create method inside the ProjectSerializer to save the object owner but then this error Direct assignment to the forward side of a many-to-many set is prohibited. Use languages.set() instead. then i tried languages.set() steal not work models.py from django.db import models from django.contrib.auth.models import User class Language(models.Model): name = models.CharField(max_length=100, blank=True, default='') description = models.TextField() owner = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering = ['id'] def __str__(self): return self.name class Developer(models.Model): name = models.CharField(max_length=100, blank=True, default='') age = models.IntegerField() bio = models.TextField() created = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering = ['created'] def __str__(self): return self.name class Project(models.Model): name = models.CharField(max_length=100, blank=True, default='') stars = models.IntegerField() developer = models.ForeignKey(Developer, related_name='projects', on_delete=models.CASCADE) languages = models.ManyToManyField(Language) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering = ['stars'] def __str__(self): return self.name serializers.py from rest_framework import serializers from … -
Alternative to list_display for Django Admin?
I am working on a project when I need the list to automatically filter when a person views the list. In the model I have a field known as "active". If the country is an active country it should display in the list. The issue with list_filter is that it requires the user to sort by a certain field. I need this filter to happen as the page loads. (i.e an Automatic Filter) but also it should link to a page I have already created (not the default Django Admin List page). I'd be grateful if anyone could help :) -
django: send two ajax requests from the same initial form
I have a form generated in a templates that is triggering an ajax request to make calculations from the input data. Everything works fine. Here is what my setup look like: index.html <form method="POST"> {% csrf_token %} <label><h3>Input variables to calculate EOQ:</h3></label> <br> <br> <span style="color:black">Annual demand <input type="text" id="annual_demand"> <br> <br> <span style="color:black">Order cost <input type="text" id="order_cost"> <br> <br> <span style="color:black">Unit cost <input type="text" id="unit_cost"> <br> <br> <span style="color:black">Holding cost <input type="text" id="holding_cost"> <br> <br> <input id="ajax-call" type="submit" value="Calculate EOQ"> </form> <span style="color:black">Optimal EOQ<fieldset type="text" id="ajax"></fieldset></span> and my views.py look like the following: def index(request): return render(request, "index.html") @csrf_exempt def compute(request): annual_demand = request.POST.get("annual_demand") order_cost = request.POST.get("order_cost") unit_cost = request.POST.get("unit_cost") holding_cost = request.POST.get("holding_cost") result = m.sqrt((2*float(annual_demand)*float(order_cost))/(float(unit_cost)*float(holding_cost))) return JsonResponse({"operation_result": result }) Now I am trying to add a second calculation from the form input data, and I cannot successfully achieve that. I have tried including the calc inside of the "compute" view but it does not work, I have also tried generating a new view, so a second ajax call for the second calculation which was unsucessful either. Here is what I got: Added a new view for the second call: @csrf_exempt def compute2(request): annual_demand = request.POST.get("annual_demand") order_cost = request.POST.get("order_cost") … -
Couldn't use for loop in Django html
When the runserver and see it . It show {%block body%}{%endblock%}I was trying to show information from database using django and return html -
how to use webcam streaming from a django app?
I am trying to test webcam streaming in a simple Django app with just a views.py and a html. It shows just simple html text on screen without opening the webcam. What am I missing here? This is my views.py from django.shortcuts import render from django.views.decorators import gzip from django.http import StreamingHttpResponse import cv2 import threading class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) (self.grabbed, self.frame) = self.video.read() threading.Thread(target=self.update, args=()).start() def __del__(self): self.video.release() def get_frame(self): image = self.frame _, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() def update(self): while True: (self.grabbed, self.frame) = self.video.read() def gen(camera): while True: frame = camera.get_frame() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') @gzip.gzip_page def livef(request): try: cam = VideoCamera() return StreamingHttpResponse(gen(cam), content_type="multipart/x-mixed- replace;boundary=frame") except: # This is bad! replace it with proper handling pass def index(request): return render(request, 'home.html') and this is my home.html - <html> <head> <title>Video Live Stream</title> </head> <body> <h1>Video Live Stream</h1> <img src="{% url 'livef' %}"> </body> </html> -
Django Test.py django.db.utils.IntegrityError: UNIQUE constraint failed: books_book.id
when I run python manage.py tests I get this error as django.db.utils.IntegrityError: UNIQUE constraint failed: books_book.id it causes most of the other tests to fail Here are the full tests.py file: class BookViewTests(TestCase): self.user=get_user_model().objects.create_user( username='test', email='test@gmail.com', city='city', state='state', password='secret', is_active =True, id_2 ='96540845', pincode ='121006', education= 'NIT Kurukshetra', work = 'Wipro' ) self.user2=get_user_model().objects.create_user( username='test2', email='test2@gmail.com', city='city', state='state', password='secret', is_active=True, id_2 ='97173660', pincode ='272896', education = 'NIT Banglore', work = 'TCS' ) self.book =Book.objects.create( title='Shoe Dog', author='Phil Knight', genre ='Non-Fiction', owner =self.user, id ='88001198', is_approved=True available=True ) self.book2 =Book.objects.create( title='The Shining', author='Stephen King', genre ='Horror', owner =self.user2, id ='75777553', is_approved=True, available=True ) self.book4 =Book.objects.create( title='How to Win Friends and Influence People', author='Dale Carnegie', genre ='Self-help', owner =self.user2, id ='75777559', is_approved=False, available=False ) #book detail view def test_book_detail_view(self): self.client.login(username='test',password='secret') resp =self.client.get(reverse('book_detail',kwargs={'book_id':75777553})) self.assertEqual(resp.status_code,200) self.assertTemplateUsed(resp,'book_detail.html') resp1 =self.client.get(reverse('book_detail',kwargs={'book_id':88001198})) self.assertEqual(resp1.status_code,302) self.assertEqual(resp1.url,'/books/mybooks/') resp2 =self.client.get(reverse('book_detail',kwargs={'book_id':75777559})) self.assertEqual(resp2.status_code,404) My model: class Book(models.Model): id=models.SlugField(max_length=8,primary_key=True) genre_choices=[(i,i) for i in ['Biography','Business','Children','Classic','Comedy','Fantasy','History','Horror','Mystery','Mythology','Poetry','Religion','Romance','SciFi','Self-Help','Spirituality','Thriller','Non-Fiction','Fiction','Others']] title =models.CharField(max_length =255) author =models.CharField(max_length =255,validators=[alphabet_validate]) genre =models.CharField(max_length=100,choices=genre_choices) date=models.DateTimeField(auto_now_add =True) available =models.BooleanField(default =True) owner =models.ForeignKey(settings.AUTH_USER_MODEL,related_name ='book_owner',db_index=True,on_delete =models.CASCADE,) shared_with =models.ForeignKey(settings.AUTH_USER_MODEL,related_name='shared_with',on_delete=models.CASCADE,null=True,blank=True) slug = models.SlugField(verbose_name='Slug', null=True,blank=True,max_length = 200) How to solve this issue? Thanks in Advance. -
Comparing Datetime in Jinja
I am working with Django. I have following variable in my template: startingTime it's value come from database (DateTimeField) currentTime actually a variable that contain the value of datetime.datetime.now() durationInMinits actually a integer field, contain int value (in minutes) Now I need to determine if the difference between currentTime and startingTime is greater than durationInMinits or not. I have tried in my template.py like this: {% if startingTime < currentTime < startingTime + durationInMinits %} <p> This will display if current time is greter than startingtime, but duration is not over </p> {% endif %} But it gives error. Please suggest how can I compare time in jinja? -
Django: view content in with a certain id
enter image description hereenter image description herehow can I make sure that with a certain category I only get the films of that category? (I attach photos of the models and views) thanks in advance Sorry for the Englishenter image description here -
Django multi tenant shared schema implementation
I am starting a new project that requires a multitenant saas application. I have looked all around the internet and it seems that most of the articles around djnago multi tenant are focused on "same db different schema" approach. I am looking for a good examples and best practices for creating an application with the "same db same schema" approach. Topics: User model extension Authentication adjustments Cross tenat data queries protection Will appreciate any direction or assistance in that matter Thanks! -
What type of database is good for heavy django project
What type of database is good for Heavy Django project like Project Management System? -
Django Admin with custom form; calculate field not in form
In a normal (none admin view), if one has a field that is calculated by the backend, and not in the form, one would handle it like so: obj = form.save(commit=False) obj.calc_me = calc_at_now() obj.save Now say I have an admin model for Foo @admin.register(Foo) class FooAdmin(admin.ModelAdmin): exclude = ['calc_me'] How do I tell Django that when it saves Foo, to calculate the required field with obj.calc_me = calc_at_now() ? -
Django rest delete request error "The 'file' attribute has no file associated with it. "
I am using the Django rest framework for the API. I tried to make the file field optional. When I create the instance, it works properly, i.e., I can upload my data without a file. But when I tried to delete it, it shows the following error, The 'file' attribute has no file associated with it. In models.py file, I write as below, file = models.FileField(upload_to="%Y/%m/%d", null=True, blank=True) In serializer.py file, I write as below, class DataSerializer(serializers.ModelSerializer): file = serializers.FileField( required=False, allow_empty_file=True, allow_null=True) class Meta: model = DataIndex fields = '__all__' Can anyone please help me to solve this error? Thanks in advance. -
set command in windows not working for django SECRET_KEY | django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable
I set the SECRET_KEY with set command in the terminal, but nothing works set SECRET_KEY='9l=jjp#g0-mbdfsntqww91s9b^a!kj44ljl4f5h!+uoft' settings.py: from pathlib import Path import environ # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent env = environ.Env( DEBUG=(bool, False) ) READ_DOT_ENV_FILE = env.bool('READ_DOT_ENV_FILE', default=False) if READ_DOT_ENV_FILE: environ.Env.read_env() DEBUG = env('DEBUG') SECRET_KEY = env('SECRET_KEY') ALLOWED_HOSTS = [] .env: SECRET_KEY='9l=jjp#g0-mbdfsntqww91s9b^a!kj44ljl4f5h!+uoft' DEBUG=True So as you can read, the READ_DOT_ENV_FILE should be True to let django read the system variables from .env file, otherwise, it'll read the variables from the terminal (session) by defining them in it using the set command. In this case: set DEBUG=True set SECRET_KEY='9l=jjp#g0-mbdfsntqww91s9b^a!kj44ljl4f5h!+uoft' -
How to format index pagination url format django
Question is really similar to Django sitemap index pagination URL format but i didn't get the answer. So, i need my url to be like this /sitemap-products-3.xml, where 3 is page by paginator. My current working links: sitemap-products.xml?p=3 . It's was generated by generic function (index). I did some work, and links look like sitemap-products-3.xml , but in urls.py, I don't know how to pass number of page in paginator, cuz the link gives me 404. Thats my sitemap.xml (index func) def index(request, sitemaps, template_name='sitemap_index.xml', content_type='application/xml', sitemap_url_name='django.contrib.sitemaps.views.sitemap'): req_protocol = request.scheme req_site = get_current_site(request) sitemaps_lastmod = [] sites = [] # all sections' sitemap URLs for section, site in sitemaps.items(): # For each section label, add links of all pages of its sitemap if callable(site): site = site() protocol = req_protocol if site.protocol is None else site.protocol sitemap_url = reverse(sitemap_url_name, kwargs={'section': section}) absolute_url = '%s://%s%s' % (protocol, req_site.domain, sitemap_url) sites.append(absolute_url) sitemaps_lastmod.append(sitemaps[section].index_lastmod(sitemaps[section])) # Add links to all pages of the sitemap. for page in range(2, site.paginator.num_pages + 1): absolute_url = absolute_url.strip('.xml') sites.append('%s-%s.xml' % (absolute_url, page)) if len(sites) > len(sitemaps_lastmod): for x in range(len(sites)-len(sitemaps_lastmod)): sitemaps_lastmod.append(sitemaps[section].index_lastmod(sitemaps[section])) sitez = zip(sites, sitemaps_lastmod) return render(request, template_name, {'sitemaps': sitez}, content_type=content_type) and urls.py: path('sitemap.xml', sitemaps.index, {'sitemaps': sitemaps_pages}), path('sitemap-<section>.xml', sitemap, … -
How to fix this Openedx-Error : str has no attribute id
Hello I've recently upgraded openedx from Hawthorn -> Koa The procedure is : Hawthorn -> Ironwood -> Juniper -> Koa There is no error in migrating but as I was logging in, this error occurs: File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3.8/contextlib.py", line 75, in inner return func(*args, **kwds) File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/edx/app/edxapp/edx-platform/openedx/core/djangoapps/util/maintenance_banner.py", line 42, in _decorated return func(request, *args, **kwargs) File "/edx/app/edxapp/edx-platform/common/djangoapps/student/views/dashboard.py", line 830, in student_dashboard return render_to_response('dashboard.html', context) File "/edx/app/edxapp/edx-platform/common/djangoapps/edxmako/shortcuts.py", line 193, in render_to_response return HttpResponse(render_to_string(template_name, dictionary, namespace, request), **kwargs) File "/edx/app/edxapp/edx-platform/common/djangoapps/edxmako/shortcuts.py", line 183, in render_to_string return template.render(dictionary, request) File "/edx/app/edxapp/edx-platform/common/djangoapps/edxmako/template.py", line 83, in render return self.mako_template.render_unicode(**context_dictionary) File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/mako/template.py", line 481, in render_unicode return runtime._render( File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/mako/runtime.py", line 878, in _render _render_context( File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/mako/runtime.py", line 920, in _render_context _exec_template(inherit, lclcontext, args=args, kwargs=kwargs) File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/mako/runtime.py", line 947, in exec_template callable(context, *args, **kwargs) File "/tmp/mako_lms/c4ececd1e3f991d50ac3b7742d7479be/my-bootstrap/lms/templates/main.html.py", line 331, in render_body runtime._include_file(context, (static.get_template_path('header.html')), _template_uri, online_help_token=online_help_token) File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/mako/runtime.py", line 795, in include_file callable(ctx, **kwargs) File "/tmp/mako_lms/c4ececd1e3f991d50ac3b7742d7479be/header.html.py", line 34, in … -
Django how to properly add validation error message in views
I am trying to add validation in my views but error message not showing in my template. I am getting this page if user enter wrong input: views.py from django import forms from django.core.exceptions import ValidationError if request.method == "POST": if comment_form.is_valid(): if request.POST['name'] != username: raise forms.ValidationError('inc') -
could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?
I have a server running well on digital ocean but suddenly one error came as "" I am using nginx and gunicorn to server the application. It was running well but suddenly error appeared. I also did not make any change in application. Also this is what I am seeing when I write the command systemctl status postgresql -
How to have shared related name?
I am trying to create a model to represent travel time between two venues, so it has two foreign keys to the Venue model: class VenueTravel(models.Model): venue1 = models.ForeignKey('Venue', related_name='travel_times') venue2 = models.ForeignKey('Venue', related_name='travel_times') minutes = models.IntegerField(default=0, validators=[MinValueValidator(0)]) class Meta: unique_together = ('venue1', 'venue2') However, I'm having trouble making the migration for this model because the related name clashes for both fields. Usually, I would understand why, but since in this case the related object relation back to this object represents the same for both fields (all travel distances for the venue, no matter if it's venue1 of venue2), I don't really care about naming them differently. In fact, I'd want to name them the same. Is there any way I could do that? If you think there's a better way of modelling this use case, please feel free to make your suggestion. -
Using arguments to nested structures for filtering parents using django-graphene
I'm currently using Python & Django with Graphene to model my Graphql backend. My question is similar to this one on Graphene's repo https://github.com/graphql-python/graphene/issues/431. I'm also using graphene_django_optimizer library to improve performance. However I'm having a hard time understanding how to apply @syrusakbary proposed solution to my problem in my current scenario. Any help would be much appreciated This is the query I wanna execute getUser(userId: $userId) { id username trainings{ id name sessions{ id createdAt completedAt category } } } } The trainings are brought correctly, only the ones belonging to that specific user id. However all sessions for each training are brought for all users. I'd like sessions to also be specific to that single user. Here on my types.py are the relevant types class SessionType(DjangoObjectType): class Meta: model = Session fields = "__all__" convert_choices_to_enum = False @classmethod def get_queryset(cls, queryset, info, **kwargs): if info.context.user.is_anonymous: return queryset.order_by('-id') return queryset class TrainingType(gql_optimizer.OptimizedDjangoObjectType): class Meta: model = Training fields = "__all__" convert_choices_to_enum = False class UserType(DjangoObjectType): class Meta: model = get_user_model() fields = "__all__" Here are my relevant models: class Training(models.Model): name = models.CharField(max_length=200, help_text='Training\'s name') details = models.TextField(default="", help_text='Descriptive details about the training') course = models.ForeignKey("Course", related_name="trainings", on_delete=models.CASCADE) user … -
Chart.JS Datasets not showing in Django Project
I have a chart made with chart.JS on one of my django pages that is working perfectly. I tried to replicate it on another page with different data, and I can't seem to get the data points to show. The x axis labels show fine, but the y axis data sets aren't showing despite having the proper data set. <div class="chart-container"> <canvas id="annualChart"></canvas> <script> function toggleData(value){ const showValue = annualChart.isDatasetVisible(value); if(showValue === true) { annualChart.hide(value) } if(showValue === false) { annualChart.show(value) } } var years2 = {{annual_income.date|safe}} var revenue2 = {{annual_income.revenue|safe}} var grossProfit = {{annual_income.grossProfit|safe}} var researchAndDevelopment = {{annual_income.researchAndDevelopmentExpenses|safe}} var ctx = document.getElementById('annualChart'); var annualChart = new Chart(ctx, { type: 'line', // OPTIONS options: { maintainAspectRatio: false, plugins: { legend: { onClick: null, display: true, labels: { filter: function(item, annualChart) { return !item.hidden; } } }, }, scales: { yAxes: [{ stacked: true, gridLines: { display: true, color: "rgba(255,99,132,0.2)" } }], xAxes: [{ gridLines: { display: false } }] } }, // Data data: { labels: years2, datasets: [{ label: 'Revenue', data: revenue2, backgroundColor: 'rgba(255, 99, 132, 0.2)', borderColor: 'rgba(255, 99, 132, 1)', borderWidth: 1 }, { label: 'Gross Profit', data: grossProfit, backgroundColor: 'rgba(54, 162, 235, 0.2)', borderColor: 'rgba(54, 162, … -
Ignore `is_active` filed for custom user model
This is my custom user model: from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ class MyUser(AbstractUser): username = None is_staff = None is_superuser = None is_active = None email = models.EmailField(_('email address'), unique=True) status = models.PositiveSmallIntegerField(default=0) In settings.py file added: AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.AllowAllUsersModelBackend'] Then, when trying to login, getting error: This account is inactive. How to ignore is_active filed for my custom user model ? -
Disable public to download files like .env
How to disable download files in the root folder? For example when I go to the link; https://example.com/.env It will download the .env file, and https://example.com/projectfolder/settings.py It will download the settings.py file. How can I disable the download access? Thank you. -
Getting Error when trying to save Django Model to My Sql Dtatabase
Hi I'm getting this error when I try to save a model AttributeError: 'tuple' object has no attribute 'startswith. Basicly the program should show a list of all users. But even though in the table there are already some entries. The table I show on the Web side is empty and no error is shown. models.py: from django.db import models from django.db import connections class Users(models.Model): identifier = models.CharField(primary_key=True,max_length=100) accounts = models.TextField() group = models.CharField(max_length=100) inventory = models.TextField() job = models.CharField(max_length=100) job_grade = models.IntegerField() loadout = models.TextField() position = models.CharField(max_length=300) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) dateofbirth = models.CharField(max_length=100) sex = models.CharField(max_length=100) height = models.IntegerField() skin = models.TextField() status = models.TextField() is_dead = models.SmallIntegerField() phone_number = models.CharField(max_length=100) class Meta: db_table = "users", views.py from django.shortcuts import render from .models import Users # Create your views here. def show(request): newUser = Users( identifier = "abc", accounts = "[]", group = "admin", inventory = "[]", job = "police", job_grade = 3, loadout ="[]", position = "da", firstname = "swpw", lastname = "wwww", dateofbirth = "wolplwodokwowdüp", sex = "m", height = 78, skin = "[]", status = "[]", is_dead = 0, phone_number = "hallo",) newUser.save() return render(request,'acp/show.html',{'user':users}) -
I get error messages at terminal when I try to run manage.py runserver
I get error messages whenever I try to run manage.py, ModuleNotFoundError: No module named 'PyShop.settings', but I have this module, named "PyShop.settings" in my folder. C:\Users\uer\PycharmProjects\PyShop>python manage.py runserver Traceback (most recent call last): ... ModuleNotFoundError: No module named 'PyShop.settings' -
YAML text editor field in Django
I am looking for a convenient way to write and edit YAML in Django admin panel. Are there any text editors in django admin panel for YAML