Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to pass url params (GET) in Django Rest Framework test client.post() method?
Is it possible to pass url params (GET) in Django Rest Framework test client.post() method besides normal post data? -
getting error with OperationalError at /admin/login/ no such table: auth_user
have created a virtual environment django 1.8.4 done with python manage.py migrate created the superadmin after that on admin login getting error OperationalError at /admin/login/ no such table: auth_user in setting.py 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), -
How To Load The Next Page When User Scrolls Down In Django
I was trying to build a blog website and was wondering to add a functionality that loads a new page as the user scroll down. I found some other answers to this but they all have some JS, JSON or Javascript in them. As I Don't know any of these languages, I was wondering if there was a way I can do this just using Django Pagination And Stuff. Thanks In Advance. -
Django convert timedelta to integer in annotation
I'm annotating the difference between two dates then aggregating the rounded average. The problem is that the difference between the two dates is a datetime.timedelta so I am getting the error: django.db.utils.ProgrammingError: cannot cast type interval to numeric How can can I use the integer days_to_pay.days in the Avg()? def aggregate_ar_detail(self): queryset = self.annotate( days_to_pay=Case( When(Q(date_paid__isnull=False), then=F('date_paid') - F('date_trans')), default=None, ) ).aggregate( avg_days=Round(Avg('days_to_pay')), ) I've tried specifying the output field on the annotation a models.IntegerField() but it causes: TypeError: float() argument must be a string or a number, not 'datetime.timedelta' -
Django DRF - using basic search filter to do an multiple OR search
Im trying to do a multiple OR search with the basic Django filter. Ive tried the below URLs already but they only return the first result api/circuit/?search=AB5814765;AB827451;AB0923784 using a comma returns no results also. is there any syntax that will show multiple records built in or does something custom need making, ive tried a few custom attempts but they are all failing too using an action like the below gives me a 404 when I try to do api/circuit/ref_search/AB5814765|AB827451|AB0923784 @action(detail=False, methods=['get'], url_path='ref_search/(?P<refs>[^/.]+)/', permission_classes=[IsAdminUser]) def ref_search(self, request, refs, *args, **kwargs): refs = refs.split('|') query = Q() for x in refs: q = Q(circuit__ref_no=x) query |= q queryset = DeviceCircuitSubnets.objects.filter(query) serializer = self.serializer_class(queryset, many=True) return Response(data=serializer.data) I also tried api/circuit/ref=AB5814765|AB827451|AB0923784 def get_queryset(self): refs = self.request.query_params.get('ref', None) if refs is not None: refs = refs.split('|') query = Q() for x in refs: q = Q(status=x) query |= q queryset = queryset.filter(query) return queryset my view: class SiteCircuitDataROView(viewsets.ReadOnlyModelViewSet): queryset = Circuit.objects.all() serializer_class = CircuitSerializer permission_classes = (IsAdminUser,) filter_class = Circuit filter_backends = (filters.SearchFilter,) -
How to import local data to production with django cookiecutter digitalocean and docker
I learn django and docker with django cookiecutter. I don't understand how transfer all data in local environment to production environment That's my actual workflow On local machine : 1- docker-compose -f local.yml up --build -d 2- docker-compose -f local.yml run django python manage.py makemigrations 3- docker-compose -f local.yml run django python manage.py migrate 4- update some models 5- docker-compose -f local.yml run django python manage.py makemigrations 6- docker-compose -f local.yml run django python manage.py migrate 7- add some datas in db And then, I try to deploy to digital ocean : 1- docker-machine create --driver digitalocean --digitalocean-access-token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx --digitalocean-image=ubuntu-18-04-x64 --digitalocean-region=fra1 prod 2- eval $(docker-machine env prod) 3- docker-compose -f production.yml up --build -d 4- docker-compose -f production.yml run django python manage.py makemigrations 5- docker-compose -f production.yml run django python manage.py migrate When I update database models : 1- docker-compose -f production.yml down 2- docker-compose -f production.yml up --build -d 3- docker-compose -f production.yml run django python manage.py migrate I trying to use dumpdata / loaddatta but with docker-compose prod and local environment the fixture.json is not found I also trying to create a postgres backup in local and applying to prduction db, but is not working. Everything work fine, the … -
Separate Authentication for Django Admin
I am implementing RemoteUserMiddleware for my Django app and it is working fine. For admin though, I would like to require both the request.META['REMOTE_USER'] to be valid and use AuthenticationMiddleware username and password to access Admin. Since Django just uses flags is_staff and is_superuser it allows REMOTE_USER to access admin without any further verification as long as those flags are set. Is there any way to require reauthentication for admin using AuthenticationMiddleware. Jira for example does this. -
How can i import media directory in a .py file using from ..media
I need to access files from my media directory that i can read using georinex and iterate over them but i cant seem to access the media directory, i keep getting invalid syntax error: from ..media. Kindly help me. I have tried changing the media url in the root urls.py but it doesn't work and frankly if i were to find an easier way such as from ..media it will very pleasant. Also i have several different files in the media directory: observation, report, coordinate but am more interested in the observation. Here's the code am trying to test out: import georinex as gr from surveyorportal.models import Files def read_rinex_file(self): obs = gr.load(self.observation_file.path) print(obs) I expect the code to read the file and after which i can implement the iteration -
How can I write widget for horizontal displaying multiple checkbox?
I have a form with multiple checkbox. But they are vertical displaying by default. I want to display their horizontally. I need to create custom widget for this task. I found a default code of CheckboxSelectMultiple https://github.com/django/django/blob/master/django/forms/widgets.py#L765 class CheckboxSelectMultiple(ChoiceWidget): allow_multiple_selected = True input_type = 'checkbox' template_name = 'django/forms/widgets/checkbox_select.html' option_template_name = 'django/forms/widgets/checkbox_option.html' def use_required_attribute(self, initial): # Don't use the 'required' attribute because browser validation would # require all checkboxes to be checked instead of at least one. return False def value_omitted_from_data(self, data, files, name): # HTML checkboxes don't appear in POST data if not checked, so it's # never known if the value is actually omitted. return False def id_for_label(self, id_, index=None): """" Don't include for="field_0" in <label> because clicking such a label would toggle the first checkbox. """ if index is None: return '' return super().id_for_label(id_, index) link to git with django widgets https://github.com/django/django/tree/master/django/forms/templates/django/forms/widgets I found also bootstrap form for horizontal displaying multiple checkboxes {% for ... %} <div class="form-check form-check-inline"> <input type="checkbox" class="form-check-input" id="materialInline{{ .id}}"> <label class="form-check-label" for="materialInline{{ .id}}">{{ .title}}</label> </div> {% endfor %} But I don't know how to unite this. -
Django -- How to call a form submit view into dataupload view
I have a Form submission view and a dataupload view. I want to save the form and be redirected to the upload page to upload the file. I tried return the form submission view in the upload view. The form is getting saved but i am getting MultiValueDictKey error def uploaddata(request): return Metadata_submission(request) if request.method == 'POST': form = uploadmetaform(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('file_list') else: form = uploadmetaform() return render(request, 'uploaddata.html', { 'form': form }) This is my form submission view: def Metadata_submission(request): print("Metadata Submitted") Authors_Name = request.POST["Authors_Name"] Affliations = request.POST["Affliations"] Dataset_Creation_Date = request.POST["Dataset_Creation_Date"] Metadata_var = Metadataform(Authors_Name=Authors_Name, Affliations=Affliations,Dataset_Creation_Date=Dataset_Creation_Dat) Metadata_var.save() MultiValueDictKeyError at /uploaddata/ 'Authors_Name' -
display all User, model with user in django admin
class JobList(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) assign_jobs_user = models.ManyToManyField(AppJob) In admin section when i register joblist then it shows only user that are add by add Job List. But i want to display all users. -
How to link and filter data from 3 tables in Django orm
I want to filter posts (beer) for which the user has not yet voted. To do this, I need to combine posts with a rating table and a help table where there is a user. Example tables raiting in db https://drive.google.com/file/d/1MkL4IVtviIcPo7XFptoybPthNyO4dUp_/view?usp=sharing My model post class Beerpost(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, editable=False) title = models.CharField("Назва", max_length=160) slug = models.SlugField(max_length=160, unique=True) img = ProcessedImageField(upload_to='static/img/%Y/%m/%d/%H/%M/%S/', processors = [ResizeToFit(150, 385)], format='JPEG', options={'quality': 90}) type_beer = models.ForeignKey( Type, verbose_name="Тип пива", on_delete=models.SET_NULL, null=True, blank=True, default=1) volume = models.ForeignKey(Vol, verbose_name="Об'єм л.", on_delete=models.CASCADE, null=True, blank=True, default=3) price_limit = models.ForeignKey(Price, on_delete=models.CASCADE, null=True, blank=True, verbose_name='Орієнтовна ціна', default=4) country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True, blank=True, verbose_name='Країна', default=3) created = models.DateTimeField("Дата створення", auto_now_add=True) is_active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) ratings = GenericRelation(Rating, related_query_name='foos') favorite = models.BooleanField(default=False, editable=False) users_reaction_favorite = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="users_reaction_favorite", editable=False) I try this all_beer = Beerpost.objects.all() user_table = UserRating.objects.filter(user_id = pk) join_user_table = user_table.select_related() But I don't know how combine this 3 queries. Pleace help me, I three days can't solve this problem( Please help me, I three days can't solve this problem( or recommend me some others solution. -
PostgreSQL tables are not creating. Unable to connect django with database?
I'm deploying a django app on heroku & when I create a new user on user registration form in my deployed app. it says the user is created but after that when I try to login through that user it says the user doesn't exist. So the error must be in my PostgreSQL database I'm using. I downloaded PostgreSQL and created a new database of name myblog and connected it to my django-app. But when I run heroku run python manage.py makemigrations The table of my database doesn't update and remains empty Here's my database settings- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'myblog', 'USER': 'postgres', 'PASSWORD': os.environ.get('PASSWORD'), 'HOST': 'https://mydjangoblog.herokuapp.com', 'PORT': '5432', }, } I've already installed psychopg2 on my environment & I'm using django 2.2. Can anyone please help. Your suggestions will be welcome, thanks. -
How do I run JavaScript code for a set of html code that repeats in a for loop created in Django?
I have this code in html that creates a block of html code for each element in my context variable. {% for car, speed in carSpeeds.items %} <div id="car1"> <div id="carSpeedBar"> <!-- progress bar indicating car speed value goes here --> </div> </div> <p id='result'></p> <!-- div simply holding the variables for each iteration --> <div class="container"> <p id='carType'>{{ car }}</p> <p id='carSpeed'>{{ speed }}</p> </div> {% endfor %} GOAL: I would like to run this JS/JQ code for each bar that gets created var bar = $('#carSpeedBar'); var result = $('#carSpeed').text(); var res = document.getElementById('result'); var width = 0; var id = setInterval(speed, 12); function speed(){ if (width < result){ width++; bar.style.width = width + '%'; res.innerHTML = width + '%'; This is what I have so far and it works, but this only creates the bar for the first block of html code and ignores the others and I cannot figure out why. Like, it creates a bar for Mercedes and leaves all the others blanks even though their values are coming through. My guess is that it refuses to overwrite the ID's of the elements as they might be getting duplicated somehow. Please tell me what I'm … -
pass multiple fields to django rest framework
My model class car(models.Model): name = models.CharField(max_length=255, unique=True) speed = models.CharField(max_length=255) age = models.CharField(max_length=255) def __str__(self): return self.name My api serializer class carSerializer(serializers.ModelSerializer): class Meta: model = car fields = ('name', 'speed', 'age') My list view class carListView(ListAPIView): queryset = car.objects.all() serializer_class = carSerializer filter_backends = (DjangoFilterBackend,) filter_fields = ('name', 'speed', 'age') How can I search the model fields name, speed, age via the api link? Currently, I am able to search a single field using http://127.0.0.1:8000/api/?name=Toyoto How can I modify the link to search multiple fields ? -
Why I can't submit my form to Database when I pass `LoginRequiredMixin` to my `view` in Django?
I'm new to Django and I'm trying to make a very simple app for my coworkers to submit their tasks on a client and how long took them to fulfill their task. I can submit to my model through the admin page fine but I can't submit it as a form through the HTML page. I'm using django-autocomplete-light which is working fine as well. # This is my forms.py file class PushTask(ModelForm): name = CharField() class Meta(object): """docstring for Meta.""" model = ClientModel fields = ['name', 'reason', 'time_spent'] widgets = { 'name': autocomplete.ModelSelect2(url='name-autocomplete'), } # This is a part of my models.py file class ClientModel(models.Model): Aa = models.AutoField(primary_key=True, unique=True) name = models.ForeignKey(Clientele, on_delete=models.CASCADE) time_spent = models.TimeField(default=None) dec_name = models.CharField(max_length=100, default=None) reason = models.ForeignKey(Task, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now=True) def __str__(self): return self.name.name # ths is my views.py which I believe is causing the issue class RecordView(LoginRequiredMixin, View): template_name = 'manage_records.html' def get(self, request): print('I got the form ') formset = PushTask() return render(request, self.template_name, {'formset': formset}) def post(self, request): print('I posted ') formset = PushTask(request.POST) if formset.is_valid(): ClientModel(name=name, reason=reason, time_spent=time_spent, dec_name=request.user) formset.save() formset = PushTask() return HttpResponseRedirect('manage_records.html') args = {'formset': formset} return render(request, self.template_name, {'formset': formset}) <!-- this is my html … -
AttributeError: module 'module' has no attribute 'celery'
I want to use celery in my Django app for a task that should run in the background. I've followed these tutorials Asynchronous Tasks With Django and Celery and First steps with Django Using Celery with Django my project structure: project ├──project | ├── settings | ├──__init__.py (empty) | ├──base.py | ├──development.py | └──production.py | ├──__init__.py | ├──settings.py | └──celery.py ├──app_number_1 | └──tasks.py project/project/init.py : from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ['celery_app'] project/project/celery.py : from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings.production') app = Celery('project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() project/project/settings/production.py : INSTALLED_APPS = [ 'background_task', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', ] . . . CELERY_BROKER_URL = 'mongodb://mongo:27017' CELERY_RESULT_BACKEND = 'mongodb://mongo:27017' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' docker-compose.yml: version: '3' services: web: env_file: - env_vars.env build: . restart: always command: - /code/runserver.sh ports: - "80:8000" depends_on: - db - mongo db: ... mongo: image: mongo:latest restart: always runserver.sh: #!/bin/bash sleep 1 python3 /code/project/manage.py migrate --settings project.settings.production python3 /code/project/manage.py runserver 0.0.0.0:8000 --settings project.settings.production & celery … -
Django Python Merge Some Data in Json
How to merge some data under a single JSON object. As you can see in JSON format below, I want to have (Company address & house address) under the same object (Address). [ { "full_data":[ { "name":"James", "email":"James@yahoo.com", "phone":"1234567890", "house_address":"address" } ] }, { "full_data":[ { "name":"James", "email":"James@yahoo.com", "phone":"1234567890", "company_address":"address" } ] } ] My desired output will be to have the following format: { "full_data":[ { "name":"James", "email":"James@yahoo.com", "phone":"1234567890", "address":{ "house_address":"address", "company_address":"address" } } ] } -
How to deploy redis session and cache to AWS EC2 in production using DJANGO 2.1
I am new to Redis and AWS. I am using PostgreSQL. I have built a web application that relay on session for shopping cart and I do use session for caching some results. My concern is that I am trying to understand the process and find some documentation on how to deploy it using AWS EC2. During the development, you have to start and stop redis(or daemonize it and have it in the background). What is the most efficient/best or configuration to deploy my infrastructure? Should I use Redis + DynamoDB(or Elasticache) from AWS or use Redis + Supervisor to deploy my web app on EC2. Thank you for the help. -
Django. Rest framework. Error with nested tags
Help advice, trying to figure out the django rest framework. I have serializers.py from rest_framework import serializers from listings.models import * class kvSerializerLocation(serializers.ModelSerializer): class Meta: model = kv fields = ['country', 'region', 'state'] class kvSerializer(serializers.ModelSerializer): category = serializers.CharField(source='get_property_type_display') url = serializers.CharField(source='get_absolute_url', read_only=True) location = kvSerializerLocation(many=True) class Meta: model = kv fields = ['title', 'price', 'address', 'category', 'url', 'location'] I created kvSerializerLocation to highlight a dataset in a generic location tag. But getting an error: Got AttributeError when attempting to get a value for field location on serializer kvSerializer. The serializer field might be named incorrectly and not match any attribute or key on the kv instance. Original exception text was: 'kv' object has no attribute 'location'. I have to succeed: <title></title> <price></price> <address></address> <category></category> <url></url> <location> <country></country> <region></region> <state></state> </location> If there is a country instead of location, the page is loaded, but the tags 'country', 'region', 'state' are missing data -
How capitalize() method works in python/django?
I have read that the method capitalize() is used to change the first letter of a string, from lowercase to uppercase. I am writing a small website in Django (first time) and I noticed that in the template section if I write item.description.capitalize() I get some error but, removing the parentheses it works, why? Isn't capitalize a method?? -
Why I am getting this error: AttributeError: 'str' object has no attribute 'decode'
I am trying to create a registration page with email verification. I am new in Python Dajngo webdevelopment. Currently I using Python 3.6, Django 2.2.4, Postgresql 11 and Ubuntu OS. But I am having a problem and can't figure it out. Guys could you please help me to solve the problem? Thanks in advance! I have provided all the code bellow: This is views.py file from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required # Email verification from django.http import HttpResponse # from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate # from .forms import UserSignUpForm from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes, force_text from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.template.loader import render_to_string from .token_generator import account_activation_token from django.contrib.auth.models import User from django.core.mail import EmailMessage # Email verificatin end def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) email_subject = 'Activate Your Account' message = render_to_string('activate_account.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage(email_subject, message, to=[to_email]) email.send() return HttpResponse('We have sent you an email, please confirm your email … -
how to learn Django by project
I'm learning Django and I want to find some initial projects to work with other people. Where can I find such a group or project and how can I contact them? Github is great but I don't know how to find. -
Is it a good practice to create/run Django migrations by docker-compose?
I wonder if it's a good idea to add commands for creating and applying Django migrations to docker-compose.yml. Something like this: command: bash -c "python /code/manage.py makemigrations && python /code/manage.py migrate && python /code/manage.py runserver 0.0.0.0:8000" Are there any drawbacks with this approach? -
access data from request body django
I am using django v2.2.4 and need to access request body data. Here's my code: @api_view(['POST']) @renderer_classes((JSONRenderer,)) def index(request): if request.method == 'POST': results= [] data = JSONParser().parse(request) serializer = ScrapeSerializer(data=data) if serializer.is_valid(): url = request.data.url #url = request.POST.get('url') But I get this error: RawPostDataException at /scrape/ You cannot access body after reading from request's data stream How can I access the request body?