Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ModuleNotFoundError from Heroku stored files
Running a blog app within Django which has been working fine until now, encountering an issue when I try to utilize any of the manage.py functions (collectstatic, migrate, runserver etc). I had to retrieve this build from a previous git which was going to a Heroku dyno so I believe a lot of the issues are results of Heroku editing path directories, although, I've scanned the code and see no issues. Current directory (previously working) home/myproject/myproject/mysite settings.py import django_heroku import dj_database_url import dotenv import os.path import django.core.mail # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Load enviroment variables from .env dotenv_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(dotenv_file): dotenv.load_dotenv(dotenv_file) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = {} DATABASES['default'] = dj_database_url.config(conn_max_age=600) # Password validation # … -
Export results from django-filter
I am trying to download results from a filtered view in Django 2.1. class ListadoEmployeeViewContactoFormularioColombia(FilteredListView): filterset_class = ListadoFormulariosFilter paginate_by = 10 model = ContactoInfoColombia fields = ['plataformaPrincipal', 'numeroPlataformaPrincipal'] #context_object_name = 'quiz' template_name = 'usuarios/listadoContactoEmployee.html' I have been looking for it but haven't found any responses so far. I have thought of creating another class where I get the request parameters like below but I don't feel this is a good way of getting the results. class PaymentExportView(FilteredListView): filterset_class = ListadoFormulariosFilter model = ContactoInfoColombia def render_to_response(self, context, **response_kwargs): # Could use timezone.now(), but that makes the string much longer filename = "{}-export.csv".format(datetime.now().replace(microsecond=0).isoformat()) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename) writer = csv.writer(response) writer.writerow(['nombre']) query = ContactoInfoColombia.objects.filter(numeroPlataformaPrincipal=self.request.GET.get("numeroPlataformaPrincipal")) for obj in query: writer.writerow([obj.nombre]) return response -
DRF: Conditially change serializer
I'm using Django 3.0 and I have a serializer using django-rest-framework. Let's say that for example I have a Forum object. Each forum has an owner that is a user. In my GET /forums/ endpoint, I'd like to just have the owner_id. However, in my GET /forums/<forum_id>/ endpoint I'd like to return the entire embedded object. Is there any way to have one serializer support both of these scenarios? -
Django - Are there security risks with not implementing is_valid and cleaned_data for forms in Django?
I'd prefer to implement A and C instead of B and D, because I'd like to implement my custom css for the form in the html css files without having to deal with forms.py or formatting the css in python. Do A and C present any security risks versus B and D? Are there any other downsides of using A and C? #A if request.method == "POST": user = authenticate(email=request.POST["email"], password=request.POST["password"]) #B if request.method == "POST": if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password'] user = authenticate(email=email, password=password) #C if request.method == "POST": contact_name = request.POST["contact"] #D if request.method == "POST": if form.is_valid(): contact_name = form.cleaned_data['contact'] -
Django models with Imagefield upload_to failed
I would like to upload to the directory below according to the file name. But it failed models.py from xxx import settings import os from pathlib import Path def get_file_path(instance,filename): li = ['index',"zxns","qyfw","login","cloud","about"] prefix = str(filename).split("_",1)[0] if prefix in li: target_folder = "/".join([settings.MEDIA_ROOT,"imgs",prefix]) if Path(target_folder).exists(): return "imgs/{0}".format(prefix) else: os.mkdir(target_folder) return "imgs/{0}".format(prefix) class XXX: photo = models.ImageField("图片",upload_to=get_file_path,null=True,blank=True) This is the result of the uploaded image, not the image format, and not under the corresponding directory. Hope someone can help me. Thanks. -
How to update background task status periodically in Django?
I have a django project which contains a long running process. I have used django-background-tasks library for this. It works but I want to create a pending page for users and display the status of the task. I should refresh that page every 60 seconds and update the status. How can I do that? Thank you. -
Cannot login in Django tests
Trying to write tests for a legacy Django 1.11 project. The project is using unittest package (I don't know if that's standard or a choice). I'm trying to use django.test.Client.force_login to test a view with LoginRequiredMixin but it does nothing. I have added print(self.request.user) to the mixin's dispatch method. It outputs AnonymousUser whether I use force_login or not. Why is it not working? The test (simplified for readability's sake): class CheckoutTest(TestCase): def test_successful_payment(self): user = UserAccount.objects.create(email='foo@bar.com', is_owner=True, is_customer=True) self.client.force_login(user) self.client.post('/subscription/buy/' + str(package.id) + '/', { ... redacted ... }) The view: class BuyPackageView(LoginRequiredMixin, View): def post(self, request, *args, **kwargs): ... redacted ... -
python django cant access the other objects only the first object can access`
In my HTML file i have script tag that contains a variable called nameSearch this will get the value from the textboxt HTML and Javascript: <!-- SEARCH BAR --> <section class = "search_bar" id ="search_bar"> <h1 class = "search_bar-h1">Find a Grave</h1> <form action="" class = "main_form"> <input type="text" id = "name" placeholder="Full Name"> <input type="button" name = "searchButton" value ="Start your Search" onclick="searched()"> </form> </section> <section> <script type="text/javascript"> function searched(){ let a = {{ nameSearched }}; nameSearched = document.getElementById('name').value; {% for names in name %} {% if nameSearched in names %} document.getElementById('dis').innerHTML = "{{ names.Last }}"; } else { document.getElementById('dis').innerHTML = "none"; } {% endif %} {% endfor %} } </script> <h1 id = "dis">test</h1> </section> i want to use the variable nameSearched in my if statement in python but i dont know if its posible because its always return nothing. -
How to play video from local folder in django?
I am working on Anomaly detection project working with django app.i tried to play video from local folder in django app but stuck in how to play video kindly help me if some one done this before?? -
Form is invalid
Django==3.0.4 class LoginForm(forms.Form): login = forms.CharField() password = forms.CharField() return_url = forms.CharField(widget=forms.HiddenInput()) class Login(FormView): template_name = 'login/login.html' form_class = LoginForm success_url = "/" <form method="post">{% csrf_token %} {{ form.login }} {{ form.password }} <input type="hidden" name="return" value="{{ return_url }}" /> <input type="submit" value="Login"> </form> The problem is that the form is invalid. In the picture it is visible what I input in the fields. Could you help me here? -
How To Create Range of Weight in django-fliter
So every other filter is working well but not able to do filter by Weight. Want to filter weight in range.. filters.py class ProductFilter(django_filters.FilterSet): category = django_filters.ModelChoiceFilter(queryset=Category.objects.all()) sub_Category = django_filters.ModelChoiceFilter(queryset=subCategory.objects.all()) city = django_filters.ModelChoiceFilter(queryset=City.objects.all()) karat = django_filters.ModelMultipleChoiceFilter(queryset=Karat.objects.all(), widget=forms.CheckboxSelectMultiple) product_weight= django_filters.RangeFilter() class Meta: model = Product fields = ['category','sub_Category','city','product_weight'] models.py class Product(models.Model): .... product_weight = models.DecimalField(max_digits=5, decimal_places=3) views.py def filter_search(request): products = Product.objects.all() f = ProductFilter(request.GET, queryset=products) return render(request, 'home/list.html',{'filter':f}) -
Can't Save Formset with Files using Django and CrispyForm
I am trying to use crispyforms with a formset so that I can allow people to upload multiple files in separate fields in a form. However, I cannot get my CampaignFile model to save. It saves the Campaign model just fine, but it saves it with an empty CampaignFile field instead of the file that has been uploaded. models.py class Campaign(models.Model): """A typical class defining a model, derived from the Model class.""" # Fields company = models.CharField(max_length=32) email = models.EmailField(help_text='This is where we will send your results') pub_date = models.DateTimeField('date_published', auto_now_add=True) # Metadata class Meta: ordering = ['company', '-pub_date'] # # Methods # def get_absolute_url(self): # """Returns the url to access a particular instance of MyModelName.""" # return reverse('model-detail-view', args=[str(self.id)]) def __str__(self): """String for representing the MyModelName object (in Admin site etc.).""" return f'{self.id}' class CampaignFile(models.Model): content = models.FileField( validators=[validate_file_type], upload_to='ad_testing_form/') campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, related_name='campaign') forms.py class CampaignFileForm(forms.ModelForm): class Meta: model = CampaignFile exclude = () widgets = { 'content': forms.ClearableFileInput(attrs={'multiple': False}) } CampaignFileFormSet = inlineformset_factory( Campaign, CampaignFile, form=CampaignFileForm, fields=['content'], extra=1, can_delete=True, labels={'content': 'Add Image/Video'} ) class CampaignForm(forms.ModelForm): class Meta: model = Campaign exclude = ['pub_date', ] def __init__(self, *args, **kwargs): super(CampaignForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = … -
django-concurrency: TriggerVersionField not creating trigger
Doing my first django project and following the tutorial. After creating my first model I ran manage.py makemigrations myapp and get an error from django-concurrency: WARNINGS: ?: (concurrency.W001) Missed trigger for field myapp.myclass.myfield Looking at the database, nothing was created, eg. no new table for the Model (django admin tables exist). The model uses django-concurency like this: version = TriggerVersionField(trigger_name='trg_component_version') What am I doing wrong? -
The variables for my Job model is not showing
I have created a Job model that contains Member and Manager info. It looks great imo. I created a class based view that translates the job if the user has one. Right now it's not showing. It just shows as a blank with an empty image file. I don't know what I did wrong or if I mistakenly used the wrong variables in the html file. Here's my views.py: from django.shortcuts import render from django.views.generic import ListView, CreateView from .models import Job from profiles.models import User # Create your views here. class jobs(ListView): model = Job template_name = 'users/user_jobs.html' context_object_name = 'jobs' def get_queryset(self): return Job.objects.filter(member__member=self.request.user) class createjob (CreateView): model = Job fields = ['member','title', 'description', 'file' My Models.py: from django.db import models from profiles.models import User # Create your models here. class Points (models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) points = models.IntegerField(default=0, null=False) def __str__(self): return self.user.username class Profile (models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png',upload_to='profile_pics') def __str__(self): return f'{self.user.username}Profile' class Manager (models.Model): name = models.CharField(max_length=30, blank=True, null=True) manager = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.name class Member (models.Model): name = models.CharField(max_length=30, blank=True, null=True) manager = models.ForeignKey(Manager, on_delete=models.CASCADE) member = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.name class Job (models.Model): manager = … -
Reverse for "URL" with arguments '(id)' not found. 1 pattern(s) tried: 'URL< int:ID >'
I'm stock with this error i can't get the "id" of my list i get an error. i'm trying to crete an UPDATE button to edit the data i add to my database. Here's my views.py in my apps from django.shortcuts import render, redirect from gomo_web_system.forms import UserForm,NewMasterForm from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.contrib.auth.decorators import login_required from gomo_web_system.models import masterList from django.contrib import messages def index(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) return render(request, 'gomo_web_system/main_menu.html') else: messages.info(request, 'Username or Password is incorrect') context = {} return render(request, 'gomo_web_system/index.html', context) def user_logout(request): logout(request) return HttpResponseRedirect(reverse('index')) @login_required def main_menu(request): return render(request, 'gomo_web_system/main_menu.html') @login_required def it_home(request): return render(request, 'gomo_web_system/IT/it_home.html') @login_required def it_master_list(request): master_list = masterList.objects.order_by('projectName') master_dict = {'master':master_list} return render(request, 'gomo_web_system/IT/it_master_list.html', context=master_dict) @login_required def it_create_master_list(request): form = NewMasterForm() if request.method == 'POST': #print('printring POST:', request.POST) form = NewMasterForm(request.POST) if form.is_valid(): form.save() return redirect('gomotion:master_list') context = {'form':form} return render(request, 'gomo_web_system/IT/it_add_master_list.html', context) def it_update_master_list(request, id): form = NewMasterForm() context = {'form':form} return render(request, 'gomo_web_system/IT/it_add_master_list.html', context) Here's my in my apps myapp/urls.py from django.conf.urls import url from gomo_web_system import views … -
Heroku DataTables warning: table id=vtable - Ajax error
I get this error when my app running in cloud server but in local server everything is working. How can I fixed this error? thank you. DataTables warning: table id=vtable - Ajax error. For more information about this error, please see http://datatables.net/tn/7 Table.html <table id="vtable" class="display" style="width:100%" data-server-side="true" data-ajax="/api/masterlist/?format=datatables"> <thead> <tr> <th>Employee ID:</th> <th>Company:</th> Ajax $(document).ready(function() { var table = $('#vtable').DataTable({ "processing": true, "serverSide": true, "scrollX": true, "ajax": { "url":"/api/masterlist/?format=datatables", "type":"POST" }, "columns": [ {"data": "Employee_Id"}, {"data":"Company"}, -
Issue with conda env while using uwsgi
I'm trying to run django server with uwsgi using anaconda python on Ubuntu 16.04.6 LTS. I've created a conda environment and installed all the dependencies. If I run the django server in dev(i.e python manage.py runserver), it's working without any issues. But, when I run it with uwsgi, I'm getting "ImportError: cannot import name _remove_dead_weakref stackoverflow" Error: Traceback (most recent call last): File "wsgi.py", line 11, in <module> from django.core.wsgi import get_wsgi_application File "/opt/myproj/venvs/api/lib/python2.7/site-packages/django/core/wsgi.py", line 2, in <module> from django.core.handlers.wsgi import WSGIHandler File "/opt/myproj/venvs/api/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 5, in <module> import logging File "/opt/myproj/venvs/api/lib/python2.7/logging/__init__.py", line 26, in <module> import sys, os, time, cStringIO, traceback, warnings, weakref, collections File "/opt/myproj/venvs/api/lib/python2.7/weakref.py", line 13, in <module> from _weakref import ( ImportError: cannot import name _remove_dead_weakref unable to load app 0 (mountpoint='') (callable not found or import error) I've set the path to anaconda $ echo $PATH /home/baji/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/baji/anaconda2/bin $ echo $PYTHONPATH /opt/myproj/venvs/api/bin/python The uwsgi command that I'm trying is $ /opt/myproj/venvs/api/bin/uwsgi -H /opt/myproj/venvs/api/ -i /opt/myproj/api/wsgi.ini This is the wsgi.ini file [uwsgi] module = wsgi:application master = true processes = 1 chmod-socket = 666 socket = /tmp/api.sock check-static = ./static wsgi-file = wsgi.py touch-reload = /tmp/api.txt buffer-size = 65535 post-buffering = 1 listen = 65535 vacuum = … -
json.dumps generates a string and returning it as dict is making a string inside another string, how to avoid it and get just a single string
class_object = ModelClass(title=entity_object['title'], entities_definition_key=entity_object['entities_definition_key'], orderId=entity_object['orderId'],uid = json.dumps( uuid.uuid4(), cls=UUIDEncoder)) ModelClass is mongoengine model class json_output = class_object.serializing_method() final_list.append(json_output) another_class_object = AnotherModelClass(workflowId=body['workflowId'],entities_list=final_list) another_class_object.save() save() to mongodb final_dict={} final_dict['entities_list'] = another_class_object.entities_list return HttpResponse(json.dumps({'entity_definition_dict':entity_definition_dict})) output-{'uid': "\"74b1900ccfbd44234563805ac0279d\""} -
Django: How to set up a test server with fixtures but Django models containing ForeignKeys?
I'm trying to directly test my client code (with requests module) to call my Django API. However, I want to automate this. What I'm trying to do is create a model with test server running. How am I able to populate my testdb with fixtures if one of my models has a ForeignKey? class Customer(models.Model): name = models.CharField(max_length=150) phone = models.CharField(max_length=12) email = models.CharField(max_length=250) class Load(models.Model): load_id = models.CharField(max_length=100, blank=True) invoice_id = models.CharField(max_length=100, blank=True) >customer = models.ForeignKey(Customer, on_delete=models.CASCADE, blank=True, null=True) notes = models.CharField(max_length=500, blank=True) carrier = models.ForeignKey(Carrier, on_delete=models.CASCADE, null=True, blank=True) driver = models.ForeignKey(Driver, on_delete=models.CASCADE, null=True, blank=True) active = models.BooleanField(default=True) -
ModelMultipleChoiceField not validating empty label
I have a ModelForm: class MCQuestionForm(forms.ModelForm): quiz = forms.ModelMultipleChoiceField( queryset=None, required=False, widget=forms.CheckboxSelectMultiple, help_text='Which tests this question applies to.') class Meta: model = MCQuestion exclude = () def __init__(self, *args, **kwargs): self.user = (kwargs.pop('user', None)) super(MCQuestionForm, self).__init__(*args, **kwargs) super_role = self.user.role subs_id = self.user.subordinates.values_list('role', flat=True) sub_roles = EmployeeType.objects.filter(pk__in=subs_id) cats = Category.objects.filter(groups=super_role) | Category.objects.filter(groups__in=sub_roles) self.fields['quiz'].queryset = Quiz.objects.filter(category__in=cats) Which I need to allow an empty choice on. I have tried initializing: self.fields['quiz'].choices = [('', 'None for now')] + \ [(quiz.pk, quiz.title) for quiz in self.fields['quiz'].queryset] and I have also tried: empty_label=False I have even tried: self.fields['quiz'].empty_label = 'Empty' But I always seem to get the form validation error: "" is not a valid value. How can I add an empty label here? -
Difference between Model serializer and base serializer django
What is the difference between a rest framework model serializer and base serializer. What are pros and cons of each. I referred the docs but couldn't understand in what scenario would each be used. -
python: can't open file 'manage.py': [Errno 2] No such file or directory docker-compose run
MY EGLISH IS NOT GOOD. SORRY! I tried run django project with code docker-compose -f local.yml run --rm django python manage.py runserver, but i had such problem "python: can't open file 'manage.py': [Errno 2] No such file or directory" in another computer this project runenter image description here but this code work docker-compose -f local.yml run django python enter image description here -
jQuery & Django, update div with different intervals
I've been making a Moon Info Display for a project of mine. I've been using Python to calculate the moon info values and used Django to send the info to the front-end. To update the page, I've been using a solution from Django, update part of the page. This allowed me to refresh the page automatically within an interval. However, now I wanted to update some part of the page with different interval, how would I do this? My jQuery code is as follows: $(document).ready(function() { $.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh var my_refresh = setInterval(function() { $('#moonphase').load('/getPhase/'); $('#alti').load('/getAlt/'); $('#az').load('/getAz/'); $('#elong').load('/getElong/'); $.get( '/getImage/', function(data){ img = parseInt(data); if (img === 1){ document.getElementById("imgphase").src = "{% static "lunarphase/0_0.png" %}"; } else if (img === 2){ document.getElementById("imgphase").src = "{% static "lunarphase/2_0.png" %}"; } else if (img === 3){ document.getElementById("imgphase").src = "{% static "lunarphase/5_0.png" %}"; } else if (img === 4){ document.getElementById("imgphase").src = "{% static "lunarphase/8_0.png" %}"; } else if (img === 5){ document.getElementById("imgphase").src = "{% static "lunarphase/14_0.png" %}"; } else if (img === 6){ document.getElementById("imgphase").src = "{% static "lunarphase/17_0.png" %}"; } else if (img === … -
Django contenttypes: null value in column "object_pk" violates not-null constraint
I'm trying to create an instance of my Comment model below. class Comment(models.Model): author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True ) body = models.TextField(blank=True) created_at = models.DateTimeField(auto_now_add=True) deleted_at = models.DateTimeField(blank=True, null=True) votes = JSONField(default=list, blank=True, null=True) total_vote = models.IntegerField(default=0) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_pk = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_pk") avatar_string = models.CharField(blank=True, max_length=100) I'm creating it by using a model form with the following definition. class CommentForm(forms.ModelForm): event = forms.ModelChoiceField(queryset=Event.objects.all(), required=False) class Meta: model = Comment fields = ["body", "author"] The form is being saved by this view function: def comment_create(request): print("foobar") comment_form = CommentForm(request.POST) print(comment_form.data) if comment_form.is_valid(): comment_form.save(commit=False) comment_form.author = request.user comment_form.content_type = ContentType.objects.get_for_model(Event) comment_form.content_object = comment_form["event"] comment_form.save() return HttpResponse() else: return HttpResponseBadRequest() How do I get it to populate the content_object field on my comment model from the ModelChoiceField in my form? -
How to use AbstractUser to customize django User model
I am working on a Django project and I am trying to customize the Django User model by inheriting AbstractUser in my models.py but when I run my server I get this error message. AttributeError: Manager isn’t available; ‘auth.User’ has been swapped for ‘django_starter_app.User’ What I am doing wrong here? below is my code models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): STUDENT = 1 TEACHER = 2 SECRETARY = 3 SUPERVISOR = 4 SITE_ADMIN = 5 USER_TYPE_CHOICES = ( (STUDENT, 'student'), (TEACHER, 'teacher'), (SECRETARY, 'secretary'), (SUPERVISOR, 'supervisor'), (SITE_ADMIN, 'site_admin'), ) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES) phone = models.CharField(max_length=12, blank=True, null=True) address = models.TextField(blank=True, null=True) on settings.py AUTH_USER_MODEL = 'django_starter_app.User'