Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
exclude vs filter using q
Can't understand how this is possible: A = object_list.filter( Q(sales__sale_starts__lte=today) & Q(sales__sale_ends__gte=today) ) # query inside filter catches 2 objects B = object_list.exclude( Q(sales__sale_starts__lte=today) & Q(sales__sale_ends__gte=today) ) # query inside exclude catches 3 objects, # though it is the same as previous # in other words: object_list has 20 objects, # A has 2 objects, and B has 17 objects Is there any difference in how filter() and exclude() working when using Q objects? Thanks. -
Django admin show proper child form based on parent field
I have the following models: #Abstact Parent Class import datetime class Media(models.Model): #Types of Media that Screens are capable to display in idle time MEDIA_TYPES = ( ('article', _('Article')), ('video', _('Video')), ('image', _('Image')), ) media_type = models.CharField(max_length=10, choices=MEDIA_TYPES, default=1) title = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) description = TextField(blank=True) duration = models.TimeField(default=datetime.time(00, 00)) screen = models.ForeignKey(Screen, on_delete=models.CASCADE) class Meta: verbose_name = _("Media") verbose_name_plural = _("Media") abstract = True class Image(Media): image = models.ImageField(upload_to='images/%Y/%m/%d/') class Meta: verbose_name = _("Image") verbose_name_plural = _("Images") #set media type to image def __init__(self, *args, **kwargs): self._meta.get_field('media_type').default = 3 super(Image, self).__init__(*args, **kwargs) class Video(Media): video = models.FileField(upload_to='videos/%Y/%m/%d') class Meta: verbose_name = _("Video") verbose_name_plural = _("Video") #set media type to video def __init__(self, *args, **kwargs): self._meta.get_field('media_type').default = 2 super(Video, self).__init__(*args, **kwargs) Parent class (Media) has a ForeignKey to Screen Model: class Screen(models.Model): #Types of Screens (To be replaced by dynamic screen types in app settings) SCREEN_TYPES = ( ('large', _('Large Touchscreen')), ('small', _('Small Touchscreen')), ('display', _('Display Screen')), ) # Fields screen_type = models.CharField(max_length=10, choices=SCREEN_TYPES, default='display') class Meta: verbose_name = _("Screen") verbose_name_plural = _("Screens") I want to edit Media as an inline of Screen in Django admin in such a way that when a … -
Django 1.11 - strange behavior in get_or_create
I see a strange behavior in get_or_create I have no record with slug='ian-osborn' >>> DjProfile.objects.get(slug='ian-osborn') Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/code.py", line 91, in runcode exec(code, self.locals) File "<console>", line 1, in <module> File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name frontend.models.DoesNotExist: DjProfile matching query does not exist. So I would expect get_or_create to istantiate a new DjProfile object but I get a Key (slug)=() already exists. error. >>> DjProfile.objects.get_or_create(slug='ian-osborn') Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 464, in get_or_create return self.get(**lookup), False File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 380, in get self.model._meta.object_name frontend.models.DoesNotExist: DjProfile matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: duplicate key value violates unique constraint "frontend_djprofile_slug_f04b026a_uniq" DETAIL: Key (slug)=() already exists. I'm running a similar query in a Django command from django.core.management.base import BaseCommand from frontend.models import DjProfile class Command(BaseCommand): ... what am I doing wrong? -
How do I avoid saving duplicate data? [Django]
I would like to prevent the form from being saved if the "Oficio" number already existed. Is there any way to do a data check before saving the data in the database? If "Oficio" number exists, show error by informing "Existing Oficio Number". This is my template that insert data: {% extends 'base.html' %} {% block body %} <form action="" method="post"> {% csrf_token %} {{ form.non_field_errors }} <div class="fieldWrapper form-group"> {{ form.numero.errors }} <label for="{{ form.numero.id_for_label }}">Número do Ofício:</label> {{ form.numero }} </div> <div class="fieldWrapper form-group"> {{ form.data.errors }} <label for="{{ form.data.id_for_label }}">Data:</label> {{ form.data }} </div> <div class="fieldWrapper form-group"> {{ form.para.errors }} <label for="{{ form.para.id_for_label }}">Para:</label> {{ form.para }} </div> <div class="fieldWrapper form-group"> {{ form.cargo_para.errors }} <label for="{{ form.cargo_para.id_for_label }}">Cargo Para:</label> {{ form.cargo_para }} </div> <div class="fieldWrapper form-group"> {{ form.assunto.errors }} <label for="{{ form.assunto.id_for_label }}">Assunto:</label> {{ form.assunto }} </div> <div class="fieldWrapper form-group"> {{ form.texto.errors }} <label for="{{ form.texto.id_for_label }}">Texto:</label> {{ form.texto }} </div> <button class="btn btn-group btn-primary" type="submit">Salvar</button> <a href="/oficio/">Voltar para a listagem</a> </form> {% endblock %} This is my view: def novo(request): if request.method == "POST": form = FormOficio(request.POST, request.FILES) if form.is_valid(): item = form.save(commit=False) item.responsavel = get_object_or_404(Responsavel, usuario=request.user) item.save() return render(request, 'salvo.html', {}) else: form = FormOficio() … -
how to set dynamic initial values to django modelform field
i'm kinda new to django, i need to set a dynamic initial value to my modelform field. i have a database field in my model name 'author' it has a foreignkey that connects it to the django user model. i need to automatically set this to the current user anytime a user fills in information into the form. from what i gathered about this problem, i'd have to define an init function inside the MyHouseEditForm below, i'm new to django and all the examples i've seen a pretty confusing. really nned help forms.py from django import forms from django.contrib.auth.models import User from .models import Myhouses class MyHouseEditForm(forms.ModelForm): class Meta: model = Myhouses fields = ('author','name_of_accomodation', 'type_of_room', 'house_rent', 'availability', 'location', 'nearest_institution', 'description', 'image') i need to set the value of 'author' to the current user anytime a user logs in. models.py from django.db import models from django.contrib.auth.models import User class Myhouses(models.Model): author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='author') Available = 'A' Not_Available = 'NA' Availability = ( (Available, 'Available'), (Not_Available, 'Not_Available'), ) name_of_accomodation = models.CharField(max_length=200) type_of_room = models.CharField(max_length=200) house_rent = models.IntegerField(null=True) availability = models.CharField(max_length=2, choices=Availability, default=Available,) location = models.CharField(max_length=200) nearest_institution = models.CharField(max_length=200) description = models.TextField(blank=True) image = models.ImageField(upload_to='profile_image') def __str__(self): return … -
Django channels: No module named 'asgiref.sync'
I am following this guide for channels tutorial (https://media.readthedocs.org/pdf/channels/latest/channels.pdf) and after adding channels to top of INSTALLED APPS, adding ASGI_APPLICATION = 'mysite.routing.application' to my setting file and creating following routing.py: # .../routing.py from channels.routing import ProtocolTypeRouter application = ProtocolTypeRouter({ # (http->django views is added by default) }) I am getting this error after running python manage.py runserver: ModuleNotFoundError: No module named 'asgiref.sync' I have following versions of libraries: Django (1.11.5) asgiref (1.1.2) channels (2.0.2) ... Can someone help me ? I am new to channels. -
Django Template--Conditional Based on The Current URL Path
I'm trying to exclude some content from the 'Blog' section of my site, and would like to exclude this info on any paths that start with /blog, which would include the main /blog page and and any other associate pages including blog/<blog-post> etc. I've looked at this post and tried some of the advice mentioned here but can't exactly get it to work. Here are my two blog URL's: url(r'^$', BlogListView.as_view(), name='blog'), url(r'^(?P<slug>[\w-]+)/$', blog_post, name='blog_post') and what I've tried (unsuccessfully) in my django template: {% url 'blog:blog_post' slug=slug as the_url %} {% if request.path == the_url %} <div>&nbsp;</div> {% else %} <div class="container"> <div class="nav-2"> <ul class="nav nav-pills"> {% block side_block %} {% get_category_list %} {% endblock %} </ul> </div> </div> {% endif %} I was able to get it to exclude the main blog page like this {% if request.path == "/blog/" %} <div>&nbsp;</div> {% else %} but having an issue with the actual blog posts. any ideas? -
How should I unit test middlewares in Django 2.0.2
I've been trying to test my custom middleware using this example however I'm getting this error message: missing 1 required positional argument: 'get_response'. How should I pass the parameter since according to this information __ init __ method in Django middleware must declare a get_response input, which represents a reference to a prior middleware class response. -
Custom Meta Sort
This is my meta model info (Django 2). class Meta: managed = True db_table = 'mydb' ordering = ['in_stock', '-type', 'sale_price', 'name'] I was wondering if I can evaluate the in_stock attribute dynamically. For example: If in_stock=0, then in_stock=50, else in_stock=1. My model should sort per the result of my conditional. Is this even possible? -
gunicorn,django ImportError: No module named application
Can anyone help? I recently merged migrations, then ran manage.py migrate, ran into an error, deleted the migrations because I didn't need them (models that I ended up not using). Now I am stuck with this error. Can anyone help? I searched elsewhere and didn't find anyone with the same error. This is just running the code by hand (as you see below). My whole site has a 502 bad gateway error; I imagine it is related to what you see below ♥root@ubuntu-2gb-nyc3-01:/home/mike/movingcollage#gunicorn --bind=unix:/home/mike/movingcollage/movingcollage.sock movingcollage.wsgi.application --preload /usr/local/lib/python2.7/dist-packages/djstripe/__init__.py:23: UserWarning: dj-stripe deprecation notice: Django 1.7 and lower are no longer supported. Please upgrade to Django 1.8 or higher. Reference: https://github.com/pydanny/dj-stripe/issues/275 warnings.warn(msg) Traceback (most recent call last): File "/usr/local/bin/gunicorn", line 11, in <module> sys.exit(run()) File "/usr/local/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 74, in run WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() File "/usr/local/lib/python2.7/dist-packages/gunicorn/app/base.py", line 185, in run super(Application, self).run() File "/usr/local/lib/python2.7/dist-packages/gunicorn/app/base.py", line 71, in run Arbiter(self).run() File "/usr/local/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 57, in __init__ self.setup(app) File "/usr/local/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 113, in setup self.app.wsgi() File "/usr/local/lib/python2.7/dist-packages/gunicorn/app/base.py", line 66, in wsgi self.callable = self.load() File "/usr/local/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/usr/local/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python2.7/dist-packages/gunicorn/util.py", line 356, in import_app __import__(module) ImportError: No module named application -
Getting and setting data in sqlite in django
So, I'm trying to update some information in sqlite db in django. What I wanna do is the following: 1. I get existing data from the db 2. Based on the data, I do some calculations on the given data to make new data. 3. After getting the new data, I put them in the sqlite db. I wanna do the process above manually or automatically. I'm currently using django framework to make some web application. In my website, there's a bunch of stores having customer reviews, and I wanna make popularity points of each store based on calculations of the reviews. How can I update data of a column based on data of another column? -
How can I launch a new terminal to track my shell script triggered from Django?
I'm working on a Django 2.0.2 project built in python 3.6.3 which necessitates forking off a shell script as a background child process. This is currently how I'm currently triggering it: import subprocess subprocess.Popen(./master.sh) Unfortunately, this doesn't echo to the same terminal as the Dango server like other processes on the site. The pipeline outputs to a log.txt file after completing, but as some jobs will take hours to complete, I'd like a way to follow the job as it happens by spawning a new terminal. I have tried using gnome-terminal commands, but so far I've had no successful readout. -
How to create Multi User Account
Please am really need you guys help on how to use Django to create Multi-user Account. e.g Student, Lecturers, and Department login page(Admin).. in this system the department will be the Admin to register the lecturers inorder to have access and why the Student register on their own... Am design a project titled Online Assignment Submission System (it is my final year Project)... I really need you guyz help... on how to go about it using Django. -
How do I filter access to certain views based on time?
I am trying to create a system whereby users can only access a certain page at a time which they have booked. Users who have not booked access to this time will not be able to access the page. Essentially the page will only be available to users once they have booked! I am trying everything I can to do it see my files below. models.py class Booking(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) daterequired = models.DateTimeField(default=timezone.now) students = models.CharField(max_length=200) length = models.CharField(max_length=40, blank=True) def __str__(self): return str(self.user) forms.py class BookingForm(forms.ModelForm): class Meta: model = Booking exclude = ['user', ] widgets = { 'students': forms.TextInput(attrs={'placeholder': 'Number of Students'}), 'length': forms.TextInput( attrs={'placeholder': 'Time needed in hours'}), } views.py @login_required def choose(request): pod = Pod.objects.all() booking = Booking.objects.filter(user=request.user) bookingtime = booking.daterequired.strftime("%Y-%m-%d %H:%M:%S") currenttime = datetime.now().strftime("%Y-%m-%d %H:%M:%S") timedifference = currenttime - bookingtime if timedifference <= booking.length: return render(request, 'choose.html', {'pod': pod, 'booking': booking}) else: return HttpResponse("<p>NO ACCESS</p>") I am not sure how far off I am at the moment but would appreciate any help in the right direction. Thanks guys! -
Django not passing data to views on POST request
I've created a dropdown menu that is supposed to pass data to a view that'll help filter a queryset. However, it doesn't seem like the data is actually being passed to the view. Below is the relevant code I've written. template.html <!-- Query based content for dropdown menu --> <form method="POST" action="{% url 'property-selected' %}" id="property-select"> {% csrf_token %} <select class="dropdown-content" onchange="this.form.submit()" name="property-select"> {% if current_user_meters %} <option disabled selected> -- select an option -- </option> {% for meter in current_user_meters %} <option class="dropdown-menu-option" value="{{meter.id}}">{{meter.name}}</option> {% endfor %} {% else %} <option>You don't have any meters</option> {% endif %} </select> </form> views.py def property_selected(request): if request.method == 'POST': selection = request.POST.get('property-select') current_user_groups = Group.objects.filter(id__in=request.user.groups.all()) current_user_properties = Property.objects.filter(groups__in=current_user_groups) current_user_meters = Meter.objects.filter(meter_id__in=current_user_properties) selected_meters = Meter.objects.filter(name=selection) selected_meter_data = MeterData.objects.filter(name=selection).order_by('date') return render(request, 'properties/property-selected.html', { 'current_user_meters': current_user_meters, 'selection': selection, 'selectected_meters': selected_meters, 'selected_meter_data': selected_meter_data, }) for the querysets in the views file, the "selection" variable doesn't seem to be getting anything, which is where I want the data from the POST request to go. I want the data from the POST request to go there so my "selected_meters" and "selected_meter_data" queries will work as intended. Thanks! -
EditForm won't save the image from my ImageField
So basically I am just trying to change the data of my user. Everything works in the edit form, except that the image won't get saved. It gets passed in the form, my form has enctype enabled and also added request.FILES in the view, but nothing seems to work. When debugging, I only get that my form has no such 'photo' attribute. class StudentEditForm(forms.ModelForm): email = forms.EmailField(required=True, widget=forms.EmailInput(attrs={'placeholder': "E-mail Address", 'class': 'email'})) name = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={'placeholder': "Name", 'class': 'name'})) surname = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={'placeholder': "Surname", 'class': 'surname'})) photo = forms.ImageField(required=True, error_messages={'required': 'A profile picture is required.'}, widget=forms.FileInput(attrs={'class': 'profile_pic'})) phone = forms.CharField(max_length=15, required=True, validators=[RegexValidator(regex='^[0-9+]+$', message='Not a valid phone number.')], widget=forms.TextInput(attrs={'placeholder': "Phone Number", 'class': 'phone'})) class Meta: model = Student fields = ('email', 'name', 'surname', 'phone', 'photo') if request.method != 'POST': form = StudentEditForm(instance=student) else: form = StudentEditForm(request.POST, request.FILES, instance=student) if form.is_valid(): user.email = form.cleaned_data['email'] user.first_name = form.cleaned_data['name'] user.last_name = form.cleaned_data['surname'] user.save() form.save() return redirect('index') {% if user.is_student %} <div id="profile-edit"> <a id="close" href="{% url "index" %}"><i class="fas fa-times"></i></a> <form class="main-form" method="post" enctype="multipart/form-data"> {% csrf_token %} <h3 id="sign-title">Edit Profile</h3> <p class="field"> {{ form.email }}</p><br> <p class="field"> {{ form.name }}</p><br> <p class="field"> {{ form.surname }}</p><br> <p class="field"> {{ form.phone }}</p><br> <label id="file1" … -
Django POST shows in form, but doesn't come through to the next view
I have a simple form such as: <form action = "{% url 'endresult' %}" form method = "POST"> {% csrf_token %} <div class="well"> <h4 style="margin-top: 0"><strong> Student Details </strong></h4> <div class="row"> <div class="form-group col-md-4"> <label/> Student ID <input class="form-control" type="text" name = "studentpost" placeholder= "{{student.studentid}}" readonly> </div> </form> </div> The student ID does show up in my form, but when I try to get the results from endresult it shows up as a blank, if i try to call the studentid i get none. Why is this? def endresult(request): postedstudent = request.POST.get('studentpost') print(f"postedstudent : {postedstudent }") studentid = request.POST.get('student.studentid') print(f"studentid : {studentid }") return render(request, 'submitted.html') Here is my output: posteduser: ntname: None -
Error in accessing file in S3-Bucket using Django
I am using Django-mailbox, AWS-EC2 instance and AWS-S3 , So I am trying to send an attachment with mail and receive it on S3 bucket and I am successful to achieve this. Next while accessing that attachment file from saved path, it showing me following error, however file is saved successfully in given path, you can see in folder dir. My folder structure is as follows Let me know if any further details needed. -
How to pass values into python script from django views
When a user logins in, they provide a username, password, serverid. I want to pass that into a script that would connect them to a server. How do I do so and also get the output of the script to see if it was executed properly? -
Django use queryset in template
I want to check a field(=is_seller) of the table(=UserProfileInfo) and if it has some value(=0) , make some part of template disabled and these are my codes : models.py : class UserProfileInfo(models.Model): user=models.OneToOneField(User,related_name='profile') companyname=models.CharField(blank=True,null=True,max_length=128,verbose_name=_('companyname')) phone_regex = RegexValidator(regex=r'^\d{11,11}$', message=_(u"Phone number must be 11 digit.")) cellphone = models.CharField(validators=[phone_regex], max_length=17,verbose_name=_('cellphone')) tel = models.CharField(blank=True,null=True, max_length=17,verbose_name=_('tel')) state=models.CharField(,max_length=128,verbose_name=_('state')) city=models.CharField(,max_length=128,verbose_name=_('city')) address=models.CharField(blank=True,null=True,max_length=264,verbose_name=_('address')) is_seller=models.CharField(blank=True,null=True, max_length=2,verbose_name=_('seller')) def __str__ (self): return self.user.username class Meta: verbose_name=_('UserProfileInfo') verbose_name_plural=_('UserProfileInfos') view.py: def stock(request): st_form=StocksForm(None) is_seller=UserProfileInfo.objects.filter(user=request.user).values("is_seller") if request.method == "POST": st_form =StocksForm(data=request.POST) print("<<<<<<<<<<<"+str(is_seller)) if st_form.is_valid(): instance=st_form.save() id_name=(st_form.cleaned_data.get("name")) instance.name=StocksName.objects.filter(id=id_name).values("name")[0]['name'] #becouse of autocomplete it was saving the value by its id and i converted to name instance.user=request.user instance.save() messages.success(request,"SUCCESSFUL" ,extra_tags="savestock") else: messages.error(request, "ERROR!") else: st_form=StocksForm() return render(request,'BallbearingSite/stock.html',{'stocks_form':st_form,'seller':is_seller}) template.html : it doesnt work and i dont know how to correct it : {% for item in seller %} {% if item.is_seller=="0" %} <p>show some message</p> {% endif %} {% endfor %} -
Pass from login a variable to know is the first time the user login
First time the use logins, I wan to show him a multi step setup. How can I pass from login a variable to know is the first time the user login ? -
What is better for an embedded device - Node.js or Django?
Background: I'm currently developing a project on Raspberry Pi - for now I want to gather data from a sensor and display it on a web page with some neat graphs and stuff like that but I plan to expand it sooner or later. I'm facing a dilemma right now: which framework should I use? I learned about Node.js from this book and I really like the concept - also the authors are giving quite a few reasons why it's good for embedded devices. On the other hand, I learned about the existence of Django and since I'm working with python on a daily basis I thought using it would be a better idea. I'm torn apart now - I'd like to use technology that would be most suitable in embedded world (and which would educate me the most) and yet I'm kinda afraid to jump into deep waters of a language I don't really know (JavaScript). If somebody with more experience with web technology and embedded devices could help me out, that would be most helpful! In short: What would be the best option for an embedded device (and for me): Node.js or Django? -
How do I handle files stored as blob from react-dropzone
When I add files to the file field using react-dropzone and pass it to a remote Django backend, it passes the values: {u'preview': u'blob:http://127.0.0.1:8080/17c3c181-e361-44f1-8ee8 -6476847aeffb'} . How do I handle that as a file for uploading to S3 using a Django Rest API backend? -
Can't Access the file from path Aws + Django
I am using Django-mailbox, an AWS-EC2 instance and AWS-S3 , I am trying to send an attachment with mail and receive it on S3 bucket and I am successful to achieve this. Now while accessing that attachment file from path, it is shows me following error, how file is saved successfully in given path My folder structure is as follows Let me know if any further details needed. -
Django Redirect Solution
In django I am having problems redirecting. Here is my urls.py for the app: urlpatterns = [ path('bkb/', views.index, name = 'index'), path('bkb/<int:department_code>/', views.lcdcl, name ='lcdcl'), path('bkb/<int:department_code>/<int:cl_id>/', views.lcdcl2, name ='lcdcl2'), path('bkb/addcl2/' , views.addcl2, name='addcl2'), path('bkb/<int:department_code>/<int:cl_id>/<int:edit_id>/edit/', views.editdata, name ='editdata'), path('bkb/<int:dept_code>/<int: id>/revers/', views.revers, name ='revers'), here is my view.py for edit data: def editdata(request, department_code, cl_id, edit_id): editdata = CL2.objects.get(pk=edit_id) cl2_info = LCD.objects.get(pk=cl_id) a = department_code b = cl_id if request.method == "POST": forms = CL2Form(request.POST, instance=editdata) if forms.is_valid(): editdata = forms.save(commit=False) editdata.save() return redirect('/bkb/lcdcl2/') else: forms = CL2Form(instance=editdata) context = {'forms' : forms} return render(request, 'bkb/lcdcl2form.html', context) My question is: I want to go to path('bkb/<int:department_code>/<int:cl_id>/', views.lcdcl2, name ='lcdcl2'), from return redirect('/bkb/lcdcl2/') in views.