Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Changing Value of an Attribute in a Model when a post takes place
I have made a blog where a user can like or unlike, so everything is working fine now but I have tried to add a Like Model to view more details related to each like that takes place by which user and when. In the Like Model I have added a value for each model and choices are Like and 'Unlike' I have tried in the views to use get_or_create but it cause an error TypeError: Field 'id' expected a number but got <built-in function id>. and I tried to add the value incase a like and unlike is made it returned AttributeError: 'str' object has no attribute 'save' I am going to show the view with my trials commented First here is the post model: class Post(models.Model): content = RichTextUploadingField(null=True, blank=True) num_likes = models.IntegerField(default=0, verbose_name='No. of Likes') likes = models.ManyToManyField(User, related_name='liked', blank=True) Here is the like model: LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike') ) class Like(models.Model): # To know Who liked user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, max_length=8) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) Here is the views.py def LikeView(request): # post = get_object_or_404(Post, id=request.POST.get('post_id')) post = get_object_or_404(Post, id=request.POST.get('id')) liked = False current_likes … -
Django tests stopped running
My Django tests have randomly stopped running and I cannot figure out why. The error that I'm getting is: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I found this question and I've run the command: export DJANGO_SETTINGS_MODULE=mysite.settings (with my relevant settings) and it didn't solve the issue. I've also tried adding this to the top of my tests file but it didn't do anything: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") Here is the full print out of the error I'm getting: /Users/x/Dropbox/Portfolio/Django/theperrygroup/venv/bin/python /Users/x/Dropbox/Portfolio/Django/theperrygroup/agents/tests.py Traceback (most recent call last): File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/agents/tests.py", line 90, in <module> from repcdocs.tasks import print_slack_users File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/repcdocs/tasks.py", line 10, in <module> from django.contrib.auth.models import User File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/venv/lib/python3.8/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/venv/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/venv/lib/python3.8/site-packages/django/db/models/base.py", line 107, in __new__ app_config = apps.get_containing_app_config(module) File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/venv/lib/python3.8/site-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/venv/lib/python3.8/site-packages/django/apps/registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/Users/x/Dropbox/Portfolio/Django/theperrygroup/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 57, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before … -
Django Multiple Choice Quiz - conditionally change background using python / html
New to django, python, and html here. I'm creating a MULTIPLE CHOICE QUIZ and want the background to conditionally change based on the user's selected answer. I'm trying to use the "IF" function through html. Stylesheet using classes via CSS are working just fine. I made several print calls just to see if my python logic was working and it does (see code below). I think it's something i'm doing wrong from the html side. Side note - all questions and answers are saved in Django database. So for example: The correct answer to question 1 is "Apple". If the user selected "Apple", the webpage should result "Correct! Good job.". For any other answer selected, should result "Wrong!! The correct answer is Apple." My problem for many many many days/hours is that as of now every choice I select results in "Wrong, you are Incorrect" as the resulted background. Even when the correct answer is chosen by the user. Thanks in advance for all of your help! Please see code below. views.py def vote(request, question_id, *args, **kwargs): question = get_object_or_404(Question, pk=question_id) ### temporarily PRINTED call from database to see if python logic works, It works. ID 1 prints out "Apple". … -
Service backend failed to build
Getting the following error while trying to build docker image: ERROR: Service 'backend' failed to build : The command '/bin/sh -c apk add — update — no-cache postgresql-client' returned a non-zero code: 3 How can I resolve this? -
How to convert Function-based generic view with object_list return type to class-based
In Django 1.4 how can I convert a function-based generic view to a class-based view when the return type is an object_list? I'm new to Django and inherited a project I must upgrade from 1.4 to 1.5+ and I can't find an example dealing with this specific situation. I tried changing def parts_list(request) to various permutations of class PartsList(ListView) based on related examples, but nothing worked and I feel like I'm in the weeds on which direction to take with this. Here's the deprecation warning signaling the needed change: /home/administrator/partsdb/vrt1/local/lib/python2.7/site-packages/django/views/generic/list_detail.py:10: DeprecationWarning: Function-based generic views have been deprecated; use class-based views instead. Relevant code snippets urls.py part_info_dict = {'queryset': Part.objects.all() } (r'^parts/(?P<object_id>[\d]+[\w-]*)/$', 'django.views.generic.list_detail.object_detail', part_info_dict), views.py from django.views.generic.list_detail import object_list # This view is a wrapper to call object_list with a different query set than the default. def parts_list(request): prefix = request.GET.get('type', False) value = request.GET.get('filter', False) extra_context = {} qs = Part.objects.all() if prefix: if prefix == '00': qs = Part.objects.all() else: qs = Part.objects.filter(part_number__startswith=prefix) extra_context['type'] = prefix if value: qs = Part.objects.filter(Q(part_number__icontains=value) | Q(description__icontains=value)) extra_context['filter'] = value return object_list(request, queryset=qs, paginate_by=settings.PAGINATE_BY, extra_context=extra_context) -
Django deployed on GKE cannot be accessed by LoadBalancer
Basically I have this django app which has the pods and loadbalancer services running successfully in GKE. But I cannt access the app through the external Ip in loadbalance with the port. Firstly here is my pods and loadbalancer status: Justins-MacBook-Pro-166:Django-RealEstate qingyuan$ kubectl get svc polls NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE polls LoadBalancer 10.108.2.157 104.155.130.204 8000:30575/TCP 3m24s Justins-MacBook-Pro-166:Django-RealEstate qingyuan$ kubectl get pods NAME READY STATUS RESTARTS AGE polls-db68f9d76-8mgrw 2/2 Running 0 3m43s polls-db68f9d76-k85rw 2/2 Running 0 3m43s polls-db68f9d76-qjsbt 2/2 Running 0 3m43s And here is my dockerfile: FROM gcr.io/google_appengine/python LABEL maintainer qm28@georgetown.edu # Create a virtualenv for the application dependencies. RUN virtualenv -p python3 /env ENV PATH /env/bin:$PATH #Prevents Python from writing pyc files to disc (equivalent to python -B option)# ENV PYTHONDONTWRITEBYTECODE 1 # So the logs can always write to container logs and not get buffered at first place ENV PYTHONUNBUFFERED 1 WORKDIR /app ADD requirements.txt /app/requirements.txt RUN /env/bin/pip install --upgrade pip && /env/bin/pip install -r /app/requirements.txt ADD . /app CMD gunicorn realestate.wsgi:application --bind 0.0.0.0:8000 here is my yml file: apiVersion: apps/v1 kind: Deployment metadata: name: polls labels: app: polls spec: replicas: 3 # selector: when deployment create the pods, it will actually created by the kubernetes … -
Django : serving static files with Nginx and docker
I am using 2 containers : one for django, one for Nginx, and I try to serve static files. Here are the port forwardings : I made a schema of the configuration : The containers are on the same server, and django is listening on port 9000 while Nginx n port 8080. Nginx can ping django, both through normal network and through docker's bridge network. I configured on the right the Nginx to listen on port 8080 and redirect non-static / media file to django (I am a first-time user of Nginx, adapting https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html) . (I created my own dockerfile). I know django is working because I can see it on my browser, the same for Nginx (the "not found" is ok for me : the server is running, and I am aksing for random-non-existing media). The issue comes when trying to fetch an answer from django going throught Nginx : the redirection doesn't work. It looks like Nginx can not find django. What do I / Could I do wrong ? -
django object has no attribute status_code
I am learning to develop and trying to develop a screen in django 1.1 and I am getting this error below. I already took a look at some stacks I already looked at httpresponse, however, I was not successful could someone help me and explain what could be wrong? I'm getting this error on the console: Internal Server Error: /gerencia-margem/list Traceback (most recent call last): File "/home/murilo/virtualenv/intranet_erp/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 131, in get_response response = middleware_method(request, response) File "/home/murilo/virtualenv/intranet_erp/local/lib/python2.7/site-packages/django/middleware/locale.py", line 38, in process_response if (response.status_code == 404 and not language_from_path and AttributeError: 'HistoricoComissao' object has no attribute 'status_code' [18/Nov/2020 13:30:06] "GET /gerencia-margem/list HTTP/1.1" 500 77145 This is models, # -*- coding: utf-8 -*- from django.db import models class HistoricoComissao(models.Model): class Meta: verbose_name = u'Historico Comissão' verbose_name_plural = u'Historico Comissões' pednum = models.CharField(max_length=40, blank=True) margem = models.DecimalField(decimal_places=4, max_digits=15, null=True, blank=True) data = models.DateTimeField() historico = models.TextField((u'Historico HTML'), blank=True) status = models.PositiveSmallIntegerField(choices=[(1, 'Em Aberto'), (3, 'Pendente'), (4, 'Finalizado'),]) def __unicode__(self): return str(self.pednum) this is the views from django.views import View from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from ..models import HistoricoComissao def listview(request): template_name = 'comissao/margenslist.html' comissoes = HistoricoComissao.objects.all context = { 'comissoes': comissoes } return render(request,template_name,context) this … -
convert timezone pytz string to offset in python/django
I am using django/python How do I convert pytz timezone string such as 'Asia/Kuala_Lumpur' to offset information ('+0800' or '80'). I am not able to find the exact function here:https://docs.djangoproject.com/en/3.1/topics/i18n/timezones/ I would like to use it in moment.js like this: Format date in a specific timezone so the question is: 'Asia/Kuala_Lumpur' --> convert to ---> '+0800' -
How can I make a relation beetween serializers in Django Rest?
A simple E-commerce app has 3 models: class Order(models.Model): """Order model.""" id = models.AutoField(primary_key=True) date_time = models.DateTimeField() @classmethod def get_total(self, obj): """Get total method. Calculate the total price of the order. """ details = OrderDetail.objects.filter(order=obj) return sum([i.price * i.cuantity for i in details]) class OrderDetail(models.Model): """Order Detail model. Primary key will be created automatically and inevitably. """ order = models.ForeignKey('sales.Order', related_name='details', on_delete=models.CASCADE) cuantity = models.IntegerField() price = models.FloatField(null=True) product = models.ForeignKey('products.Product', on_delete=models.CASCADE) @classmethod def get_product_price(cls, obj): """Get product price, and put it on the order detail price. """ obj.price = obj.product.price obj.save() return obj.price class Product(models.Model): """Product model.""" id = models.CharField(max_length=20, primary_key=True) name = models.CharField(max_length=25) price = models.FloatField() Product objects are already been created in one endpoint, but I need to create a new order with its order details, all in one endpoint. For that I have to use a ModelViewSet and ModelSerializer. I've tried this way: class DetailSerializer(serializers.ModelSerializer): """Order Detail model serializer.""" product_id = serializers.CharField() product = ProductSerializer(read_only=True) price = serializers.SerializerMethodField() class Meta: model = OrderDetail fields = ['cuantity', 'price', 'product_id', 'product'] read_only_fields = ['price'] def get_product(self): """Get the product from his id.""" return Product.objects.get(id=self.product_id) def get_price(self, obj): """Get the price for every detail.""" return OrderDetail.get_product_price(obj) class OrderDetailedSerializer(serializers.ModelSerializer): """Order … -
how to set selected value of a select tag from database in django
I'm trying to make an edit screen. What I want to do is render the data stored as default values of the select tag. Forms.py class EditGroupForm(ModelForm): class Meta: model = Group fields = ["current_year", "career", "commission", "subject", "contacts"] widgets = { 'name': TextInput(attrs={ "placeholder" : "", "class": "form-control" }), 'subject': Select(attrs={ "class": "form-control" }), 'contacts': SelectMultiple(attrs={ "class": "form-control" }) } Views.py def edit_group(request, id): if request.method == "GET": form = EditGroupForm() group = Group.objects.get(id=id) form.name = group.name return render(request, "edit-group.html", {'form': form, 'group':group}) edit-group.html <div class="card-header"> <h5>Edit group: {{form.name}}</h5> </div> <form> {% csrf_token %} <div class="form-group"> <label for="inputSubject">Subject</label> <div class="input-group mb-3"> {{ form.subject }} </div> </div> <div class="form-group"> <label for="inputContactList">Contacts</label> <div class="input-group mb-3"> {{ form.contacts }} </div> </div> <button type="submit" class="btn btn-primary shadow-2 mb-4 float-right">Save</button> <a class="btn btn-secondary float-right" href="/groups" role="button">Cancel</a> </form> Right now, there is no default selected value. How can I do this? -
drf serializer don't find value because of is_html_input() function
I'm tiring to post many files with nested data and I got an error of "this field is required", after debugging I found that the serializer searching for field using regex ( in this line ), this is because of is_html_input() which returns true but the data was well decoded I can retrieve it with data.get('field_name') instead -
Django: Access query_params in ModelViewSet method 'get_numbers_fruit'
I have FruitViewSet(viewsets.ModelViewSet): My view is accessing my viewset with: FruitViewSet.get_numbers_fruit() However, if I run print(self.request.query_params) inside my method, I receive the error: 'WSGIRequest' object has no attribute 'query_params' I have read that this is inaccessible on the first go round, but I can't figure out how to prevent it so as to allow access no the second. -
Django Rest Framework: After creating an object assign it to other model
I have two models - Meeting Room and Rezervations and now I need to somehow connect these two. So basically my logic for this is simple: User Creates an Meeting room through API and later on he can create reservations for many users (not one). For this I have this model: class Reservations(models.Model): statusTypes = [ (0, "Valid"), (1, "Cancelled") ] to = models.ForeignKey(Employees, on_delete=models.CASCADE) title = models.CharField(max_length=150, blank=False, null=False) status = models.IntegerField(choices=statusTypes, null=False, blank=False, default=0) date_from = models.DateTimeField() date_to = models.DateTimeField() def cancel_reservation(self): self.status = 1 self.save() print('Reservation is now', self.status) return True class Meta: db_table = "Reservations" def __str__(self): return str(self.id) class MeetingRooms(models.Model): public_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, blank=False, null=False, max_length=36) creator = models.ForeignKey(Employees, on_delete=models.CASCADE) reservations = models.ManyToManyField(Reservations) secret_key = models.CharField(max_length=128, null=False, blank=False) date_created = models.DateTimeField(auto_now_add=True) # There could be a lot of reservations, so we will just leave it as it is. def create_secretKey(self, secret_key): return make_password(secret_key, hasher="argon2") def check_secretKey(self, secret_key): return check_password(secret_key, self.secret_key) class Meta: db_table = "MeetingRooms" def __str__(self): return str(self.id) But the thing is that I can't figure out how can I do it with rest-framework. RestFramework-MeetingRoom RestFramework-Rezervations Serializers : from rest_framework import serializers from main.models import MeetingRooms, Reservations class MeetingRoomSerializer(serializers.ModelSerializer): class Meta: model … -
I cannot migrate the change I made to the model
I have a User model written in AbstractBaseUser. When I add new fields on this model and run python manage.py makemigrations and then python manage.py migrate --run-syncdb, django tells me that nothing changes. I would like to add that there is no migrations folder inside this User app. -
Django - How could I create a method of allowing the user to edit an existing note?
I'm working on an application which allows users to create, edit, and delete notes for artists and their shows at venues. Currently I have a method for creating new notes and deleting as example, how could I create a method of allowing the user to edit an existing note? Here is what I currently have, I also thrown in repository links as reference to help explain how my application works. https://github.com/claraj/lmn/blob/master/lmn/urls.py #Note related path('notes/latest/', views_notes.latest_notes, name='latest_notes'), path('notes/detail/<int:note_pk>/', views_notes.note_detail, name='note_detail'), path('notes/for_show/<int:show_pk>/', views_notes.notes_for_show, name='notes_for_show'), path('notes/add/<int:show_pk>/', views_notes.new_note, name='new_note'), path('notes/detail/<int:note_pk>/delete', views_notes.delete_note, name='delete_note'), https://github.com/claraj/lmn/blob/master/lmn/views/views_notes.py @login_required def new_note(request, show_pk): show = get_object_or_404(Show, pk=show_pk) if request.method == 'POST' : form = NewNoteForm(request.POST) if form.is_valid(): note = form.save(commit=False) note.user = request.user note.show = show note.save() return redirect('note_detail', note_pk=note.pk) else : form = NewNoteForm() return render(request, 'lmn/notes/new_note.html' , { 'form': form , 'show': show }) @login_required def delete_note(request, note_pk): # Notes for show note = get_object_or_404(Note, pk=note_pk) if note.user == request.user: note.delete() return redirect('latest_notes') else: return HttpResponseForbidden https://github.com/claraj/lmn/blob/master/lmn/templates/lmn/notes/note_list.html <form action="{% url 'delete_note' note.pk %}" method="POST"> {% csrf_token %} <button type="submit" class="delete">Delete</button> </form> -
Troubles accessing a file from a directory from Django's views.py
I am trying to access a Matlab .mat file from a function in my views.py. I'm running into various errors. FileNotFoundErrors or file or directory not found. Depending on what I'm doing in views.py and settings.py to access that file. I have tried and tested various things according to the docs and my various googles, but coming up against a wall. I'm hoping SO can help me out. Right now I have the following configured: views.py import os from django.conf import settings def pig_data(request): file_path = os.path.join(settings.FILE_DIR, 'RingData_21Oct2020_PV96.mat') with open(file_path, 'r') as source: mat = loadmat('RingData_21Oct2020_PV96.mat') fat_mat = mat.items() return redirect('/display') settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) FILE_DIR = os.path.abspath(os.path.join(BASE_DIR, '/static/main')) The results fat_mat = mat.items() should appear on a simple html page. Nothing crazy. All I'm doing is clicking a button: <button onclick="document.location='/pig_data'">Input</button> My routes are all good and working as expected. urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index), path('calibration', views.calibrate), path('download', views.download), path('display', views.display), path('pig_data', views.pig_data), ] Traceback: File "C:\dev\steady_flux\env\quest_buster\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\dev\steady_flux\env\quest_buster\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\dev\steady_flux\env\quest_buster\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\dev\steady_flux\quest_buster\main\views.py" in pig_data 66. with open(file_path, 'r') … -
Django & Celery. Group not executing tasks in parallel
I'm trying to execute some task with different arguments in parallel. For example, I have this function: def printRange(start, stop): for i in range(start, stop, 1): print(i) And I want it to execute in parallel with different start's and stop's. As I working in Django, my Celery config files looks like this: # celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myProj.settings') app = Celery('myProj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() # __init__.py of project's root folder from .celery import app as celery_app __all__ = ('celery_app',) Next, I have task like one in example: # tasks.py import logging from celery import shared_task @shared_task def test_task(task_number, start, stop): for i in range(start, stop, 1): logging.info(f'task {task_number} says: {i}') As expected output from parallel task, I waited logs like: ... task 0 says: 2312 task 0 says: 2313 task 1 says: 7438 task 0 says: 2314 task 1 says: 7435 ... But, got just linear execution: task 0 says: 0 task 0 says: 1 ... task 0 says: 50000 task 1 says: 50001 task 1 says: 50002 ... task 1 says: 99999 What am I doing wrong? P.S: I had already seen this, and this questions and they don't helped … -
How to extract path params from Django Request object?
Sup people, I'm working on my own role-based authorization decorator for Django and did write some validation classes to be used for each role. My validation classes currently are receiving, as arguments, the request object, and the view itself. But for some roles, I need to extract a client_id from my URL to verify some rules. How can I extract this as a key-value pair from the Request object? I know that Django injects the path params as key-value pairs using keyword arguments but how could I extract this from the request? -
Django 3.1 not serving media files correctly
I have a project running in Django 3.1, and suddenly it has started to fail serving media files (static files uploaded by users), even though I haven't changed anything in settings.py or elsewhere. My main urls.py: from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('cart/', include('cart.urls', namespace='cart')), path('', include('contacts.urls', namespace='contacts')), path('customers/', include('customers.urls', namespace='customers')), path('orders/', include('orders.urls', namespace='orders')), path('account/', include('account.urls')), path('', include('catalog.urls', namespace='catalog')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) From my settings.py: from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath( os.path.join(__file__, os.pardir)))) DEBUG = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join('static'), ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') I don't know and can't figure out where the mistake is, but runserver just keeps throwing 404 when trying to load media files, even though static files (CSS/JS) are being served correctly. -
In django, how do I post a parent and multiple child models at the same time?
So I am trying to make a website that keeps track of when our dogs were taken out last. I have it set up so that there are database models for users, dogs, posts, and actions (what each dog did when they were taken out), which is a child model for the post model. The problem that I am facing currently is trying to create a post and action models for each dog via a post webpage. The error I keep getting is an attribute error for the action model. I have tried to set it up my views in multiple different ways but none seem to work. How can I fix this? forms.py: from django import forms from dog_log_app.models import * class Log_Form(forms.ModelForm): class Meta: model = Post fields = ("issues",) class Action_Form(forms.ModelForm): class Meta: model = Action fields = ("peed", "pooped") views.py: from django.shortcuts import render from django.views.generic import ListView, CreateView from .models import Post, Dog, Action from dog_log_app.forms import * from django import forms from django.contrib.auth.models import User from django.http import HttpResponse, HttpResponseRedirect def home(request): context = { 'posts': Post.objects.all().order_by('-time_posted'), 'actions': Action.objects.all(), 'dogs': Dog.objects.all() } return render(request, 'dog_log_app/home.html', context) def post(request): form_post = Log_Form(request.POST or None) form_action … -
How to use javascript libraries imported from NPM
Context For a long time I was using Bootstrap and other libraries by sources. I mean I was including it as below: - static - vendor - jquery - popper - bootstrap - ... But nowadays, I need to improve myself in managing my web dependencies. For some reasons : Less sources in repositories and a more efficient team project Greater support to choose version or test migrations Saving time for later projects with same dependencies I need to include a library which is only provided through NPM which is codemirror So I am currently trying to manage dependencies via NPM, in a django project. But I'm stuck at a very basic step I guess. I don't know where to continue after npm install --save jquery popper.js bootstrap. I'm disturbed by all examples which are for node.js application... Where I'm stuck I have an index.js at the same level of my main package.json. I thought I had to import my scripts in this file, then include this script in my page. So I tried require Jquery then bootstrap, but I get errors on bootstrap required because jquery is undefined. I don't have much code to show, the more I need … -
How can i use Base64FileField for save file as base 64?
I want to save file with pdf txt and png extensions as bas64 .how can i write this class that support all of extentions.in other site i found Class Base64ImageFile ,but this class support image only. -
Select a valid choice. That choice is not one of the available choices. Django Error
Hy, I am a beginner in django and I am trying to create an App like Quora. I want the user to answer based on the question selected which I get from list of items. I wrote both class based and function based views but I get the same error of "Select a valid choice. That choice is not one of the available choices." Models.py class Question(models.Model): current_user = models.ForeignKey(User,on_delete=models.CASCADE) question = models.TextField() question_date_pub = models.DateTimeField(auto_now_add=True) def __str__(self): return (self.question) def get_absolute_url(self): return reverse('questions') class Answer(models.Model): current_user = models.ForeignKey(User,on_delete=models.CASCADE) question = models.ForeignKey(Question,on_delete=models.CASCADE) answer = models.TextField() def __str__(self): return self.answer def get_absolute_url(self): return reverse('questions') Forms.py from django import forms from .models import Question,Answer # class AskQuestionForm(forms.ModelForm): class Meta: model = Question fields = ['current_user','question'] widgets = { 'current_user':forms.TextInput(attrs={'class':'form-control','id':"my_user_input","type":"hidden"}), 'question':forms.Textarea(attrs={'class':'form-control'}) } class AnswerQuestionForm(forms.ModelForm): class Meta: model = Answer fields = ['current_user','question','answer'] widgets = { 'current_user':forms.TextInput(attrs={'class':'form-control','id':"my_user_input","type":"hidden"}), 'question':forms.TextInput(attrs={'class':'form-control','id':"current_question"}), 'answer':forms.Textarea(attrs={'class':'form-control'}) } Views.py def AnswerQuestionView(request,pk): question = Question.objects.get(pk=pk) if request.method == "POST": form = AnswerQuestionForm(request.POST or None) if form.is_valid(): form.save() else: form = AnswerQuestionForm() return render(request,'answer_question.html',{'form':form,'question':question}) This is the class based view also giving the same error class AnswerQuestionView(CreateView): model = Answer form_class=AnswerQuestionForm template_name = "answer_question.html" def get_context_data(self,*args,**kwargs): context = super(AnswerQuestionView,self).get_context_data(*args,**kwargs) question = get_object_or_404(Question,id=self.kwargs['pk']) context['question'] = … -
Exception inside application: __init__() takes 1 positional argument When adding ASGI_APPLICATION in Django 3.1 for channels
I am getting the following error when adding channels in Django. Exception inside application: __init__() takes 1 positional argument but 2 were given Traceback (most recent call last): File "/home/dell/Desktop/s/s/s-env/lib/python3.6/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/home/dell/Desktop/s/s/s-env/lib/python3.6/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/home/dell/Desktop/s/s/s-env/lib/python3.6/site-packages/channels/routing.py", line 160, in __call__ send, File "/home/dell/Desktop/s/s/s-env/lib/python3.6/site-packages/asgiref/compatibility.py", line 33, in new_application instance = application(scope) TypeError: __init__() takes 1 positional argument but 2 were give The application works fine on WSGI configuration.The above error only appears when ASGI_APPLICATION = 'app.routing.application' is added. Since it's showing error originating from static files, I have tried generating static files again but that doesn't help.