Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django extract dictionary value [duplicate]
This question is an exact duplicate of: Django: get a Select value from form instead of its tag result I have this code: a = TipoAux.objects.filter(denom=form.cleaned_data.get('tipAux')).values('codigo') It is returning: <QuerySet [{'codigo': 'PRO'}]> Now I need the value PRO in order to compare some other things. How can I do it? -
Celery: Get worker by parameters
I am trying to implement time-consuming calculations with Celery (v 3.1.25). I need to get already running worker by the parameter that passed when the task was started. Client passes company_id to the server and Celery starts the worker with given parameter. There could be many clients that pass the same company_id, so I have to check that the process is not already running. If it is running the task should not be scheduled, because the result of running the same process always the same and we have to tell him that task is already running. @celery_app.task(bind=True) def calculate(self, company_id): obj_list = get_objects(company_id) for i, obj in enumerate(obj_list): self.update_state(state='PROGRESS', meta={'current': i, 'total': len(obj_list)}) result = calc( registry=registry_key, company_id=company_id, ) return result I'm thinking about storing the current status in Postgres database, where the model would be work_id, status (PROGRESS/SUCCESS), start_time, finish_time. In this case the question is how to handle that status of the work has changed? And is it correct to store such information in database? Are there any other variants of solving this problem? I was looking at celery-once, but did not find there the method that could tell me that this process is running (I want to … -
How to add more than one image in blog using django
I'm creating my blog using Django. I want to add images in between the post. For this, I'm using 5 image field in one model. I have tried to add <img src=" {{article.img1.url}} "</img> in the content of the article, still it's not showing images in between my written article. This is my template code, models.py class article_by_author(models.Model): author_name = models.CharField(max_length=200, default='xxxx') article_title = models.CharField(max_length=200, default='') article_content = models.TextField(max_length=999999, default='') article_date = models.DateTimeField(auto_now_add=True) article_category = models.CharField(max_length=200, default='') article_priority = models.IntegerField() article_category_priority = models.IntegerField() article_views = models.IntegerField(default=0) author_img = models.ImageField(blank=True, upload_to='images/') article_img = models.ImageField(blank=False, upload_to='article_img/') img1 = models.ImageField(blank=True, upload_to='article_img/') img2 = models.ImageField(blank=True, upload_to='article_img/') img3 = models.ImageField(blank=True, upload_to='article_img/') img4 = models.ImageField(blank=True, upload_to='article_img/') img5 = models.ImageField(blank=True, upload_to='article_img/') this is my Template, {% for article in full_article %} <div id="post-header" class="page-header"> <div class="background-img" style="background-image: url('{{article.article_img.url }}');"></div> <div class="container"> <div class="row"> <div class="col-md-10"> <div class="post-meta"> <a class="post-category cat-2" href="../../../preview/theme/webmag/category.html">{{article.article_category}}</a> <span class="post-date">{{article.article_date|stringformat:".10s"}}</span> </div> <h1>{{article.article_title}}</h1> </div> </div> </div> </div> <div class="main-post"> {{article.article_content|safe}} </div> {% endfor %} This is my view.py full_article = article_by_author.objects.filter(article_title=article_title) context = { 'full_article':full_article, } For adding Content, I have another page with a form where I add all the article content. Now my question is how to call images(img1, img2,..) in between the … -
Django: Key error during migrations in Google App Engine
I am deploying my django web app to Google app engine. Deployed successfully. Now when i run $ python manage.py makemigrations there was an error due to this, In my settings.py I have, SECRET_KEY = os.environ['SECRET_KEY'] In my app.yaml I have, env_variables: SECRET_KEY : 'my-secret-key-is-here' The error I am getting is, File "C:\Users\Bidhan\AppData\Local\Programs\Python\Python35\lib\os.py", line 725, in __getitem__ raise KeyError(key) from None KeyError: 'SECRET_KEY' The error clearly is due to secret key not present in settings.py. How to solve this? Note: If this question is asked before, I could not find it here. So it will be helpful to tag the question in comment section. -
Filter Django query set on value of earliest instance of related field
Given the following models class Thing(models.Model): ... class Status(models.Model): thing = models.ForeignKey(Thing, ...) value = models.CharField(choices=(('foo', 'foo'), ('bar', 'bar')), ...) timestamp = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('timestamp',) Is it possible by using the Django ORM tools (without much raw SQL writing and post-query in-memory processing) to get the queryset of Things for which the latest timestamp has the value bar? In other words, I'd like to re-write the following code and achieve the same value for queryset: thing_ids = [] for thing in Thing.objects.all(): status = thing.status_set.last() if status is not None and status.value == 'bar': thing_ids.append(thing.id) queryset = Thing.objects.filter(id__in=thing_ids) -
Make a django website and wordpress website run on same vps from nginx
I have already a django site running on nginx, but now i want to add a wordpress site. i have centos6, php7.1.26 installed but php-fpm not recognized. thid nginx enabledsite.conf work perfect for django upstream django { server 0.0.0.0:8080; } server { listen 80; server_name drlandivar.com www.drlandivar.com; return 301 https://drlandivar.com$request_uri; } server { listen 80; server_name doutorlandivar.com www.doutorlandivar.com; return 301 https://doutorlandivar.com$request_uri; } server { listen 80; server_name doctorlandivar.com www.doctorlandivar.com; return 301 https://doctorlandivar.com$request_uri; } server { listen 443; server_name drlandivar.com www.drlandivar.com; charset utf-8; client_max_body_size 75M; # adjust to taste ssl on; ssl_certificate /etc/letsencrypt/live/drlandivar.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/drlandivar.com/privkey.pem; # managed by Certbot location /media { alias /opt/virtualenv/landivarpj/media; } location /static { alias /opt/virtualenv/landivarpj/static; } location / { include /opt/virtualenv/landivarpj/uwsgi_params; proxy_pass http://django; proxy_redirect off; include proxy_params; } } server { listen 443; server_name doutorlandivar.com www.doutorlandivar.com; charset utf-8; client_max_body_size 75M; # adjust to taste ssl on; ssl_certificate /etc/letsencrypt/live/drlandivar.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/drlandivar.com/privkey.pem; # managed by Certbot location /media { alias /opt/virtualenv/landivarpj/media; } location /static { alias /opt/virtualenv/landivarpj/static; } location / { include /opt/virtualenv/landivarpj/uwsgi_params; proxy_pass http://django; proxy_redirect off; include proxy_params; } } server { listen 443; server_name doctorlandivar.com www.doctorlandivar.com; charset utf-8; client_max_body_size 75M; # adjust to taste ssl on; ssl_certificate /etc/letsencrypt/live/drlandivar.com/fullchain.pem; … -
Select related executes queries
I can't make select_related work with the following configuration: Models: class Text(models.Model): author = models.ForeignKey('authors.Author', on_delete=models.SET_NULL, blank=True, null=True) Author model: class Author(models.Model): name = models.CharField(max_length=200) View In a view, I use the select_related function to avoid hitting the db when querying for text's authors e.g.:mytext.author: class TextsViewTest(TestCase): def text_view(request, pk, template_name='texts/detail.html'): source_text = Text.objects.select_related('author').get(pk=pk) return render(request, template_name, { 'source': source_text, }) Test According to select_related it shouldn't hit the database when accessing the Text.author relationship, but when testing it with: def test_layout_content_header__uses_prefetched_relationships(self): author = Author.objects.create(name="foobar") source_text = Text.objects.create(author=author) context = {'source': source_text} with self.assertNumQueries(0): source_text.author Output ./manage test texts.test_views shows a hit: Creating test database for alias 'default'... System check identified no issues (0 silenced). F ====================================================================== FAIL: test_layout_content_header__uses_prefetched_relationships (author.tests.test_views.TextsViewTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/.../text/tests/test_views.py", line 1035, in test_layout_content_header__uses_prefetched_relationships source_text.author File "/.../lib/python3.6/site-packages/django/test/testcases.py", line 80, in __exit__ '%d. %s' % (i, query['sql']) for i, query in enumerate(self.captured_queries, start=1) AssertionError: 1 != 0 : 1 queries executed, 0 expected Captured queries were: 1. SELECT "authors_author"."id", "authors_author"."name", FROM "authors_author" WHERE "authors_author"."id" = 1 ---------------------------------------------------------------------- Ran 1 test in 0.489s FAILED (failures=1) Destroying test database for alias 'default'... Any ideas? -
Django Bootstrap Crispy InlineField with custom validation missing message
I'm using Django Crispy forms to render a fieldset containing multiple fields, most of which are not inline, but I have a date of birth field which I'd like to be inline. It uses a custom validation in which is translates date to age and then checks that the user is over 18. This validation is correct and works normally when the field is rendered in a FieldSet. However, after applying crispy_forms.bootstrap.InlineField, with no options, just simply: Layout( Fieldset( #Other fields... InlineField('dob'), ) ) The message does not display - though validation still works: How do I get this message to appear while using InlineField? -
Problem with ForeignKey. Django migrations
I have to define code.Spatial class like primary_key and codels.LScharacteristic codels.PlannedUsing like foreign key. I face this, when i tried migrate: ProgrammingError: ERROR: the id column specified in the foreign key constraint does not exist. but I havn't a id column in my model: from django.db import models from django.utils.translation import ugettext_lazy as _ from renter.models import RefAbstract, Renter from django.contrib.gis.db import models from textwrap import shorten class Unitt(RefAbstract): ....//some classes class Task(RefAbstract): class Meta(RefAbstract.Meta): verbose_name = 'task' verbose_name_plural = 'tasks' class Spatial(models.Model): codeq = models.IntegerField('no',help_text='no') code = models.PositiveIntegerField('cutare',primary_key=True,help_text='cutare')//unique column codeV = models.IntegerField('novi',help_text='novi') renter = models.ForeignKey(Renter, on_delete=models.DO_NOTHING, verbose_name='renter') geometry = models.MultiPolygonField(geography=True, verbose_name='geometry') class Meta: verbose_name = 'cutarea' verbose_name_plural = 'cutarea' class LScharacteristic(models.Model): codels = models.ForeignKey(Spatial, on_delete=models.DO_NOTHING, verbose_name = 'cutarea')// Foreign Key tract = models.CharField('tract',max_length = 80, help_text='tract') task = models.ForeignKey(Task, on_delete=models.DO_NOTHING, verbose_name='task') totalarea = models.PositiveIntegerField('totarea',help_text = 'totarea') explarea = models.PositiveIntegerField('exarea',help_text = 'exarea') protecttype = models.CharField('category',max_length = 50, help_text = 'category') class Meta: verbose_name = 'characteristic' verbose_name_plural = 'characteristics' class PlannedUsing(models.Model): codels = models.ForeignKey(Spatial, on_delete=models.DO_NOTHING, verbose_name = 'cutarea') // Foreign Key codeq = models.IntegerField(help_text='number') cutareaShape = models.ForeignKey(CutareaShape, on_delete=models.DO_NOTHING, verbose_name='form') cuttype = models.ForeignKey(CutareaType, on_delete=models.DO_NOTHING, verbose_name='type1') managetype = models.ForeignKey(ManageType, on_delete=models.DO_NOTHING, verbose_name='type2') unit = models.ForeignKey(Unitt, on_delete=models.DO_NOTHING, verbose_name='unit') composition = models.ForeignKey(Composition, on_delete=models.DO_NOTHING, verbose_name='sort') assortment = … -
Why does Jinja2 range() function cannot be parsed? "TemplateSyntaxError, Could not parse some characters...". Generating random number in Jinja2
I want to add random number to the URL of the static file I am loading (because otherwise static file is cashed and not refreshing). But when I try to load the page The following is displayed: Exception Type: TemplateSyntaxError Exception Value: Could not parse some characters: range|(1, 51)| | random My snippets: in wrapper.html (inside head tag) <link rel="stylesheet" href="{% static 'css/style.css' %}?v={{ range(1, 51) | random }}" type="text/css"/> in settings.py (Maybe something wrong here) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] I have looked at this question Generate random number with jinja2 and used the same line suggested in the answer, but it didn't work. Thank you very much -
How to get url of view using django.core.urlresolvers.reverse
I have URL pattern in urls.py in a Django project like this. urlpatterns = [ url(r'^web/', include('project.web.weburls')), ] and in my weburls file I have this: urlpatterns = [ url(r'^$', webview.home)] in my test file, I have written test case like bellow, url = reverse("project.web.weburls.webview.home") but it gave me an error. NoReverseMatch: Reverse for 'project.web.weburls.webview.home' not found. Why do I get this? what mistake do I have in using this reverse URL pattern? Thanks in advance. -
Django-Allauth Implementation
I'm trying to implement django-allauth using a tutorial https://wsvincent.com/django-allauth-tutorial/ .Performed same as what has been told but when I click or type http://127.0.0.1:8000/accounts/signup/ blank screen pops up .And I'm unable to perform login too! Django version : 2.1 Python version : 3.7.1 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'django.contrib.sites', 'django_extensions', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.github', 'questions', 'profile', 'core', 'search', 'bootstrap4', # 'social.apps.django_app.default' ] SITE_ID = 1 AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) Now changed all the changes in the django admin too. But I'm unable to get any positive output till now! -
How to change size of TextArea wiget in Django form
How do I resize my django textarea widget. By default, it is taking up full width and has too many rows -
Django: get a Select value from form instead of its tag result
I have a form with a select. (Generated by my django form) Its result looks like this: <select name="tipAux" id="id_tipAux"> <option value="CLI">Clientes</option> <option value="PRO">Proveedores</option> I need the value to be returned instead of what is inside the <option> tag. At the moment when I use form.cleaned_data.get('myform') it is returning for example the value "Clientes" or "Proveedores" and I need CLI or PRO instead (its value). -
Django Debug Toolbar unexpected behaviour
I have defined two serializers defined for a model, ListingSerializer and DetailedSerializer. Also, there is a static function get_people_count() defined in both serializers as below: @staticmethod def get_people_count(obj): #some code When using Django Debug toolbar, get_people_count() of ListingSerializer is called instead of DetailedSerializer's even though DetailedSerializer is returned in overridden get_serializer_class(). However, this problem doesn't occur when using Postman. Debug toolbar is updated to 1.11 version, still this issue is occuring. -
Invalid syntax when trying to create custom http errors
I'm trying to make custom http error pages. And as usual the django docs are really hard to understand. I'm trying my best to follow this doc: https://docs.djangoproject.com/en/2.1/topics/http/views/#customizing-error-views So I have set DEBUG = False I have set ALLOWED_HOSTS = ['*'] In my views.py (not inside an app) def server_error(request, exception): return render(request, 'mysite/errors/500.html') And in my urls.py (not inside an app), after all paths. urlpatterns = [ path('', views.index, name='index'), .......etc handler500 = 'mysite.views.server_error' ] When I run my server, I get instant error on handler500 in urls.py. handler500 = 'mysite.views.server_error' ^ SyntaxError: invalid syntax I also made a simple '500.html' under 'templates/errors'. I have tried with importing handler, even though I read that I should not. I tried with removing 'mysite' in location for view etc. I can't seem to find anything about this SyntaxError on my handler? -
How to run function if model instance field is equal to inplay (Django)
I have a model that's being updated by a background task every few seconds. I would like to execute a function when the instance of the attribute status changes to 'inplay' I have looked through documentation and examples but can't find what I'm looking for. Would signals be the best option to call a function? from django.db import models class testModel(models.Model): player1 = models.CharField(null=True, max_length=50) player2 = models.CharField(null=True, max_length=50) Player1_odds = models.FloatField(null=True) Player2_odds = models.FloatField(null=True) status = models.CharField(null=True, max_length=10) complete = models.CharField(null=True, max_length=10) from django.dispatch import receiver from django.db.models.signals import pre_save, pre_delete, post_save, post_delete from django.dispatch import receiver @receiver(post_save, sender=testModel) def post_save(sender, instance, created, **kwargs): # if status is = true call send # # pass def send() do stuff -
Making an HTML element show most recent blog post name/topic
I'm creating a blog as my first project in HTML/CSS using Python/Django for some of the apps. I'd like to add a section in a sidebar that shows the last blog post and some other most recent objects. Here's what I have so far that doesn't seem to do it. blog/models.py class Post(models.Model): title = models.CharField(max_length=150) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: get_latest_by = 'publication_date' blog/views.py def recent_post(request): latest_post = Post.objects.latest() blog/templates/blog/base.html <h3 id="sidebar">Recent</h3> <ul class="list-group mt-2"> <li class="list-group-item list-group-item-light"> {{ recent_post }} </li> -
Environment status becomes severe when second environment is deployed
I uploaded sample django project to AWS using elasticbeanstalk. I deployed two environment accoding to a tutorial here https://colintoh.com/blog/how-to-deploy-application-to-aws-elastic-beanstalk. When I deployed(create using eb cli), the first environment helth changes to sever showing errors on elasticbeanstak console 100.0 % of the requests are erroring with HTTP 4xx. Insufficient request rate (12.0 requests/min) to determine application health. ELB processes are not healthy on all instances. ELB health is failing or not available for all instances. However when I access both pages they seem to be working correctly since they both show django's debug message for first page The install worked successfully! Congratulations! You are seeing this page because DEBUG=True is in your settings file and you have not configured any URLs. Can I just ignore the error or I need to do something to fix the error(and how to fix it)? -
How to give pagination with form
I want to give pagination to following view. How can i give it because it have conditions as well form. I am not getting how to deal with with it. Please help me to integrate pagination in this JobListView class JobListView(LoginRequiredMixin, generic.TemplateView): template_name = 'jobs/job.html' def get(self, request, *args, **kwargs): context = super(JobListView, self).get_context_data(**kwargs) if 'status' in request.GET: form = JobSearchForm(request.GET) if form.is_valid(): status = form.cleaned_data['status'] start_date = form.cleaned_data['start_date'] end_date = form.cleaned_data['end_date'] company = self.request.user.userprofile.user_company lookups = (Q(job_company=self.request.user.userprofile.user_company)) if start_date: lookups = lookups & Q(job_created_on__gte=start_date) if end_date: lookups = lookups & Q(job_created_on__lte=end_date) if status == 'Active': lookups = lookups & Q(job_status=status) if status == 'Inactive': lookups = lookups & Q(job_status=status) jobs=Jobs.objects.exclude(job_is_deleted = True).filter(lookups) else: form = JobSearchForm() company_name = self.request.user.userprofile.user_company jobs = Jobs.objects.exclude( job_is_deleted = True ).filter( job_company=self.request.user.userprofile.user_company ) return render(request, self.template_name, {'form': form, 'jobs': jobs}) -
Django cannot update another model from a DetailView
I have been stuck trying to build a validation form in a DetailView which compares an argument with flag key and if it is correct it will update some fields in another model (the score field). This view exists in a Django app ("Challenges") and it presents a model from the given app. However I would like to change two fields from another model. The other model exists in another app("Accounts". However I cannot select the fields I want from the second model. I get an ObjectDoesNotExist exception, no matter I know that it is there. The troubling class: class ChallengeDetailView(FormMixin,DetailView): model = Challenge form_class = FlagForm def get_success_url(self): return reverse('challenges:challenge_detail', kwargs={'pk': self.object.pk}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = self.get_form() return context def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): f=form.cleaned_data['flag'] if f==self.object.flag: try: u= User.objects.get(pk=self.request.user.pk) ch=Challenge.objects.get(flag=f) request.user.score+=ch.point except ObjectDoesNotExist as e: pass return super().form_valid(form) Maybe the models might also help as well as the FlagForm: class FlagForm(forms.Form): flag = forms.CharField() User Model: class User(auth.models.User, auth.models.PermissionsMixin): score = models.IntegerField(default=0) def __str__(self): return self.username def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.score … -
Message is not showing in admin django panel
I have app in django 1.11 and my problem is, that I can't show message in admin panel about existing image. I am using here clean method in models.py. Previous I tried with messages, without success because I need request to do this. In terminal this command is executed print('Test'), but not this one raise ValidationError('This image already exists.') class ImageModel(BaseImage): text = models.TextField(null=True, blank=True) def clean(self): if ImageModel.objects.filter(original_filename=self.file).exists(): print('Test') raise ValidationError('This image already exists.') -
how i delete data from database after 1 hour
hy guys i have save a user ip address in my database using django but i wnt to delete this ip address after one hour please tell me how can i do that this in django my table name is iptable in my ip table 2 columns 1 is ip_adress and 2 is date_time of saved data how can i delete this from my database after one hour please tell me thanks in advance if you need any information about my code please tell me i provide it on my comment section ........ -
Using django-cc as cryptowallet for my users
is smb. able to give my a hint about a good way to implement cryptopayments (BTC, LTC, DASH) in my Django app? Currently im just able to find the following: https://github.com/limpbrains/django-cc but it seems that the documentation is somehow very lightweight and not clear understandable, at least not to me. Thanks in advance :) -
How to register inherited sub class in admin.py file in django?
Project Name : fusion App Name : admin_lte Python 3.7 Django 2 MySql Question is "I want to register sub model in django admin-panel",when i write code for model registration in admin.py file that time occurred below error. django.core.exceptions.ImproperlyConfigured: The model Device is abstract, so it cannot be registered with admin. NOTE : I used multiple separated model file. device.py (Model File) from django.db import models class Device(models.Model): device_type = models.CharField(max_length=100,blank=False) price = models.IntegerField() status = models.CharField(max_length=10, default="SOLD") issues = models.CharField(max_length=100, default="No Issues") class Meta: abstract = True def __str__(self): return 'Device_type:{0} Price:{1}'.format(self.device_type,self.price) #Inheritance Concept class Laptop(Device): pass class Meta: db_table = "laptop" class Desktop(Device): pass class Meta: db_table = "Desktop" class Mobile(Device): pass class Meta: db_table = "Mobile" __init__.py File from django_adminlte.models.employee import Employee from django_adminlte.models.device import Device admin.py from django.contrib import admin from.models import Employee from.models import Device admin.site.register (Employee) admin.site.register (Device) I want to show sub model (Desktop,Laptop,Mobile) in admin panel so admin can add some data from admin panel.