Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery parameter for JavaScript
I have a Celery job queue that searches for hashtags, facebooks posts, quoted facebook posts, etc and and put the found information in 3 different columns. So if there no results for hashtags the 1st one is shrinking (that's the idea), if there are no results for facebook posts — the 2nd one is shrinking etc. The columns are positioned with help of bootstrap. So the questiong is: How can I obtain a parameter from Celery? So later I can put in the JavaScript to perform. var columnResult1 = +kw_search_results + +recipients var columnResult2 = +div_media_section & +div_media_section_news + ... var columnResult3 = +fb_posts_div_id + +comments_main_div + ... if (columnResult1 == 0) { if(columnResult2 == 0) { [do the jQuery scenario 1]; /* it'll have 6 scenarios: 1st, 2nd > 0; 1st, 3rd > 0; 2nd, 3rd > 0; 3rd, while other = 0, etc */ } } if (columnResult1 == 0) { if(columnResult3 == 0) { [do the jQuery scenario 2]; } } if... etc. Thanks. -
difference between localhost and postgres for host in docker
I am developing a django app and trying to run it inside docker. I have an issue that I could not understand so far. while running the app with docker-compose, it seems that the web app cannot connect to the database when i use these configurations: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'my_db', 'USER': 'my_user', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '5432', } but once I change the host to postgres, it works. like this DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'my_db', 'USER': 'my_user', 'PASSWORD': '', 'HOST': 'postgres', 'PORT': '5432', } what is the difference between postgres and localhost. One is running without and issue inside docker and not in development environment in my mac and the other one is the opposite. # docker-compose.yml version: '3' services: db: image: postgres expose: - "5432" web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db -
Django/Python - Cannot assign "1": "Company.merchant" must be a "Merchant" instance
couldn't figure out a way to give self.companies.merchant a id error is : Cannot assign "1": "Company.merchant" must be a "Merchant" instance. I looked for another questions like this but didn't understand. self.merchant = Merchant.objects.create( name='merchant', ref_code='45664', ) self.companies = Company.objects.create( name='companyone', ref_code='222', merchant=Merchant.objects.first().id, ), self.merchant.companies.add(*self.companies) Merchant model: class Merchant(models.Model): name = models.CharField(max_length=255) ref_code = models.CharField(max_length=32) Company Model : class Company(models.Model): name = models.CharField(max_length=255) ref_code = models.CharField(max_length=32) merchant = models.ForeignKey( 'accounts.Merchant', related_name='companies') -
Django set ModelForm field without including it in the form
In my app, I have Users create Post objects. Each Post has a User class Post(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) ... I want to create a post-submission form for editing and submission, so I plan to use Django's ModelForm functionality. class PostForm(ModelForm): class Meta: model = Post fields = "__all__" However, if I do this, then whoever is viewing the form will be able to set who the Post author is. I want to make sure that the resulting user field is them. But, if I exclude the user field from the ModelForm, class PostForm(ModelForm): class Meta: model = Post exclude = 'user' then the user will not be set on form submission. I've hacked my way around this by making a custom form and updating the post field def submit_view(request): .... request.POST = request.POST.copy() request.POST.update({ 'user' : request.user.id }) form = PostForm(request.POST, request.FILES) .... but then I lose automatic UI generation and form validation, which in some ways defeats the purpose of the Form class. Could somebody point me to the idiomatic way of setting the user field without including it in the Form? -
Multidimensional arrays from a GET/POST request in Django
php array: $post = [ 'contact' => ['phone' => '1234', 'lname'=>'Anton'], ['phone' => '123', 'lname'=>'Sima'] ]; or GET URL: contact[][phone]=1234&contact[][lname]=Anton How can I get data in this format using jango request ? I used https://github.com/bernii/querystring-parser, its result does not suit me, it deletes duplicate keys -
Best DJango module to create Dashboard?
What the best DJango module to create Dashboard? -
Django ORM count group by issue
I have the following model: class Referral(models.Model): referrer = models.ForeignKey(Profile, related_name='referral_made') recipient = models.ForeignKey( Profile, related_name='referral_received') created_at = models.DateTimeField(auto_now=True) I need to group by the number of referrals for each recipient This query works: Referral.objects.values('recipient_id').annotate(total_referral=Count('recipient_id')).order_by('-total_referral') and the output is [{'total_referral': 5, 'recipient_id': 929}, {'total_referral': 1, 'recipient_id': 143}] The problem is that I need query objects for later use If I remove the ".values('recipient_id')" I get separated records and not grouped. Referral.objects.annotate(total_referral=Count('recipient_id')).order_by('-total_referral') [Referral: Referral object, Referral: Referral object, Referral: Referral object, Referral: Referral object, Referral: Referral object, Referral: Referral object] I have made a lot of search and tested some answers but can't manage to get the results as Query objects Any thoughts? -
django python file storage
I would like to upload a file, parse it to .txt and then store it in the disk via a django application. I've tried quiet a few things that didn't work. First I want to make the storage work. Here's my code. I would appreciate any help. Index.html <form name='F' action='AjoutTelechargement' method='POST' enctype='multipart/form-data'> {% csrf_token %} <input type="file" name="filedir" style="color:white" size="100" > <input type="submit" class="btn .btn-ajouter btn-xl page-scroll" value="Ajouter" /> <script type="text/javascript" src="/media/js/jquery-1.10.2.min.js"></script> <script> function myFun() { $.get('AjoutTelechargement/',{"value":"get_the_value_from_web"},function(ret) { return ret; }); } models.py from django.db import models from django.core.files.storage import FileSystemStorage key_store = FileSystemStorage(location='myFiles/') class FileUpload(models.Model): file = models.FileField(storage=key_store, upload_to='myFiles/%Y-%m-%d', blank=False, null=False) urls.py from django.conf.urls import url from django.contrib import admin from omicCV import views as omicCV_views from blog import views as blog_views urlpatterns = [ url(r'^$', omicCV_views.index), url(r'^admin', admin.site.urls), url(r'^AjoutTelechargement$', blog_views.AjoutTelechargement), ] views.py from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse from .models import FileUpload @csrf_exempt def AjoutTelechargement(request): if request.method == 'POST': form = FileUpload(request.POST, request.FILES) form.save() return HttpResponse("done!") -
How to create related database in django from marksheet?
I have used django-import-export package.And want to have related database from csv file of format, roll_no,name_of_student,subject_1_mark,subject_2_mark,....subject_n_mark I'm having trouble to relate subject mark with student. -
'UserLoginForm' object has no attribute 'cleanned_data' Django
Hello i have some trouble with authentification in Django so that's what i have in view.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout, get_user_model from django.shortcuts import render from django.views import generic from FS import forms from .forms import UserLoginForm, UserRegisterForm def login_view(request): form= UserLoginForm(request.POST or None) title = "Connexion" if form.is_valid(): username = form.cleanned_data.get("username") password = form.cleanned_data.get("password") user = authenticate(username=username, password=password) login(request.user.is_authenticated()) return render(request,"forms.html",{"form":form, "title": title}) def register_view(request): print(request.user.is_authenticated()) title= "Inscription" print(request.user.is_authenticated()) form = UserRegisterForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) password = form.cleanned_data.get('password') user.set_password(password) user.save() login(request, user) print(request.user.is_authenticated()) #redirect context = { "form":form, "title":title } return render(request,"forms.html", context) def logout_view(request): logout(request) return render(request, "forms.html") and that's in forms.py from django.contrib.auth.models import User from django import forms from django.contrib.auth import authenticate, login, logout, get_user_model from django.forms import ModelForm User = get_user_model() class UserLoginForm(forms.Form): username = forms.CharField() password= forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): username = self.cleanned_data.get('username') passworrd = self.cleanned_data.get('password') if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError('This user does not exist') if not user.check_password(password): raise forms.ValidationError('Mot de passe incorrecte') if not user.is_active: raise forms.ValidationError('plus valide') return super(UserLoginForm, forms).clean(*args, **kwargs) class UserRegisterForm(forms.ModelForm): class Meta: model = User fields = ['username', 'password'] … -
Searching for the most optimal solution with Django, Docker, virtualenv and Heroku deployment
I would like to use Docker with my existing Django project in virtualenv and MySQL database. It seems to my that my solution is not optimal (BTW it is not working). My app is not finished, but I wonder if it is possible to deploy it on Heroku and working with it without publishing? I will be grateful if you could show me the best solution. To wit this is my docker-compose.yml: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" db: image: mysql environment: - MYSQL_ALLOW_EMPTY_PASSWORD=yes - MYSQL_USER=root - MYSQL_DATABASE=pri Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'pri', 'USER': 'root', 'HOST': 'db', } } Structure of my files looks in this way: DockerContainerDirectory: - docker-compose.yml - Dockerfile - requirements.txt - ProjectDirectory In ProjectDirectory I have virtualenv and Project: - bin - include - lib - pip-selfcheck.json - Project In Project I have git repository, back-end and front-end written in Angular2: - backendFolder - frontendFolder backendFolder: -backendProject backendProject: - my project with `manage.py` etc. -
AuthenticationMiddleware tables migrated into multiple DB
I have two apps, and each app needs its own set of tables for user authentication. In my dbRouters.py file I have defined which Models should be migrated to which databases. However, I have been unable to change the database that the tables in the AuthenticationMiddleware get written to. I would like it to have seperate instances of the table in each db (so the apps dont share it). For my other models I have been using the meta data 'app_label' to sort the migration, read, and write databases. But I do no know the app label for AuthenticationMiddleware How can I have tables for the Authentication Middelware in each app and a way to differentiate between users of one app and another in the router? -
Django - Common data, few views
I need your help because I have approximately 6 views having common data. Example similar to my problem : def informationPlayers(request,nameTeam): try : team = Team.objects.get(name = nameTeam) except Team.DoesNotExist: return redirect(teams) if not request.user.is_authenticated(): formLogin = loginForm(auto_id=False) countMembers = team.members.count() else : members = team.members.members() ... code specific to this view ... def informationCoach(request,nameTeam): try : team = Team.objects.get(name = nameTeam) except Team.DoesNotExist: return redirect(teams) if not request.user.is_authenticated(): formLogin = loginForm(auto_id=False) countMembers = team.members.count() else : members = team.members.members() ... code specific to this view ... So these 2 views have same variables and an algorithm (if user is authenticated or not). I don't want to write this algortihm and variables in all views using them, How can I do please ? I already try TEMPLATE_CONTEXT_PROCESSORS but it's applied in all views/pages of my site, I don't want that. -
JobLookupError on restarting Django APScheduler
I'm running APScheduler on Heroku with Django Framework to send scheduled e-mails. Everything is working fine on processing. But when i'm restarting Django before schedule time, when the schedule time has come, it sending e-mail twice and having this error: apscheduler.jobstores.base.JobLookupError: 'No job by the id of 930d3aeeb08f44a58ca1be0cf441f055 was found' These are my codes: views.py from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor jobstores = { 'default': SQLAlchemyJobStore(url='postgreurl') } executors = { 'default': ThreadPoolExecutor(20), 'processpool': ProcessPoolExecutor(5) } job_defaults = { 'coalesce': True, 'max_instances': 1 } scheduler = BackgroundScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults) scheduler.start() def some_func(): scheduler.add_job(scheduled_emails, 'date', run_date=some_date, args=[model.pk]) def scheduled_emails(pk): with transaction.atomic(): try: email = EmailScheduling.objects.get(pk=pk) html = render_email_template_queryset(email) send_postmark_mail_header_footer(settings.EMAIL_SENDER_BOT, email.email, email.topic, html) except: raise I want to mention again, I'm only having error when restarting Django. Still working, but sending email twice. Everything looks fine on database. apcscheduler_jobs table remains same. Nothing is adding or removing or changing when restart Django. -
Change maxlength in django cms
Good day. I just want to change maxlength of meta_description in Django CMS, so I find titlemodels.py in .virtualenv/cms/models, which contain this: meta_description = models.TextField(_("description"), max_length=155, blank=True, null=True, help_text=_("The text displayed in search engines.")) So I try to change max_length to 255, but it does not work. And my question is how can i overwrite this prop? How can I do this? -
Django Test, 'SQLCompiler' object has no attribute 'col_count'
What I'm Testing I'm attempting to unit test the annotate_active queryset inside my models.py, class ServerQuerySet(QuerySet): def annotate_active(self, start=None, end=None): return self.annotate( active=Case( When(fqdn__in=self.get_active_fqdns(), then=True), default=False, output_field=BooleanField() ) ) class Server(models.Model): ... objects = ServerQuerySet.as_manager() How it Works get_active_fqdns just returns a set of fqdn values {'va1', 'val2', ...} When I execute the query in the django shell everything works fine: >>> Server.objects.annotate_active().values_list('fqdn', 'active') <QuerySet [('101.104.243.11', False), ('101.203.185.232', False), ('103.110.68.247', False), ('103.201.105.197', False), ('103.47.83.167', False), ('1.119.79.204', False), ('1.152.209.127', False), ('120.14.125.221', False), ('120.14.95.12', False), ('127.239.228.52', False), ('127.94.245.121', False), ('133.107.3.133', False), ('143.65.89.141', False), ('151.161.235.135', False), ('162.54.208.170', False), ('170.252.228.176', False), ('170.55.42.194', False), ('171.210.89.116', False), ('175.166.243.88', False), ('175.62.108.95', False), '...(remaining elements truncated)...']> Failing Test I have the following test case inside test_server.py (I expect this test to fail at the assertion) import pytest from reports.models import Server @pytest.mark.django_db def test_annotate_active(): result = Server.objects.annotate_active().values_list('fqdn', 'active') print(result) assert False However when I run the test function with pytest: pytest reports/tests/models/test_server.py::test_annotate_active I get an AttributeError when it executes the query: @pytest.mark.django_db def test_annotate_active(): result = Server.objects.annotate_active().values_list('fqdn', 'active') > print(result) reports/tests/models/test_server.py:35: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ … -
django-import-export, exported csv contains multiple languages and are unreadable
I have included django-import-export to export csv files and csv works fine in Ubuntu LibreOffice but not in Microsoft excel,turning unsupported languages into special characters -
Set PythonHome to /home/appuser/Env/myproject django - uwsgi ImportError: No module named site
I am using uwsgi and nginx for deployment of django project, i am new to this server side configuration and i m using this article https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-16-04 . After executing below command uwsgi --http <my_server_ip>:8080 --home /home/appuser/Env/myproject --chdir /home/appuser/myproject -w myproject.wsgi i am getting this error : Set PythonHome to /home/appuser/Env/myproject ImportError: No module named site There are many similar questions on SO, but i did not find any solutions -
Django Wagtail says I have -1 pages, attribute error when clicking explorer
I am building a jobsite with a blog. I set up Wagtail a while ago and toyed with the basics. I then built the jobsite (as a separate app in the project with Wagtail installed) and that is up and running. Now (a few months later) I am looking to work on the blog part of the site. When I log into the Wagtail admin, it says I have "-1 pages". When I click on the "explorer" link I get an attribute error: Traceback: File "/home/colin/Envs/matchstaff/lib/python3.4/site-packages/django/core/handlers/exception.py" in inner 42. response = get_response(request) File "/home/colin/Envs/matchstaff/lib/python3.4/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/home/colin/Envs/matchstaff/lib/python3.4/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/home/colin/Envs/matchstaff/lib/python3.4/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/colin/Envs/matchstaff/lib/python3.4/site-packages/django/views/decorators/cache.py" in _cache_controlled 43. response = viewfunc(request, *args, **kw) File "/home/colin/Envs/matchstaff/lib/python3.4/site-packages/wagtail/wagtailadmin/decorators.py" in decorated_view 24. return view_func(request, *args, **kwargs) File "/home/colin/Envs/matchstaff/lib/python3.4/site-packages/wagtail/wagtailadmin/views/pages.py" in index 43. parent_page = Page.get_first_root_node().specific Exception Type: AttributeError at /admin/pages/ Exception Value: 'NoneType' object has no attribute 'specific' Is this a data error where it is expecting a default page in the database? (I did add some test pages when I initially set up wagtail as proof of concept, though I assume that those got deleted when developing the … -
Django query, annotate latest child value
Is it possible to annotate value of last child? There is model StoreItem, that has relation has many to model Movement: StoreItem.objects.last().movements.last().total_count # => 32 I need something like: StoreItem.objects.annotate(total_count_of_last_movement=...??...) Thank you! -
Updating User model and saving new model - Django
I am trying to save a model by using User model as a ForeignKey, but when I try to save the model I get a RecursionError: maximum recursion depth exceeded. My code is: from django.db import models from django.contrib.auth.models import (User, Group) from phonenumber_field.modelfields import PhoneNumberField class AuthenticatorModel(models.Model): id = models.IntegerField(auto_created=True, default=1, primary_key=True, serialize=False) user_id = models.ForeignKey(User, related_name='auth_user', null=True) first_name = models.CharField(default='First Name', max_length=50) last_name = models.CharField(default='Last Name', max_length=50) phone_number = PhoneNumberField() email_id = models.CharField(default='email ID', help_text='Enter the email ID used to register the Django user', max_length=50) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): try: obj = User.objects.get(id=self.id) obj2 = AuthenticatorModel.objects.get_or_create(id=self.id) except User.DoesNotExist: return obj.first_name = self.first_name obj.last_name = self.last_name obj2.phone_number = self.phone_number obj.email = self.email_id obj.save() return super(AuthenticatorModel, self).save() I am not sure whats wrong in this. How would I create content for AuthenticatorModel and update first_name, last_name and email? -
pass parameter from CreateView to template (Django)
I've seen a similar question, alas it has not been answered. I have an app that features Entries (like blog entries) which include a part called SubEntry. I want the users to be able to report SubEntries (i.e. press the button 'report', fill some fields and the application sends an email to admins, saving the report in db is nice to have): The flow should be like that: at the view EntryDetails (url: /entry/entry-title/) the user may click on the SubEntry part. The modal opens and the subentry is visualized in the modal as enlarged, with a button/link underneath 'Report the SubEntry'. Then it's possible to click on the 'Report the SubEntry' button and two fields appear - reason of reporting and contact detail of the reporter (here I am just toggling the visibility of the fields). I manage to display the form (with get overriden - overriding get_form_kwargs causes the error No Entry with that title) but either the Entry or its attributes are not displayed... My questions are: 1) is creating a model for Reporting (ReportSubEntry) a decent approach? 2) I can't seem to pass the needed variable (an Entry object that is to be a ForeignKey for … -
markdown not rendering properly in django
i am using markdown in django 1.11 and i implemented it using cdn but when ever run the site the first paragraph is rendred inside pre and code tags below is the screenshot which is rendred: https://i.stack.imgur.com/lqNKI.png here every first para is rendered like that in every post why is it so and pls help me to resolve. post_detail.html {% extends "base.html" %} {% block body %} <div class="container" style="margin-top: 10px;"> <div class="card mb-3"> {% if list.image %} <img class="card-img-top" src="{{ list.image.url }}" alt="Card image cap"> {% endif %} <div class="card-block"> <h3 class="card-title">{{ list.title }}</h3> <p class="card-text"><small class="text-muted">Author: {% if list.user.get_full_name %} {{ list.user.get_full_name }} {% else %} {{ list.user }} {% endif %} </small></p> <div class="content-marked"> <p class="card-text">{{ list.content }}</p> </div> <p class="card-text"><small class="text-muted">Last updated {{list.updated | timesince}} ago</small></p> <a href="{% url 'posts:edit' list.slug %}" class="card-link">Edit</a> </div> </div> </div> {% endblock %} -
Django access intermediary model fields and sort
I have following models: @python_2_unicode_compatible class Translation(Model): id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False) word = CharField() related = ManyToManyField('self', blank=True, symmetrical=False, related_name='+', through='RelatedIntermediary', through_fields=('translation', 'related')) class RelatedIntermediary(Model): translation = ForeignKey(Translation, related_name='+') related = ForeignKey(Translation, related_name='+') ordering = PositiveSmallIntegerField(default=0) class Meta: ordering = ('ordering', ) and in view: for t in translations: related = t.related.all() #this doesn't sort by ordering and also related is list of translations, I don't have access to ordering How can I order and access to intermediary model? I know that I can directly use RelatedIntermediary,objects..., but I have too many translations. -
Putting Personal data in User class or make Personal data class
I have User class with some fields like age, name, surname, id. Now I want to add some more information to user: living place, education, etc. So here's a question: What is better and more logical to do: adding this info in User Class or create Personal Data Class and add field personal_data to user?