Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django add dropdown filter for a view with no class / model
I have a method mapped to a url in urls.py: urlpatterns = [ url(r'^mydir/statistics', statistics_view, name="Statistics") ] Then in mydir/statistics/views.py I have the method: def statistics_view(request): list_mystuff = Mytable.objects.all() #Mytable is defined in models .... #lots of code here to assign "enriched_models" data structure enriched_models = {bunch of stuff} ...... return render(request, 'statistics.html', {"statistics_enriched_models": enriched_models}) It all works fine and everything is rendered in using statistics.html template. Now I need to implement a dropdown filter by one of the fields of Mytable. With classes I would have to create class for Statistics in models.py, StatisticsAdmin as a proxy model in admin.py, register them both, and have list_filter=["myfield",] set in StatisticsAdmin Is there a way to set up a dropdown filter (with list_filters or whatever) and have the dropdown rendered directly without creating the classes, just with what I already have (a method that populates the template)? -
Django: Redirect from function doesn't work
Anyone can tell me, why my redirect doesn't work? I can see "SHOULD REDIRECT 2" in my terminal, but somehow the redirect never happens. Redirect import is there. helpers.py def get_reserved_items_or_redirect(request): session_order_reference = request.session.get('order_reference') if request.session.get('order_reference'): reserved_items = ReservedItem.objects.filter( order_reference=session_order_reference ) print("session_order_reference: ", session_order_reference) if not reserved_items: print( "SHOULD REDIRECT 1") return redirect('website:index') else: print( "SHOULD REDIRECT 2") return redirect('website:index') views.py class CheckoutView(TemplateView): # To check make an order template_name = "checkout/checkout_new.html" # make it a decorator def dispatch(self, request, *args, **kwargs): get_reserved_items_or_redirect(request) return super().dispatch(request, *args, **kwargs) -
Multiple programs in supervisor
I'm deploying a django app in a virtual environment and I'm using supervisor for the app itself and some celery tasks. When my /etc/supervisor/conf.d/project is like this: [program:botApp] command = /home/ubuntu/gunicorn_start.bash; user = ubuntu; stdout_logfile = /home/ubuntu/logs/gunicorn_supervisor.log; redirect_stderr = true; environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8; it works fine, I do sudo systemctl restart supervisor and I can see it running properly, but when I add my second program in the same configuration file like this: [program:botApp] command = /home/ubuntu/gunicorn_start.bash; user = ubuntu; stdout_logfile = /home/ubuntu/logs/gunicorn_supervisor.log; redirect_stderr = true; environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8; [program:worker] command=/home/ubuntu/django_env/bin/celery -A botApp worker -l info; user=ubuntu; numprocs=1; stdout_logfile=/home/ubuntu/logs/celeryworker.log; redirect_stderr = true; autostart=true; autorestart=true; startsecs=10; stopwaitsecs = 600 ; killasgroup=true; priority=998; it throws the following error: ● supervisor.service - Supervisor process control system for UNIX Loaded: loaded (/lib/systemd/system/supervisor.service; enabled; vendor preset: enabled) Active: activating (auto-restart) (Result: exit-code) since Tue 2018-09-04 08:09:26 UTC; 12s ago Docs: http://supervisord.org Process: 21931 ExecStop=/usr/bin/supervisorctl $OPTIONS shutdown (code=exited, status=0/SUCCESS) Process: 21925 ExecStart=/usr/bin/supervisord -n -c /etc/supervisor/supervisord.conf (code=exited, status=2) Main PID: 21925 (code=exited, status=2) Sep 04 08:09:26 ip-172-31-45-13 systemd[1]: supervisor.service: Unit entered failed state. Sep 04 08:09:26 ip-172-31-45-13 systemd[1]: supervisor.service: Failed with result 'exit-code'. I have tried changing the second program to be the same as the first one with different name … -
Creating reverse relationship objects with Model Mommy
I use Model Mommy for creating test data and it's working fine so far. Now I have a Django model named Invoice and a related model named InvoiceItem. class Invoice(models.Model): created_by = models.ForeignKey(users.User) class InvoiceItem(models.Model): invoice = models.ForeignKey(Invoice, related_name='items') I've created two simple Mommy recipes for these models: InvoiceRecipe = Recipe( Invoice, created_by=foreign_key(UserRecipe), ) InvoiceItemRecipe = Recipe( InvoiceItem, invoice=foreign_key(InvoiceRecipe), ) Now I'd like InvoiceRecipe.make() to automatically add a varying number of InvoiceItem objects to the invoice that is created. Currently, I'm doing it like this, but I'd like it to automatically happen: invoice = InvoiceRecipe.make(created_by=contractor) invoice.items.add(InvoiceItemRecipe.make()) invoice.items.add(InvoiceItemRecipe.make()) -
How can I join 10 small videos (~30 sec each), using Django, into 1 video?
please help me to solve this problem, I am really got stuck in this part. Actually, I upload data per 30 sec while live stream the video using WebRTC on Desktop app then upload it to Web App 30 sec per one time. so please kindly help me thank before hand. -
Best way to extract apk icon (frontend/backend)
I am creating a website where apk files will be uploaded using react.js and django. While doing the above I was confused in extraction of apk icon. My main intention of extracting the apk icon is to show the icon on website. Do I have to extract the apk icon on front-end and then make request so that the icon of apk will get stored in backend. or Do I have to take the apk file from front-end and extract the apk icon on backend and store it. Thanks. -
Filtering object values in django
I have : student.detailinfo_set.all() When i print "student.detailinfo_set.all()" to a file, i get below output. <DetailInfo: 700101 - Jack Marcher/2018-09-19/Trans X101 / 204X1001 / Pro/Y2> <DetailInfo: 700101 - Jack Marcher/2018-09-21/Trans X1 / 204X22 / Pro/Y2> <DetailInfo: 700101 - Jack Marcher/2018-09-11/Trans X102 / 204X1001 / Pro/Y2> <DetailInfo: 700101 - Jack Marcher/2018-09-10/Trans X1 / 204X22 / Pro/Y2> I just want to filter 4th columns of each row which are "204X1001", so that it will print just 2 lines to the file. -
Django model comparison not working with float data type
i am working on a project that requires location services. i'm using google's geocode(reversed) api to get detailed information from raw coordinate(latitude and longitude) like city,province,county,...etc my geocoding is done server side and this gives me the ability to cache the result to avoid query limit from google. my caching table works in context of the location bounds (northwest and southeast coordinates). i first implemented this features in PHP and MySql and it worked fine. #this is the sql query to search for location within a specific bound SELECT _mainid FROM {$this->addressCacheTable} WHERE $lat<= _nlat AND $lat>=_slat AND $lon>=_slong AND $lon<=_nlong i am trying to switch to python using django framework. and i have this #this is my query statement in django data = Coordinates.objects.filter(nlat__lte=lat, slat__gte=lat, nlon__gte=lon, slon__lte=lon) in python, i always get an empty result even tho they are values that logical match my query. How do i get my django code to work as my PHP/MySql did Please i have been stagnant for days now, any pointer in the right direction would be most helpful. also, if there is anything wrong with my implementations or there is a better way i can go about it, i would be … -
How to use signals in django-models?
I'm working on employee management system for final-year term project, after a user account is created another model should be populated with the amount of leaves the user is eligible for. with the below model user account is created- from django.contrib import auth from django.db import models from django.utils import timezone class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) and this model should get populated with the created user's details by default- class History(models.Model): first_name = models.CharField(max_length = 50) last_name = models.CharField(max_length = 50) username = models.CharField(max_length = 20) earned_leave = models.IntegerField() casual_leave = models.IntegerField() sick_leave = models.IntegerField() paid_leave =models.IntegerField() def __str__(self): return self.name the forms.py associated with it - from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django import forms class UserCreateForm(UserCreationForm): class Meta: fields = ("first_name", "last_name", "username", "email", "password1", "password2") model = get_user_model() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["username"].label = "Username" self.fields["email"].label = "Email address" I've read the signals documentation but I didn't understand it quite well. I'm very much new to django as well. -
From Django project achieve an asynchronous request to external API?
In my Django project, I have to implement an asynchronous HTTP request to the external API and get the result. I found that by using Django channels and celery we can do. There is a package in the tornado simpleAsynchronousHttp package is there anything in Django. please, can anyone suggest which is the better way to achieve asynchronous HTTP call to external API and get data in Django? -
auto_now field is not updating with updating using filter()
I'm using Django 2.0. I have a model like class MyModel(models.Model): update_new = models.CharField(blank=True, max_length=200) modified = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) and updating model data using Model Manager class MyModelManager(models.Manager): def get_queryset(self): return MyModelQueryset(self.model, self._db) def update_or_create(self, pk, **save_data): record = MyModel.objects.filter( pk=pk ) if record.exists(): # setting field manually for testing save_data['update_new'] = 'anuj' uc = record.update(**save_data) print(uc) # prints 1 return record.first(), True record, created = self.get_queryset().get_or_create( pk=pk **save_data ) return record, created This works fine and value is updated. But modified field is not updated. Value in created and modified fields remain same (timestamp when record was created) -
How to understand a Django app source code?
I would like to know how can I read an already written Django app code in order to understand it faster and better. Should I start reading url patterns? Models? Views? Should I see if it has tests, understand and execute them? I think I should do everything but, where do I start? -
Reverse for 'news_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['news\\-(?P<news_pk>[0-9]+)$']
This issue only happens in production environment ,in my local development environment it works well. Production environment is digitalocean ubuntu 16.04.Development python version is 3.6,production python version is 3.5. Here is my urls.py: urlpatterns = [ path('', NewsView.as_view(), name='index'), path('news', include(('news.urls', 'news'), namespace="news")), ] Here is news/urls.py: from .views import newsDetailView urlpatterns = [ path('-<int:news_pk>', views.newsDetailView, name="news_detail"), path('tag_lists-<int:tag_pk>', views.tagNewsList, name="tag_news_list"), path('category_lists-<int:category_pk>', views.categoryNewsList, name="category_news_list"), ] here is news/views.py def newsDetailView(request, news_pk): news = get_object_or_404(News, id=news_pk) category = news.category tags = news.tag.annotate(news_count=Count('news')) all_comments = NewsComments.objects.filter(news=news) news.comment_nums = all_comments.count() news.save() News.objects.filter(id=news_pk).update(pv=F('pv') + 1) relative_news = News.objects.filter(tag__id__in=news.tag.all()).exclude(id=news_pk)[:6] return render(request, "news_detail.html", { 'news': news, 'tags': tags, 'category': category, 'all_comments': all_comments, 'relative_news': relative_news }) def tagNewsList(request, tag_pk): tag = get_object_or_404(Tag, pk=tag_pk) news_list = News.objects.filter(tag=tag) return render(request, "tags_list.html", { 'news_list': news_list, 'tag': tag, }) def categoryNewsList(request, category_pk): category = get_object_or_404(Category, pk=category_pk) news_list = News.objects.filter(category=category) return render(request, "categories_list.html", { 'news_list': news_list, 'category': category }) Here is the html: <a href="{% url 'news:news_detail' news.pk %}"><img src="{{ MEDIA_URL }}{{ news.image }}"></a> -
ArrayField in serializer
Im my model, one of my filed are ArrayField. How can I use this field in serializer class. class MyModel(models.Model): arr = ArrayField(models.CharField()) class MySerializer(ModelSerializer): class Meta: model = MyModel fields = ('arr') -
mysqlclient error when docker build python django app in alpine linux
Dockerfile FROM python:3.6.5-alpine3.7 WORKDIR /app ADD . /app RUN pip install --no-cache-dir -i https://mirrors.aliyun.com/pypi/simple/ -r requirements.txt EXPOSE 10021 CMD ["python", "manage.py", "runserver", "0.0.0.0:10021"] Requirements openpyxl==2.4.11 requests==2.18.4 Django==2.0.2 mysqlclient==1.3.12 Build Error Collecting mysqlclient==1.3.12 (from -r requirements.txt (line 4)) ... ... /bin/sh: mysql_config: not found ... Please help! Thank you so much. -
Django: Auto logout when Tab is closed (Not browser)
I've used the following line of code to make my browser log a user out of the Django admin when the browser is closed SESSION_EXPIRE_AT_BROWSER_CLOSE setting to true How do I change this and make it in such a way that when the user closes the tab, The user gets logged out? -
Django redirect to results page after scrapy finish
I have a Django project with a scrapy application. After the user fill some form fields, I pass the filled data to the spider and crawl some pages. Everything is working like a charm, the database is being populated. Except for one thing. When the user press the submit button, the results page is blank because the spider didn't finish crawling and the data isn't in the database. How can I, inside a Django view, the same that called the spider, know that that crawl has finished? Here goes my code: def search_process(request): """ Get data from the user and redirect him to results page. """ db = get_db() process_number = request.POST.get('process_number', '').strip() court = request.POST.get('court', '').strip() start_crawl(process_number, court) process = db.processes.find_one({ 'process_number': process_number, 'court': court }) context = { 'process': process, } return render(request, 'process_result.html', context) def start_crawl(process_number, court): """ Starts the crawler. Args: process_number (str): Process number to be found. court (str): Court of the process. """ runner = CrawlerRunner() dispatcher.connect(reactor.stop, signal=signals.spider_closed) process_info = runner.crawl(ProcessesSpider, process_number=process_number, court=court) process_info.addBoth(lambda _: reactor.stop()) -
how to show two forms in one template who share relationship?
class Author(forms.ModelForm): name = models.CharField(max_length=100) class Book(forms.ModelForm): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_length=100) i have two modelforms who share foreignkey relationship in between and i want to show these two in one template so a user able to submit these two at once.I know how to render them through function based and class based views but i am puzzled with that foreign key, how to represent it that when one type name in Author modelform field then it would appear in author field of Book model form? -
How to use get_form() to filter FK?
I have three Models, and ListView with filter for each. Here are my Models. #models.py class Store(models.Model): name = models.CharField(max_length=64, unique=True) description = models.TextField(null=True, blank=True) class StoreManager(models.Model): store = models.ForeignKey(Store, related_name='store', on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) class StoreLogo(models.Model): store = models.ForeignKey(Store, related_name='store', on_delete=models.CASCADE, verbose_name='Store') image = photo = models.FileField() I want create a form what the field contains ForeignKey filter the specific Object. In my view from Detail Store, I see detail from Store.Object01, and in the view has a link for view StoreLogo form, I want in this form the field Store has attributed Object01, since I came from the detail of this object. I'm trying use get_form in Django CBV(CreateView), but my queryset doesn't work. Here my view. class CreateLogo(LoginRequiredMixin, generic.CreateView): model = StoreManager template_name = 'generic_form.html' fields = ['store', 'user'] success_url = reverse_lazy('register:store_logo_list') context_object_name = 'object_name' def get_form(self): form = super(CreateLogo, self).get_form() form.fields['store'].queryset = StoreLogo.objects.filter(store__id=self.request.id) return form Can anyone help me? If you have a solution for TemplateView, I can be used too. Thank you very much. -
Django - Passing ID into url template tag using Javascript
How do I insert an id inside a url template tag using javascript? I tried this way and I did not get it. Can not find the route in the urls.py. function Edit(pk){ window.location.assign("{% url 'authentication:edit_user' "+${pk}+" %}"); } <!-- Other way --> function Edit(pk){ window.location.assign("{% url 'authentication:edit_user' "+pk+" %}"); } Error is: Reverse for 'edit_user' with arguments '('+${pk}+',)' not found. 1 pattern(s) tried: ['authentication\/user\/edit\/(?P[0-9]+)\/$'] -
Django keeps on throwing an importerror about not finding request module (Python 2.7)
Compilation Error I know I know.. this question was asked, but my situation is slightly more problematic than the solutions I've found. Everytime I try to run "python manage.py runserver" I always get a compilation error, saying that request module isn't found. Pip says otherwise (I have request = 1.0.2), it won't let me install "request" because the dependencies for it is already satisfied. This is for python version 2.7.15. I also have python 3.4.4 installed and get an import error "Couldn't import Django". What should my next course of action be? -
celery supervisor.sock no such file
I'm deploying a django app on a Ubuntu 16.04 LTS and I'm using supervisor for some celery tasks. I had one configuration file running on /etc/supervisor/conf.d/myapp.conf with the following code: [program:botApp] command = /home/ubuntu/gunicorn_start.bash; user = ubuntu; stdout_logfile = /home/ubuntu/logs/gunicorn_supervisor.log; redirect_stderr = true; environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8; that worked perfectly when running the next code my botApp was running great. sudo systemctl restart supervisor sudo systemctl enable supervisor sudo supervisorctl status botApp Then I added a second config file for running celery with the following code: [program:projworker] command=/home/ubuntu/django_env/bin/celery -A botApp worker -l info; user=ubuntu; numprocs=1; stdout_logfile=/home/ubuntu/logs/celery/proj_worker.log; redirect_stderr = true; autostart=true; autorestart=true; startsecs=10; stopwaitsecs = 600 ; killasgroup=true; priority=998; The thing is that running the same restart, enable and status returned the following error message: unix:///var/run/supervisor.sock no such file I've been looking for a solution but it doesn't make sense that it stops working when I include the second config file, and now I get the same error even if I delete that second config file. I have managed to make work the first app again reinstalling supervisor and the same thing happens again and again when I include the second config file. I'm out of ideas of what can be the issue. Many … -
Django forms error - That choice is not one of the available choices
I'm trying to create a custom messaging platform between users. For some reason it says that my form is not valid when I submit it, and when I print the error with print(messageform.errors), I get: <ul class="errorlist"><li>receiver<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li></ul> This is strange because I don't believe that I'm using a dropdown anywhere in the form. Does anyone know why this might be the case? forms.py class MessageForm(forms.ModelForm): class Meta: model = Message fields = ['text', 'receiver'] html file <form action="" method="post"> {% csrf_token %} <input type="text" name="text" value="" /> <label for="text">Enter your message here</label><br/> <input type="text" name="receiver" value="" /> <label for="receiver">id of receiver</label><br/> <input type="submit" value="Send" /> </form> models.py class Message(models.Model): text = models.TextField(max_length=10000, blank=True) sender = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null = True, related_name="sender" ) receiver = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null = True, related_name="receiver" ) views.py usermodel = get_user_model() if request.method == "POST" and not signupform.is_valid(): messageform = MessageForm(request.POST) print(messageform.errors) if messageform.is_valid(): receiverid = messageform.cleaned_data['receiver'] newmessage = messageform.save(commit=False) newmessage.sender = request.user newmessage.receiver = usermodel.objects.filter(username=receiverid) newmessage.text = messageform.cleaned_data['text'] new_profile.save() return HttpResponseRedirect('/profile/') -
Possible to annotate sum over multiple date ranges in query set?
Is it possible to annotate .sum()s over multiple date ranges in one QuerySet Ie, basically combining these, so each object has the sum for each date range. query_set_week = DailyReports.objects.filter( date__range=('2018-08-27', '2018-08-31')) \ .select_related('profile') \ .values('profile__user_id') \ .annotate(premium=Sum('total_field'), first_name=F('profile__user__first_name'), last_name=F('profile__user__last_name') \ .order_by('profile__agent_code') query_set_year = DailyReports.objects.filter( date__range=('2018-01-01', '2018-08-31')) \ .select_related('profile') \ .values('profile__user_id') \ .annotate(premium=Sum('total_field'), first_name=F('profile__user__first_name'), last_name=F('profile__user__last_name') \ .order_by('profile__agent_code') Both work individually, but it's difficult to loop through and display the data (user - week total - year total, for example), because someone may have a result in the year filter, but not in the week filter. -
Creating separate comment section per article Django
I am trying to create a comments section that is separate from each topic. for some reason the comments app that I created will show all comments on every topic. for example if I were to make a comment on topic 1 that same comment would appear on topic 2. topic 1: Comment: blah topic 2: Comment: blah comments app: models.py from django.db import models from django.conf import settings from blogging_logs.models import Topic # Create your models here. class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE) topic = models.ForeignKey(Topic, on_delete=models.CASCADE) content = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.content) forms.py (In blogging_logs app) from django import forms from .models import Category, Topic, Entry from comments.models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['content'] labels = {'text': ''} widgets = {'text': forms.Textarea(attrs={'cols': 80})} view.py (In blogging_logs app) from comments.models import Comment from .models import Category, Entry, Topic from .forms import CategoryForm, TopicForm, EntryForm, CommentForm def topic(request, entry_id): """Show entry for single topic""" topic = Topic.objects.get(id=entry_id) entries = topic.entry_set.all() comments = Comment.objects.all() if request.method != 'POST': # No comment submitted form = CommentForm() else: # Comment posted form = CommentForm(data=request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.topic = topic …