Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django how to redirect url after create post on the same edit post
This is my url where I want to redirect after post. path('edit//produkti/add/', views.add_choice, name="add_choice"), This is my view. def add_poll(request): if request.method == "POST": form = PollForm(request.POST) if form.is_valid(): new_blerje = form.save(commit=False) new_blerje.pub_date = datetime.datetime.now() new_blerje.owner = request.user new_blerje.save() messages.success( request, 'Fatura u krijua me sukses, kliko butonin me poshte per te shtuar produktet!', extra_tags='alert alert-success alert-dismissible fade show' ) return redirect('polls:edit',) else: form = PollForm() context = {'form': form} return render(request, 'polls/add_poll.html', context) -
Django REST Framework: DRY way to specify viewmodels
I would like to have a clear way for declaring a viewmodel for my Django REST endpoints, which the incoming requests must adhere to and which would take care of the validation. I mean something like viewmodels in Spring or other Java projects. The most primitive way is just to work with the request.data (or request.POST) dictionary-like object, but in this case all the validation is hardcoded to the view layer. A little better approach would be to use serializers, but using them is still quite verbose and in the end you get back a dict, unless you implement the .create() method witch makes the code even more verbose. Here is my current approach: class MyView(APIView): def post(self, request, format=None): serializer= MySerializer(data=request.data) serializer.is_valid(raise_exception=True) what_i_actually_need = serializer.validated_data ... return Response('Something') Is there a more DRY way to do it? -
how to use the django rest-auth views with custom html templates instead of browserable APIs
I am using django rest-auth and allauth for a login/logout and registration on my website. These are very easy to use and work well. however, the browseable APIs are ugly for production. I want to fully customize my login view but still have the underlying rest-auth logic in place. I was not able to find helpful tutorials on how to do this. I found this: https://wsvincent.com/django-user-authentication-tutorial-login-and-logout/ which is exactly what I want to do but with rest-auth rather than the build-in user authentication system that django offers. How can I do this? is there a default .html files that I can override? details this is my app's urls.py: urlpatterns = [ path('users/', include('users.urls')), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), ] the above have default views, I would like to overwrite their templates. -
Issue signing up new users in Django
I have the following signup flow in an app using Django 1.11- accounts/views.py: from .forms import UserForm def sign_up(request): if request.method == "POST": form = UserForm(request.POST) if form.is_valid(): user = form.save() return redirect('index') else: form = UserForm() return render(request, 'signup.html', {'form': form}) accounts/forms.py: from django.forms import ModelForm from django.contrib.auth.models import User class UserForm(ModelForm): class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password'] It does appear to "register" a new user, in that it creates a new user in the database. The issue is I cannot login with that newly created user, the username/pw combo does not match. Going into the database I see the newly created users, but the password is in plain text: "password". But the first user I created through the command line, python manage.py createsuperuser has a salted hash as the password like pasdfhjasf8234jk324hgsdfa8df89asdf987 and I can login correctly using the password I made for it, ie "password". How do I save new users using my ModelForm where Django knows to correctly store the password as a salted hash? Thank you -
AttributeError: 'NoneType' object has no attribute 'Command'
I have upgraded django on my project, when i am running any command like "python manage.py runserver" It shows an error like "AttributeError: 'NoneType' object has no attribute 'Command'" Is there any issue in Django or In code?? Django Pro\Django_Project-master\Dpro> python manage.py migrate Traceback (most recent call last): File "manage.py", line 16, in execute_from_command_line(sys.argv) File "C:\Users\Ga\Django Pro\Django_Project-master\Dpro\env\lib\site-packages\django\core\management__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Ga\Django Pro\Django_Project-master\Dpro\env\lib\site-packages\django\core\management__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Ga\Django Pro\Django_Project-master\Dpro\env\lib\site-packages\django\core\management__init__.py", line 224, in fetch_command klass = load_command_class(app_name, subcommand) File "C:\Users\Ga\Django Pro\Django_Project-master\Dpro\env\lib\site-packages\django\core\management__init__.py", line 37, in load_command_class return module.Command() AttributeError: 'NoneType' object has no attribute 'Command' -
can I use restfull framework for Django to use api
I want to use tomtom web api for routing : https://developer.tomtom.com every time I search how to use an API with django I get the restfull framework isn't that for building an API? If I can use it to work with an existing API if yes I want to know how? Or the requests library for python would be enough? -
How to fix django-dynamic-formset with FormWizard not sending multiple forms data through POST
I'm currently trying to write an application in Django which is asking for multiple form inputs to create instances of a model; I'm trying to get information about a students grades. As typically the number of grades vary, I'm trying to use a dynamic form to allow the user to add as many fields as they need. As the form is spread across multiple pages due to its length (for other details, not related to the grades) I'm using a FormWizard solution to retain data across a session. The issue I'm getting is when I submit the form, all the data from the previous pages is sucessfully submitted, but only one of the forms is submitted on the grades page. I've tried various methods suggested on SO but cannot find an answer which works - if anyone can shed some light I'd greatly appreciate it! views.py: class SFFormWizard(SessionWizardView): template_name = "template.html" file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT,"docs")) def done(self, form_list, **kwargs): form_data = process_form_data(form_list) return render_to_response("done.html",{"form_data":form_data}) forms.py: GCSEGradeFormSet = modelformset_factory(GCSECourses, exclude=("student",),extra=1,can_delete=True) models.py: class GCSECourses(models.Model): CCHOICES = (("completed","Completed"),("predicted","Predicted")) GCHOICES = (("gcse","GCSE"),("alevel","A-Level")) class Meta: verbose_name = 'GCSE Courses Taken' verbose_name_plural = verbose_name name = models.ForeignKey(GCSESubject,verbose_name="Subject Name",on_delete=models.CASCADE) student = models.ForeignKey(Applicant,on_delete=models.CASCADE) grade = models.ForeignKey(GCSEGrade,on_delete=models.CASCADE) completed = models.CharField("Grade … -
why always error SyntaxError: 'return' outside function
i'm setting camera.py for my face recognition using python3, opencv and flask i have tried remove space or add space remove tabs, but always error. def get_frame(self): while True: # pdb.set_trace() success, img = self.video.read(1024) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) frame=vs.read() faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x,y,w,h) in faces: cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) roi_gray = gray[y:y+h, x:x+w] roi_color = img[y:y+h, x:x+w] ret, jpeg = cv2.imencode('.jpg', img) return jpeg.tobytes() i wanna fix it and no more error so i can stary my main.py without error, thanks :) -
How to set some meta attributes based on a class name in Django?
i want to streamline creation of identical views/filtersets/younameit in Django. At this point i have structures like this: class SerializerBase(serializers.HyperlinkedModelSerializer): class Meta: abstract = True fields = standard_fields extra_kwargs = { 'url': {'lookup_field': 'slug'}, } class TraitSerializerShort(SerializerBase): class Meta(SerializerBase.Meta): model = Trait What i want to do is make Meta take name of subclass, remove Serializer part and use that as model name. Is there any way to do that? It does not look that bad here, but filterset code becomes insanely big just coz everything is reiterated over and over again. -
Django React build files not found in Docker but it found without docker
I am learning docker and dockerizing my Django-react app! It is working now great except an issue and that is the bundle.js file are not getting Django when i run the project through dockcer But bundle.js files are found if run the project without docker! I guess, docker bundle the javascript in a different directory, that is why it is not getting if run with docker! this is my settings.py file STATICFILES_DIRS = [ os.path.join(os.path.join(BASE_DIR, os.pardir), 'dist'), ] and my Dockerfile is given below: FROM node:8 WORKDIR /app COPY . ./ RUN yarn RUN yarn build # Pull base image FROM python:3 # Set environment varibles ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory, we can name it whatever we want WORKDIR /djangobackend # Install dependencies # Copy requirement file from the docker workdir we defined named djangodocker COPY requirements.txt /djangobackend/ RUN pip install -r requirements.txt # Copy project COPY . /djangobackend/ and docker-compose.yml is given below: version: '3.2' services: db: image: postgres:10.1-alpine volumes: - postgres_data:/var/lib/postgresql/data/ web: build: . command: python /djangobackend/backend/manage.py runserver 0.0.0.0:8000 volumes: - .:/djangobackend ports: - 8000:8000 depends_on: - db volumes: postgres_data: Please know my problem carefully: If I run my app without docker like … -
Django list of objects doesn't render properly when using a form on the same page
I have developed a very simple Django app about music bands and their members (complete code: https://drive.google.com/file/d/1MwaC-_PchU6eBrwO01OaDivIF52S0L1D/view?usp=sharing). I used just the simple SQLlite3 database for my objects. I would appreciate help with rendering object lists when they need to be shown together with forms. They do render properly in templates that show just them, but not when a form is used on the same page with an object list. What I want is to display, say, a list of bands from the database in the middle column. It shows them properly when I render just that (i.e. when I click the Bands link). However, when I click Add band in the right-hand column and hope the list to remain in the middle column, it suddenly shrinks as if there were no Band objects in the database. In learning Django, I used the official Django tutorial, as well as the one provided by Mozilla (https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website), but could not figure out what I'm doing wrong. The code below shows the relevant parts of the code. The link above takes you to the complete code (zipped), where the relevant HTML templates are included as well. I used Python 3.7, Django 2.2, and PyCharm … -
Django List Serializer bulk update failing with 'QuerySet' object has no attribute 'pk'
I am trying to do bulk update with ListSerializer in Viewset. My Bulk create works fine but not PUT. Here is my Serializer, ListSerizlier and my View. django=2.0.0 Serializer class SampleListSerializer(serializers.ListSerializer): pass class SampleSerializer(serializers.ModelSerializer): class Meta: list_serializer_class = SampleListSerializer model = Sample fields = ['id', 'name', 'last_name' ] Here is my ViewSet: class SampleViewSet(viewsets.ModelViewSet): serializer_class = SampleSerializer queryset = Sample.objects.all() def get_serializer(self, *args, **kwargs): if "data" in kwargs: data = kwargs["data"] # check if many is required if isinstance(data, list): kwargs["many"] = True return super(SampleViewSet, self).get_serializer(*args, **kwargs) def put(self, request): sorted(request.data, key=lambda o: o["id"]) instances = Sample.objects.filter(id__in=[o["id"] for o in request.data]).order_by("id") try: with transaction.atomic(): ss = SampleSerializer(data=request.data, instance=instances, many=True) if ss.is_valid(raise_exception=True): s = ss.save() return Response(ss.data) return Response(status=status.HTTP_400_BAD_REQUEST) except Exception as e: print(f"In exception {e}") return Response(status=status.HTTP_400_BAD_REQUEST) def create(self, request, *args, **kwargs): return super().create(request, *args, **kwargs) I am getting 'QuerySet' object has no attribute 'pk' at ss.is_valid(). Can someone suggest where my mistake is? or what's wrong? -
Django: how to view raw sql response upon a query
In Django if i want to see the raw sql in debug mode i can check using in django shell from django.db import connections User.objects.all() print(connections['default'].queries[-1]['sql']) Similarly can we see the raw response of that sql. Like In the above case the sql query may return the raw results in csv, tab delimited format. From then django may create the model objects array. -
How to trouble shoot the lag in the Django live server?
I have a small protein database. You can see the codes here. Say a user searches for their proteins of interests from the database. They can add the sequences to the cart. Also, they can upload their custom data to the database using session. If the user clear the session their custom data will be remove. The purpose is to do additional analysis in the database (say pairwise alignments). The problem is when a user want to clear session. After clearing the session still the html page shows the data. After ~60 seconds the session clears. I use anonymous sessions in the script. The database works perfectly well locally. I couldn't figure out where the problem is. I tried both SQLite3 as well as PostgreSQL for the database. Still the problem persists. """ Django settings for database project. Generated by 'django-admin startproject' using Django 2.2.5. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os, socket # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used … -
Django DB Routers
My django application will connect with 3 diffrent databases (SQLLite as default, postgresql for product and manufacturer database, MSSQL for Funds database) for 3 diffrent app (product, manufacturer, funds) I have created 3 routers.py file in each app to route the read, write operations depending on the app_lable name. On my settings file I have created a DATABASE_ROUTERS configuration as below DATABASE_ROUTERS = [ "product.routers.productdbrouter","manufacturer.routers.manufacturerdbrouter", "funds.routers.fundsdbrouter", ] Now when I try to access the application it always tries to find the table from the first router (product.routers.productdbrouter in this case) and if the table is missing then it fetches from the default router (SQLLITE). Any suggestion on what Iam missing on the configuration? -
Stream with OpenCV from client to Django server
I'm looking for a solution for the following: I have a server with a Django backend to be used as a kind of chat app with a chat room that will be used to connect two clients. For that I'm using Django Channels. Client A connects to the chat room and is able to send messages to client B using this toy example (running in client B): import asyncio import websockets import json ws_url = "ws://IP_ADDRESS:PORT/ws/chat/loby/" async def command_receiver(): async with websockets.connect(ws_url) as websocket: while True: message = await websocket.recv() message = json.loads(message) print("Received: ",message["message"]) asyncio.get_event_loop().run_until_complete(command_receiver()) Now I want that client B streaming its webcam using for example OpenCV in response to client A message. In the same python script, I want to capture the webcam stream using, for example, this solution. It would be something like to this: import asyncio import websockets import json import cv2 import numpy as np ws_url = "ws://IP_ADDRESS:PORT/ws/chat/loby/" async def command_receiver(): async with websockets.connect(ws_url) as websocket: while True: message = await websocket.recv() message = json.loads(message) if message["message"] == "send_stream": cap = cv2.VideoCapture(0) currentFrame = 0 while(True): # Capture frame-by-frame ret, frame = cap.read() # Handles the mirroring of the current frame frame = cv2.flip(frame,1) … -
Django Bash completion not working on manage.py
I am trying out the django_bash_completion script provided by Django but can't use it with python manage.py command. I am trying out the django_bash_completion script provided by Django. I have added it to active script in the virtual environment. It works with django-admin but can't use it with python manage.py command. virtualenv -p python3 venv echo "source /path/to/.django_bash_completion" >> venv/bin/active active django-admin<tab><tab> python manage.py<tab><tab> For django-admin it shows all options like check, makemigrations, migrate runserver etc but when I run python manage.py it gives manage.py: command not found. Any idea why and how can I solve it? I am running bash on Ubuntu 18.04 -
Error whie install psycopg2 on ubuntu server 16.04
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /home/mosi/venv/bin/python3.6 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-im9_x6c8/psycopg2/setup.py'"'"'; file='"'"'/tmp/pip-install-im9_x6c8/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /tmp/pip-record-jyz3lis6/install-record.txt --single-version-externally-managed --compile --install-headers /home/mosi/venv/include/site/python3.6/psycopg2 Check the logs for full command output. -
How to exclude empty values in an AND queryset whitout writing if else statements
For a real-estate listing site I have a search form with multiple inputs. The user can use one or many fields to filter his search results. The more fields are filled in the more detailed the search should get. For example: If you only input the zip code all listings that match the zip code should be shown, if you input the zip code and the room number only listings that match both should be shown. My forms.py looks like this: from django import forms from .models import Property class PropertyForm(forms.Form): zip_code = forms.CharField(required=False) rooms = forms.CharField(required=False) Because I need a AND search I had to write a series of conditions in my ListView to query the results: My views.py looks like this: class ListPageView(ListView): template_name = 'property_list.html' model = Property def get_queryset(self): plz = self.request.GET.get('plz') rooms = self.request.GET.get('rooms') if plz and not rooms: object_list = Property.objects.filter(zip_code__exact=plz) elif rooms and not plz: object_list = Property.objects.filter(rooms__exact=rooms) elif plz and rooms: object_list = Property.objects.filter( Q(zip_code__icontains=plz) & Q(rooms__exact=rooms) ) else: object_list = self.model.objects.none() return object_list For only two input fields this would suffice but if I add more input fields I quickly have to write a lot of queries. Is there a better … -
Trying to save with model formset factory getting 'list' object has no attribute 'event'
I'm trying to save a related model field via Django model_formset but it's giving me this error AttributeError at /events/event/52/detail 'list' object has no attribute 'fields' anyone ever encountered this? and how to solve it. thanks View def event_detail(request, pk): event = get_object_or_404(Event, pk=pk) TicketFormSet = modelformset_factory(Ticket, exclude=('event',), extra=1, max_num=3) if request.method == 'POST': ticket_form = TicketFormSet(request.POST) if ticket_form.is_valid(): ticket_obj = ticket_form.save(commit=False) # ticket_obj.event = event ticket_obj.fields['event'].queryset = event ticket_obj.save() else: ticket_form = TicketFormSet() return render(request, 'events/event/event_detail.html', {'event': event, 'formset': ticket_form}) Model class Ticket(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) name = models.CharField(max_length=120) quantity = models.SmallIntegerField() price = models.FloatField() def __str__(self): return '{} {}'.format(self.event.name, self.name) -
Force to run delayed task Celery
I have a celery task with countdown, and I want to force this task to run. task_id = uuid() timer.apply_async( args=(self.room_group_name, cache.get(f'{self.room_name}_round'), cache.get(f'{self.room_name}_round') > self.total_rounds ), countdown=self.timer' task_id=task_id ) now I revoke this task and create another task. Is there any possibility to force run celery task with countdown? -
Call a Django view from JavaScript
Say I'm writing a web app, web shop to sell antique coins, and I have an HTML combobox (<select>) and upon selection (say, I selected 'gold') I want to redirect to a specific Django view, how can I do that? My guess is JavaScript, but I'm not sure how to properly construct a URL to the desired Django view. -
Django with NoSQL
I want to create a website using django to visualize data for companies, and I have the data in json file represented as: [{'label': 'BMW', 'gain': [{'cash': 198, 'visa': 923, 'year': 1988}, {'cash': 112, 'visa': 313, 'year': 1989}], 'type': 'automobile'}] Is it better to create two tables for each year or I should use NoSQL database with django? I don't have any experience with NoSQL, can you tell which is easier to use? -
Why does template inheritance in Django not show error?
I'm not seeing an error when template inheritance seems to fail. I don't see content from the child template but I don't see a 'TemplateNotFound' error. If I change the path to the parent template to 'notthefilename.html' I still don't see an error. Is there a way to make template inheritance fail noisily? I have no idea why this is not working even though I have a similar inheritance in a adjacent folder that is working as expected. generic_create.html The text 'hello2' is rendering. {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div style= "padding-top: 30px"> <form method="post">{% csrf_token %} {% if model_name == 'TransactionsTable' %} <div> {% block transactions_create %} hello2 {% endblock transactions_create %} </div> {% else %} {{ form |crispy }} {% endif %} <div id="container"> <input type="submit" class="btn btn-default" value="Save"> <a href="{{ view.get_success_url }}" class="btn btn-default">Cancel</a> <div> </form> </div> {% endblock content %} transactions_create.html - The content 'Hello1' is not rendering {% extends "generic_create.html" %} {% load static %} {% block transactions_create %} Hello1 {% endblock transactions_create %} -
How to remove the unspecified space between root and include url in django 2.2
I am trying to create a Django website. I have specified the path to one of my apps. But I am getting an unspecified space in the pattern.I am using Django 2.2. screenshot of the django debug page my base urls.py file from django.contrib import admin from django.urls import include, path urlpatterns = [ path('', include('homepage.urls')), path('account/', include('account.urls')), path('admin/', admin.site.urls), path('db/', include('dashboard.urls')), ] my dashboard/urls.py file from django.urls import include, path from .import views urlpatterns = [ #author dashboard path('authordboard/<int:auth_id/',views.author_dboard, name='author_details'), #reviewer dashboard path('reviewdboard/<int:re_id/',views.author_dboard, name='reviewer_details'), ] I have included the dashboard app in the settings.py file. Please help! Thanks in advance!