Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In django users should be able to see only the files which they uploaded
I'm working on a simple django website that provides its users with the ability to upload files. Right now all the uploaded files can be seen by every authenticated user. How can I make it so that the users can only see the files which they uploaded only? My models: from django.db import models from django.contrib.auth.models import User class Document title = models.CharField(max_length=100) file = models.FileField(upload_to = 'media') def __str__(self): return self.title I believe I need to add a ForeignKey model to my Document class to trace back the user id... Unfortunately, I didn't find a way to make it work. Any help appreciated. Thank you. -
Django real-time real notification system
I'm trying to make a notification system that basically notifies the user or superuser when a specific action has been completed or a date has been reached. Let's say I have a model which has a datetime field. I want my system to send me an email when that datetime is 5 day and 1 minute away from me and obviously applies to all the objects of that model. Or let's say I want to send that notification email on the moment of that date time. Also, I need this dynamic so I can change or remove the conditions of these notifications and perhaps have multiple notification conditions on the same model. Now, I did consider scheduling tasks (I don't really know how to do that yet) but I thought that would really slow the system down on lets say hundreds of model objects, maybe even thousands. My reason to come here and bother this amazing community with yet another question is that I want to know the following: Is there an existing Django app that does this already but I couldn't find after hours of searching? If not, is scheduling tasks the only option? If so, could a get … -
How to filter Integerlist from a Array list field
I am using Django Admin (list_filter) to filter a list of Integers form a array list field am not getting any result query. model.py class Offer(CreatedAndUpdatedMixin): stores = ArrayField(models.IntegerField(),default=list(), null=True, blank=True) below is my custom lookup code in filter.py def queryset(self, request, queryset): if self.value() == 'Bangalore': stores = Store.objects.filter(city__id=1).values_list('id', flat=True) return queryset.filter(stores__contains=list(stores)) return queryset Am not geting any errors but returns empty -
How to run a flask code in a python script
I have a django code written in python. I have another flask code. I want to implement the functionality of the flask code in the django. Is there any way? -
URL Redirection is not working (Django 3.0)
I am the newbie of writing programming, now I am learning django. I have a problem for URL redirection. I create the model and it does work at admin site. Also I set the PK for each article, that successfully generate the URL by PK. However when I post the message form the front-end, after posting it appear the error message suppose it should be redirect to the page of DetailViewand I have imported the reverse function in my model, but it seem not working. My python version : 3.7.6 and django version : 3.0.0 ImproperlyConfigured at /add/ No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model. My View from django.shortcuts import render from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView from .models import Page class PageListView(ListView): model = Page template_name='home.html' context_object_name = 'all_post_list' class PageDetailView(DetailView): model = Page template_name='post.html' class PageCreateView(CreateView): model = Page template_name='post_new.html' fields = ['title', 'author', 'body', 'body2'] Model from django.urls import reverse from django.db import models from ckeditor.fields import RichTextField class Page(models.Model): title = models.CharField(max_length=50) author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, ) body = RichTextField() body2 = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse('post', args=[str(self.id)]) … -
Redirect User to previous page after successful login in django all auth
I'm using django allauth in my project, it is working fine, but I'm facing little bit issue, that is user didn't redirect to previous page after successful login. I tried to search on google but i din't find any solutions. -
Django: OperationalError No Such Column
I'm building my first partly "independent" project without utilizing a tutorial. I made an Event object which the user could assign the title, date_due, and description. I am currently attempting to add an author value to it, which would hold the user's profile. I'm using the django.contrib.auth.models User model. I'm not entirely sure of what I am doing, I would just like some help on my project overall. I'm rather young in early high school and am feeling really lost currently. Extremely appreciated, thanks. This is my Blog/models.py, holding my Event model. from django.db import models from django.contrib.auth.models import User # Create your models here. class Event(models.Model): title = models.CharField(max_length=100) date_due = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True) description = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) This is my Blog/forms.py file, for the Event object. from django import forms from .models import Event class EventCreationForm(forms.ModelForm): class Meta: model = Event fields = ['title', 'date_due', 'description'] This is my Blog/views.py, which displays the Event form as well as a list of all of the User's events. from django.shortcuts import render from .models import Event from .forms import EventCreationForm # Create your views here. def CalendarView(request): if request.method == "POST": form = EventCreationForm(request.POST) if form.is_valid(): form.save() … -
Django: Cannot assign “<Booking: loader2>”: “Booking.b_price” must be a “Loader_post” instance
hi am working on a project where driver add price to the user post...now user can accept and reject the offer ....when the user accepts offer it do booking but after submitting the form it gives error this is my models.py class Booking(models.Model): post = models.ForeignKey(Loader_post, related_name='b_price',on_delete=models.CASCADE,default='',null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='') approved_price = models.BooleanField(default=False) pay = models.CharField(max_length=30, default='') mode = models.CharField(max_length=30 ,default='') this is my views.py class booking_approve(CreateView, LoginRequiredMixin): form_class = forms.booking_form model = Booking template_name = "confirm_booking.html" success_url = reverse_lazy("Loader:post") def form_valid(self, form,*args, **kwargs): booking = get_object_or_404(Booking, pk=self.kwargs.get('pk')) print(form.cleaned_data) bk = form.save(commit=False) bk.user = self.request.user bk.post = booking bk.save() return super().form_valid(form) this is my urls.py path('confirm_booking/<int:pk>/booking',views.booking_approve.as_view(), name="booking_approve"), this is my html page {% for loader_post in request.user.Loader.all %} {% for price in loader_post.prices.all %} <img src="{{loader_post.image_of_load.url }}" alt="Avatar" style="width:100%; height: 25%; margin-bottom: 10px; "> <h4><b>Post id : {{loader_post.id }}</b></h4> <p>Driver offer : <i class="fa fa-inr" aria-hidden="true"></i>{{price.driver_price }}</p> <p>Offer by : {{price.driver_name }}</p> <a style="margin-right:20px;" href="{% url 'Loader:booking_remove' pk=loader_post.pk %}"><i class="fa fa-times fa-4x" style="color: red;" aria-hidden="true"></i></a> <a href="{% url 'Loader:booking_approve' pk=loader_post.pk %}"><i class="fa fa-check-circle fa- 4x" aria-hidden="true"></i></a> </div> </div> {% endfor %} {% endfor %} this is the error in my views -
How to refresh <div> in html and not the whole page
I want to refresh particular section(which contains form) in html page and not the whole page in Django templates.form contains question and choices when user submit the form it redirect to next question.(base.html contains script which i used to create countdown timer) question_details.html {% extends 'app/base.html' %} {% block content %} <div> <h2>score -{{user.userextend.score}}</h2> <form action="{% url 'app:detail' quiz_id=que.quiz.id question_id=que.id %}" method="post" id="user_form"> {% csrf_token %} {% for choice in que.answer_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.answer }}</label><br> {% endfor %} <input type="submit" value="Next"> </form> </div> {% endblock %} -
Best Python Backend for Firebase Applications
Good day people of Web Development! I've recently been introduced to the wonderful world of Firebase! Putting my Angular Front-end web app onto their server was beyond seamless (don't even get me started with the GCP cross platform analytics). Is there a similar solution for integrating a Python Backend or is the best solution to stick with Django/Flask REST API's? -
Setting HttpReferrer In Unit Tests
In my view.py I check that request.META.get('HTTP_REFERER') and request.build_absolute_uri(reverse('example_page')) are equal, and if so, the user can view the page. The problem comes when I want to unit test the page, because my tests access the page with a get or post request rather than a redirect from the specific page, the check within my view fails and my unit test cannot access the page to test the logic that I want to test. How can I access the page within a unit test as if it had been redirected from a certain page (not just called with a get or post request from nowhere). my test (which no template is rendered as it fails my check in view.py) def test_logged_in_user_uses_correct_template(self): user = User.objects.create_superuser('username') self.client.force_login(user) # I thought setting the referer here would work, but it doesnt response = self.client.get(reverse('example_page'), headers={'referer': reverse('calling_page')}) self.assertTemplateUsed(response, 'website/example_page.html') self.assertEqual(response.status_code, 200) Thank you. -
Setup Django to execute a python function only once on system ready
I'm using Django 3.0.6 as a web interface for a python pool controller. The web server is Nginx 1.14.2 with Gunicorn. The system manages various items including, opening and closing valves, monitoring of valve positions, controlling pump speeds, pool lights, chlorinator, scheduling etc. The software and the hardware build is coming along nicely, although it has been a massive learning curve for me. I need to find a way that just after Nginx/Gunicorn/Django boot (i.e. when the server is ready), a simple python function is executed only once to set the default 'pool program' and schedule and system status variables. The solutions that I have seen read and tried have various outcomes - running the start-up function twice, or only when the index page is requested, or not at all. Thank you in advance. -
Dockerized Python Scripts Having Issues Accessing Files Stored to /tmp
I want to apologize in advance that I don't have specific code examples to share (though I have included my docker-compose file below that may or may not be helpful). I am having a strange issue I can't seem to trace and I am not 100% sure what to share. I have a django + celery setup running in Docker (based off of cookiecutter-django). Everything seems to be working great at first. I have extensively tested and used this setup outside of Docker, and the Dockerized Celery tasks generally behave as I'd expect (i.e., as they did when they were not Dockerized). Here's where things get weird, though. For various reasons, I need to load some data files and create temp files at runtime that I can't just put in my docker file. One example is Using NamedTemporaryFile. Another is installing the data files from Spacy. In both cases, my scripts are storing data to /tmp (I know the easy answer here is to put them in my docker file, but I can't predict which files I need ahead of time, sadly). When my celery task worker tries to access data files it supposedly created, downloaded, and/or stored to /tmp, … -
scheduled CronJob whit python Django don't execute error variable type Cron
from crontab import CronTab class CronManager: def __init__(self): system_cron = CronTab(user=True) self.cron = CronTab(user='david') minute = self.minute.on() hour = self.hour.during(0-23) day = self.day.during(1-31) week = self.week.during(0-6) mouth = self.mouth.during(1-12) year = self.year.on() return True #Add an hourly cron task def add_minutely(self, user, command, minute, environment=None): cron_job = self.cron.new(command=command, user=user) cron_job.minute.every(minute) cron_job.enable() self.cron.write() if self.cron.render(): print (self.cron.render()) return True #Add an hourly cron task def add_hourly(self, name, user, command, minute, hour, environment=None): cron_job = self.cron.new(command=command, user=user) cron_job.minute.every(minute) cron_job.hour.every(hour) cron_job.enable() self.cron.write() if self.cron.render(): print (self.cron.render()) return True #Add a daily cron task def add_daily(self, name, user, command, minute, hour, day, environment=None): cron_job = self.cron.new(command=command, user=user) cron_job.minute.every(minute) cron_job.hour.every(hour) cron_job.day.every(day) cron_job.enable() self.cron.write() if self.cron.render(): print (self.cron.render()) return True # Add a weekly cron task def add_weekly(self, name, user, command, minute, hour, day, week, environment=None): cron_job = self.cron.new(command=command) cron_job.minute.every(minute) cron_job.hour.every(hour) cron_job.day.every(day) cron_job.week.every(week) cron_job.enable() self.cron.write() if self.cron.render(): print (self.cron.render()) return True # Add a monthly cron task def add_monthly(self, name, user, command, minute, hour, day, mouth, environment=None): cron_job = self.cron.new(command=command) cron_job.minute.every(minute) cron_job.hour.every(hour) cron_job.day.every(day) cron_job.month.every(mouth) cron_job.enable() self.cron.write() if self.cron.render(): print (self.cron.render()) return True #Add a quarterly cron task, is not important def add_quarterly(self, name, user, command, environment=None): cron_job = self.cron.new(command=command) cron_job.minute.on(0) cron_job.hour.on(0) cron_job.day.on(1) cron_job.month.on(3,6,9,12) cron_job.enable() self.cron.write() if … -
django authentication using @login_required
is @login_required decorator an alternate to login() and authenticate() in django?, Anyone can you please elaborate it?. Thanks in advance for the reply -
The time from a datetime-local input not being passed to the server in post request
I have an input element that doesn't pass the time but just the date to the server to be stored in the database. I printed the start and end time from the POST request sent by the form and only the date gets sent even though the time has been entered. 2020-05-27T00:00 2020-05-30T00:00 Not sure why it's only grabbing the date. Any help is greatly appreciated. Thanks in advance for any help. My code is below. <div class="form-group"> <label for="checkin">Check-in</label> <input type="datetime-local" class="form-control" id="checkin" name="checkin" placeholder="Check-in date"> </div> Here's my model: class Customer(models.Model): name = models.CharField(max_length=255) site = models.IntegerField(null=True) category = models.CharField(default='time', max_length=10) title = models.CharField(max_length=255) start = models.DateTimeField() end = models.DateTimeField() def __str__(self): return self.name Here's my view: def addCustomer(request): if request.user.is_authenticated: if request.method == 'POST': name = request.POST.get('name') start = request.POST.get('checkin') end = request.POST.get('checkout') lot = request.POST.get('lot') print(start) print(end) if name and start and end and lot: customer = Customer(name=name, site=lot, title=name, start=start, end=end) customer.save() return redirect('home') else: messages.error(request, 'Please make sure to fill out all the feilds.') return redirect('home') else: return redirect('loginuser') -
Reason for getting Unknown field(s) (text) specified
I am trying to add a comment section to posts in a class based view and I am getting Unknown field(s) (text) specified for Comment I have reviesed the comment form as it is the place where this error could come from here is the models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(max_length=160) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return '{}-{}'.format(self.post.title, str(self.user.username)) here is the comment form class CommentForm(forms.ModelForm): content = forms.CharField(label="", widget=forms.Textarea( attrs={'class': 'form-control', 'placeholder': 'Text goes here!!!', 'rows': '4', 'cols': '50'})) class Meta: model = Comment fields = ('content',) here is the views.py class PostDetailView(DetailView): model = Post template_name = "post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter(post=post).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') comment = Comment.objects.create( post=post, user=request.user, content=content) comment.save() return HttpResponseRedirect("post_detail.html") else: comment_form = CommentForm() context["total_likes"] = total_likes context["liked"] = liked context["comments"] = comments context["comment_form"] = comment_form return context class PostCommentCreateView(LoginRequiredMixin, CreateView): model = Comment fields = ['text', ] def form_valid(self, form): form.instance.author = self.request.user form.instance.post_id = self.kwargs['slug'] return super().form_valid(form) here is the template … -
How to return all the intere connected multiple items from a Django model using a qurey set?
I have a data like given bellow, first column protein IDs second column peptide sequence and third column some value I have created a Django model to store this data. Data Table A0A075B6K4 YELTQPPSVSTAR 60,10 A0A075B6K4 SYELTQPPSVTAR 2 A0A075B6Q5 EVQLVESGEGSLR 7 A0A075B6S5 DIQMTQSPSGDR 10 A0A0A0MRZ8 EIVLTQSPGER 30,20 A0A0B4J1V0 EVQLVESGGSLR 10 A0A0B4J1X5 EVQLVESGGSLR 0 A0A0B4J2D9 AIQLTQSPSGDR 0 A0A0C4DH42 EVQLVESGGSLR 0 A0A0C4DH55 EIVMTQSPGER 10 A0A0C4DH42 YELTQPPSTAR 20 A0A0C4DH55 YELTQPPSTAR 4 A0A0B4J1X5 YELTQPPSTAR 12 Django mdoles from django.db import models # Create your models here. class ProteinID(models.Model): ProtID = models.CharField(max_length=30) def __str__(self): return "%s" % (self.ProtID) class PeptideSeq(models.Model): sequence = models.CharField(max_length=100) feq = models.CharField(max_length=100) protein = models.ForeignKey(ProteinID, on_delete=models.CASCADE) def __str__(self): return "%s %s" % (self.sequence, self.feq) class Meta: ordering = ['sequence'] Details: As we can see in the table a single protein ID can hold more then one peptide sequence and single peptide can be associated with more then one protein ID. I want to add two search option: if a protein ID entered as a query it should return all the associated peptides and the values from the third column query A0A0C4DH55 should return YELTQPPSTAR 4 EIVMTQSPGER 10 Or a peptide sequence entered as a query it should return all the associated … -
How to Inspect the Queue Processing a Celery Task
I'm currently leveraging celery for periodic tasks. I am new to celery. I have two workers running two different queues. One for slow background jobs and one for jobs user's queue up in the application. I am monitoring my tasks on datadog because it's an easy way to confirm my workers a running appropriately. What I want to do is after each task completes, record which queue the task was completed on. @after_task_publish.connect() def on_task_publish(sender=None, headers=None, body=None, **kwargs): statsd.increment("celery.on_task_publish.start.increment") task = celery.tasks.get(sender) queue_name = task.queue statsd.increment("celery.on_task_publish.increment", tags=[f"{queue_name}:{task}"]) The following function is something that I implemented after researching the celery docs and some StackOverflow posts, but it's not working as intended. I get the first statsd increment but the remaining code does not execute. I am wondering if there is a simpler way to inspect inside/after each task completes, what queue processed the task. -
Make django work with `network_mode: host` in docker-compose
Related project : https://github.com/mjozan/docker-compose-django-react Hello This project is a simple app using react and django with docker-compose. As I want to make this project work with vscode Codespace (cf this issue) , I put network_mode: host on the django service in the docker-compose file. However, by doing so, django is not running anymore (the container seems to run but the browser cannot access localhost:8000). I would like to know how I could solve this so that all services work. Thank you for your answer. -
Django form validation on clicking Next instead of Submit
I have this HTML page in which I have 2 forms. Django is not checking the form validation for the first form. I want it to check form validation for the first form. This is the Html Code <form method="post" id="msform"> {% csrf_token %} <!-- progressbar --> <ul id="progressbar"> <li class="active" id="conf"><strong>Configuration</strong></li> <li id="auth"><strong>Authentication</strong></li> </ul> <div class="progress"> <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuemin="0" aria-valuemax="100"></div> </div> <br> <!-- fieldsets --> <fieldset> <div class="form-card"> <div class="row"> <div class="col-7"> <h2 class="fs-title">Cluster Configuration</h2> </div> <div class="col-5"> <h2 class="steps">Step 1 - 2</h2> </div> </div> {{ form1|crispy }} </div> <input type="button" name="next" class="next action-button" value="Next" /> </fieldset> <fieldset> <div class="form-card"> <div class="row"> <div class="col-7"> <h2 class="fs-title">Authentication</h2> </div> <div class="col-5"> <h2 class="steps">Step 2 - 2</h2> </div> </div> {{ form2|crispy }} </div><button type="submit" class="btn btn-primary" >Next</button> </fieldset> </form> If I use submit button instead of next for the first form then second form doesn't work. -
How do I implement an html button to run a python script in django?
I have read a lot about this but I'm still rather unclear. Hoping someone can help me with a simple step by step guide on how to do it. Im new to coding if it wasn't clear. At present I have a very basic django web app up and running. It has views setup and a template html page I've called 'home'. This is where I want the button to be. When a user presses the button I want it to run a python script. The python script is currently just on my computer but I would like to move it to the relevant directory in my django project - where is that? The python script generates a unique video which will display on the same html page as the button. I already have a video tag on the html page and static folder where the video assets can go to facilitate this. Each time the button is clicked it should run the script again and generate a new unique video. I need to think about how this will work with multiple users too which sound like it requires Ajax? Thanks for any help. -
Adding Mock Data To A mkdtemp Folder
Im testing my website and have a page which creates a pdf. I decided id use mkdtemp() to make a temporary MEDIA folder so the pdf would be created in there and destroyed once testing was complete. My problem is that I need to be logged in to view the page and during user creation a default profile image is given to the user - from the MEDIA folder. Because I make a mock MEDIA folder then try to create a user which needs to access an image from within my MEDIA folder it throws an error when it cant find it. How can I add the files to my mocked MEDIA folder so the user can be created (with the default image attached to their profile) then continue to test my application. test.py MEDIA_ROOT = tempfile.mkdtemp() @override_settings(MEDIA_ROOT=MEDIA_ROOT) def test_redirects_after_POST(self): user = User.objects.create_superuser('username') self.client.force_login(user) response = self.client.post( reverse('final_question'), data={ 'final_question': 'Test data'} ) self.assertRedirects(response, reverse('enrolment_complete')) The error message FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Acer\\AppData\\Local\\Temp\\tmp_s8vtsfx\\profile_pics\\default.jpg' Thank you. -
Django queryset is returning none or empty
I am trying to print/get whatever is in the Property.applicable_platform.event_group but when I try to print them out I get a empty queryset: parser.EventGroups.None or <QuerySet []> Here is my models currently setup. class Device(models.Model): name = models.CharField(max_length=100) class EventGroups(models.Model): name = models.CharField(max_length=100) class PlatformDevice(models.Model): name = 'Property Specifics' event_group = models.ManyToManyField('EventGroups', blank=True) applicable_devices = models.ManyToManyField('Device', blank=True) class Platform(models.Model): name = models.CharField(max_length=255) class Property(models.Model): name = models.CharField(max_length=255) applicable_platform = models.ManyToManyField(Platform, through=PlatformDevice) I can successfully print the device names but I can not print the event_groups names as it returns empty. I have a bunch of test EventGroups added in my admin panel and if I print out the objects then I can see them. -
Can't import django via windows terminal
I'm trying to import django on my virtualenv, but I always get the same error when I use import django it says 'import' não é reconhecido como um comando interno ou externo, um programa operável ou um arquivo em lotes. in English, it means "'import' isn't recognized as an intern or extern command[...]"