Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'django.db.utils.IntegrityError: UNIQUE constraint failed:' error still showing after i have deleted the attribute
I was trying to add an attribute to a django model and it showed me 'django.db.utils.IntegrityError: UNIQUE constraint failed:' error. So i backed down and just deleted the attribute, but it still shows me the error, so please how can i delete the attribute permanently. -
Using django form within custom html template
I have a html file that I wanna use this template to render my form and save it to my database How to do this? HTML code: <div class="container-contact100"> <div class="wrap-contact100"> <form class="contact100-form validate-form" enctype="multipart/form-data" method="POST"> {% csrf_token %} <span class="contact100-form-title"> Add Item! </span> <div class="wrap-input100 validate-input" data-validate="Name is required"> <span class="label-input100">Title</span> <input class="input100" type="text" name="name" placeholder="Enter food name"> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input"> <span class="label-input100">Price</span> <input class="input100" type="number" name="price" placeholder="Enter food price"> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input" data-validate = "Message is required"> <span class="label-input100">Description</span> <textarea class="input100" name="message" placeholder="Your description here..."></textarea> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input" data-validate="Image is required"> <input type="file" class="custom-file-input" id="customFile" name="filename"> <label class="custom-file-label" for="customFile">Choose file</label> <span class="focus-input100"></span> </div> <div class="container-contact100-form-btn"> <div class="wrap-contact100-form-btn"> <div class="contact100-form-bgbtn"></div> <button class="contact100-form-btn" type="submit"> <span> Add <i class="fa fa-long-arrow-right m-l-7" aria-hidden="true"></i> </span> </button> </div> </div> </form> </div> </div> <div id="dropDownSelect1"></div> and here is my forms.py : from django import forms from .models import Product class AddItemForm(forms.ModelForm): class Meta: model = Product fields = '__all__' even you can access my project from this link via github: https://github.com/imanashoorii/FoodMenu.git -
django check-contraint boolean expression [postgresql]
So I have a model like this class Role(BaseModel): class Meta: verbose_name = 'role' verbose_name_plural = 'roles' ordering = ['position', 'cluster'] required_db_features = { 'supports_deferrable_unique_constraints', } constraints = [ models.UniqueConstraint( fields=['position', 'cluster'], name='deferrable_unique_role_position', deferrable=models.Deferrable.DEFERRED ), models.CheckConstraint( name='default_role_check', check=models.Q( is_default=True, position=1, color='#969696', name='@everyone' ) ) ] permission_flags = [ 'READ_DATA', 'WRITE_DATA', 'MANAGE_RECORDS', 'MANAGE_ROLES', 'MANAGE_CLUSTER', 'MANAGE_DATASHEETS', 'MANAGE_FIELDS', 'MANAGE_CONSTRAINTS', 'KICK_MEMBERS', 'MANAGE_MEMBERS', ] default_perm_flags = ['READ_DATA', 'WRITE_DATA', 'MANAGE_RECORDS'] def __str__(self): return self.name objects = managers.RolesManager() positions = managers.PositionalManager() permissions = BitField(flags=permission_flags, default=default_perm_flags, db_index=True) position = models.PositiveSmallIntegerField(null=True, blank=True, db_index=True, editable=True) name = models.CharField(max_length=100, validators=[MinLengthValidator(2)], db_index=True, default='new role') color = ColorField(db_index=True, default='#969696') is_default = models.BooleanField(default=False, db_index=True) cluster = models.ForeignKey('api_backend.Cluster', on_delete=models.CASCADE, editable=False) Basically I want to enforce a check constraint on this model such that when the model has the is_default field set to True, the name must always be @everyone the color must always be #969696 the position must always be 1. I tried to implement the same, however my current implementation doesn't work. While using serializers, I can edit the default role's name, and no exceptions are raised. I am using postgresql at the backend. Can someone please help me? thanks in advance! -
How to make the LINE message API access token change dynamically on request
I want to use django to change the access token of the LINE message API depending on the request. However, the decorator is not reflected because the handler is declared in the post function. How can I set the handler? In order to change the access token dynamically, I must receive a request. from django.shortcuts import render from django.http import HttpResponseForbidden, HttpResponse from django.views.decorators.csrf import csrf_exempt from linebot import (LineBotApi, WebhookHandler) from linebot.exceptions import (InvalidSignatureError) from linebot.models import ( MessageEvent, TextMessage, TextSendMessage, ) import os from user_app.models import Profile from django.views import View class Api(View): @csrf_exempt def post(self, request, *args, **kwargs): YOUR_CHANNEL_ACCESS_TOKEN = "22222222222222" ←Change dynamically on request YOUR_CHANNEL_SECRET = "11111111111111111111"Change dynamically on request line_bot_api = LineBotApi(YOUR_CHANNEL_ACCESS_TOKEN) handler = WebhookHandler(YOUR_CHANNEL_SECRET) signature = request.META['HTTP_X_LINE_SIGNATURE'] body = request.body.decode('utf-8') try: handler.handle(body, signature) except InvalidSignatureError: HttpResponseForbidden() return HttpResponse('OK', status=200) @handler.add(MessageEvent, message=TextMessage) def handle_text_message(event): print("dddd") line_bot_api.reply_message(event.reply_token, TextSendMessage(text=event.message.text)) -
How to work with multiple databases in Django [using Database Routers]
I need to isolate django`s default (auth, contenttypes, sessions) apps database, I read in documentation [Multiple Databses][1] all is clear and well explained, but not working to me :( settings.py DATABASES = { 'default_django': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'OPTIONS': { 'options': '-c search_path=eos,public' }, 'NAME': '****', 'USER': '*****', 'PASSWORD': '****', 'HOST': 'localhost', 'PORT': '5432', } } DATABASE_ROUTES = ['core.dbrouter.AuthRoute', 'core.dbrouter.GisRoute'] and ./core/dbrouter.py class AuthRouter: """ A router to control all database operations on models in the 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', """ route_app_labels = { 'auth', 'admin', 'contenttypes', 'sessions', 'messages', 'staticfiles' } def db_for_read(self, model, **hints): """ Attempts to read auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return 'default_django' return None def db_for_write(self, model, **hints): """ Attempts to write auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return 'default_django' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the auth or contenttypes apps is involved. """ if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the auth and contenttypes apps only appear in … -
Simple search in django-cms
I'm trying to implement a simple search in Django-cms (search article by title and description). The description field is a Django-cms Placeholder and I can't access its content. Any suggestion on how to do this? The model: class Article(models.Model): title = models.CharField(max_length=200) intro = models.TextField(max_length=300, blank=True) description = PlaceholderField('description') The view: from .models import Article from django.db.models import Q class ArticlesListView(generic.ListView): template_name = 'article/index.html' def get_queryset(self): search_string = self.request.GET.get('search', None) #search within title #result = Article.objects.filter(Q(title__icontains=search_string)) # works as expected #search within title and content # error: "Related Field got invalid lookup: icontains" result = Article.objects.filter(Q(title__icontains=search_string) | Q(description__icontains=search_string)) return result (django 3.0.11, django-cms 3.7.4, Python 3.7.8) -
How to raise different messages when the ValidationError is caused due to max_length limit and min_length limit in Django
I want to create a model in Django where I could introduce character values for a given field (task), with min_limit=1 and max_limit=255. The code would be something like this in the models.py file: from django.db import models from django.core.validators import MinLengthValidator, MaxLengthValidator from django.forms import ModelForm class ListModel(models.Model): task = models.CharField(max_length= 255, validators = [MinLengthValidator(1), MaxLengthValidator(255)]) status = models.BooleanField(default=False) class ListForm(ModelForm): class Meta: model = ListModel fields = ["task", "status"] Now, if the form is not valid I want to show different messages depending on whether it is invalid because of max_length>255 or because of min_length<1, the code would be something like this in the views.py file: from django.shortcuts import render, redirect from django.contrib import messages from django.http import HttpResponseRedirect from django.urls import reverse from .models import ListModel, ListForm def index(request): if request.method == 'POST': form = ListForm(request.POST) if form.is_valid(): form.save() alltasks = ListModel.objects.all() return HttpResponseRedirect(reverse("index")) else: if max_length > 255: messages.info(request, ('Maximum length limit: 255 characters!')) else: messages.info(request, ('No Task added!') return redirect('index') else: alltasks = ListModel.objects.all() return render(request, "index.html", {'alltasks': alltasks}) Now the problem is that the above code is giving the error name 'max_length' is not defined which is quite obvious as in views.py I have … -
django Page not found (404) forms
i'm building a simple app using django and i got this error when i'm making an authentication here is the error Page not found (404) Request Method: GET Request URL: http: / /localhost:8000/POST?csrfmiddlewaretoken=AZSGUVU7Z13xZoSOsuvFrSPDGy1ZXfHjeJtpHW3HCByK4We0fyLTihcIJsUKUKjt&username=a2020&password1=123456&password2=123456 here is views.py from django.shortcuts import render,redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login def home(request): return render(request,'home.html') def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request,user) return redirect('home') else: form = UserCreationForm() return render(request,'signup.html',{'form':form}) here is urls.py from django.urls import path,include from . import views urlpatterns = [ path('',views.home,name="home"), path('signup',views.signup,name="signup") ] -
Django 3 NameError: name 'model_name' is not defined
I know this question has come up but many answers refer to older versions of Django and Python. I am running Django 3 and Python 3. Besides in our project we have decided to separate each model in its own file under a "models" folder. Please see below our tree structure: ├── db.sqlite3 ├── manage.py ├── poi │ ├── admin.py │ ├── apps.py │ ├── CHANGELOG.md │ ├── fabfile.py │ ├── __init__.py │ ├── LICENSE │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── 0002_auto_20210104_1048.py │ │ ├── __init__.py │ │ └── __pycache__ │ │ ├── 0001_initial.cpython-38.pyc │ │ ├── 0002_auto_20210104_1048.cpython-38.pyc │ │ └── __init__.cpython-38.pyc │ ├── models │ │ ├── __init__.py │ │ ├── layer.py │ │ ├── poi.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-38.pyc │ │ │ ├── layer.cpython-38.pyc │ │ │ ├── poi.cpython-38.pyc │ │ │ └── tag.cpython-38.pyc │ │ └── tag.py │ ├── models.py In our models/init.py we have: from .poi import Poi from .tag import Tag from .layer import Layer In our models/poi/poi.py we have: from django.db import models from .tag import Tag from .layer import Layer class Poi(models.Model): ... ... tags = models.ManyToManyField('Tag', through='Layer') def __str__(self): return self.name In our … -
how to filter year from datefield in django
Basically I want to use 'chartjs' for display "Clustered Bar chart", with following things year wise Total amount Amount Received Amount Left I want to fetch data from data base and display it on chart, I have saved data of all above field 3 fields in one table for each date and I want to also fetch year from Datefield. Main things is how to display Clustered bar chart by fetching data from database for each year. class Allinvoice(models.Model): company_choice = ( ('VT_India', 'VT_India'), ('VT_USA', 'VT_USA'), ) company = models.CharField( max_length=30, blank=True, null=True, choices=company_choice) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) project = models.ForeignKey(Allproject, on_delete=models.CASCADE) invoice_title = models.CharField(max_length=15) invoice_id = models.IntegerField(primary_key=True) currency = models.ForeignKey(Currency, on_delete=models.CASCADE) invoice_amount = models.IntegerField() invoice_date = models.DateField( blank=True, null=True) invoice_duedate = models.DateField( blank=True, null=True) invoice_description = models.TextField() def __str__(self): return str(self.invoice_id) class Paymentdete(models.Model): payment_id = models.IntegerField(primary_key=True) invoice = models.ForeignKey( Allinvoice, on_delete=models.CASCADE) total_amount = models.IntegerField() amountreceived = models.IntegerField() amount_left = models.IntegerField() currency = models.ForeignKey(Currency, on_delete=models.CASCADE, null=True) date = models.DateField( blank=True, null=True) paymentmethod = models.ForeignKey( Allpaymentmethod, on_delete=models.CASCADE) def __str__(self): return str(self.payment_id) So, above is the code of my 2 models.So, i want to get total of all data yearwise for example for year 2019= Total Amount,Amount Received,and amount Left for year … -
Mark as Read for a page in Django
I followed Sentdex Django tutorials to build a simple website. Now I want to add mark as read for each tutorial. If every tutorial is read then that particular series should be marked as read. Can you suggest how should I approach? class blogCategory(models.Model): blog_category = models.CharField(max_length=200) image = models.ImageField (upload_to ='static/images/models') category_summary = models.CharField(max_length=200) category_slug = models.CharField(max_length=200) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.blog_category class blogSeries(models.Model): blog_series = models.CharField(max_length=200) image = models.ImageField (upload_to ='static/images/models') blog_category = models.ForeignKey(blogCategory, default=1, verbose_name = "Category", on_delete = models.SET_DEFAULT) series_summary = models.CharField(max_length=200) class Meta: verbose_name_plural = "Series" def __str__(self): return self.blog_series class blog(models.Model): completed=models.BooleanField(default=False) blog_title = models.CharField(max_length=200) image = models.ImageField (upload_to ='static/images/models',blank=True) blog_contents = models.TextField(default="") blog_publishedDate = models.DateTimeField("Date Published",default=datetime.now()) blog_series = models.ForeignKey(blogSeries, default=1, verbose_name="Series", on_delete=models.SET_DEFAULT) blog_slug = models.CharField(max_length=200, default=1) def __str__(self): return self.blog_title -
AJAX post request with django and python
I am trying to build a web app on django where a user can record something which then gets turned into text and after that sent to the server with AJAX. I did some research and found this article: https://medium.com/@manask322/implementing-speech-to-text-feature-in-a-django-app-f0fa53bb3e03 So I copied the html code: (this is only the part I copied) <div id='result'> Your text will appear here </div> <br> <div id= 'record'> <button onclick="startConverting()" class='btn btn-info btn-sm' id="re">record</button> <button class='btn btn-info btn-sm ml-3' value="Send" id="send">Send</button> </div> <script> function startConverting() { document.getElementById("re").style.visibility = "hidden"; var r=document.getElementById('result'); var spr=new webkitSpeechRecognition(); //Initialisation of web Kit spr.continuous=false; //True if continous conversion is needed, false to stop transalation when paused spr.interimResults=true; spr.lang='en-IN'; // Set Input language spr.start(); //Start Recording the voice var ftr=''; spr.onresult=function(event){ var interimTranscripts=''; for(var i=event.resultIndex;i<event.results.length;i++) { var transcript=event.results[i][0].transcript; transcript.replace("\n","<br>") if(event.results[i].isFinal){ ftr+=transcript; } else interimTranscripts+=transcript; } r.innerHTML=ftr +interimTranscripts ; }; spr.onerror=function(event){}; } $(document).ready(function() { $("#send").click(function(event){ $.ajax({ type:"POST", url:"/audio_data", data: { send : $('#result').html() }, }); }); }); </script> </div> But changed the function in views.py a bit: @csrf_exempt def audio_data(request): if request.method == 'POST': result = request.POST['send'] return render(request, 'success.html') elif request.method == 'GET': return render(request, 'afterContinue.html') The recording works and it also displays the text you say but when … -
Twisted , Channels is not installing - nor through pip neither through Manual Installation
I am building a Blog WebApp. Everything is working fine. BUT Twisted is not installing in cmd. -----------------------------------------The Problem---------------------------------------- My code consumers.py from channels.generic.websocket import AsyncJsonWebsocketConsumer When i import this in consumers.py an Error is raised in cmd while server was running. The Error was :- ModuleNotFoundError: No module named 'channels.generic' Then i searched this Error on Google then, I saw an Answer of this Question and The Answer was to pip install channels. Then i install it, AND while installing it , An main/Big Error is raised This Error. AND i now think this error is raising from Twisted, because channels and twisted are connected libraries This Error is raising again and again, whenever i try to install channels and Twisted. Before few hours ago i was trying to install Twisted through pip. BUT then error occurred and then i installed it manually from Here. I downloaded Twisted‑20.3.0‑cp38‑cp38‑win_amd64.whl. AND my python version is Python 3.8.2. When i open python Idle and enter import twisted to make sure that is is installed or not, Then no error is occuring ( It means that Twisted is installed , Why django-channels is not installing ). BUT twisted is not running in my … -
Redirect www to root (Django WSGI LetsEncrypt) is failing - Not Found
I’m having trouble understanding what’s missing where I’ve added a LetsEncrypt certificate to a Django web application hosted on Linode (CentOS 7) and using Apache. I used the certbot command to obtain an SSL certificate and noted the changes it added to the VirtualHosts files. certbot --apache I included with the root and www domains when prompted. Here’s what LetsEncrypt added to the /etc/httpd/sites-available directory. <server_name>.com.conf <VirtualHost *:80> # Default from LetsEncrypt RewriteEngine on RewriteCond %{SERVER_NAME} =www.<server_name>.com [OR] RewriteCond %{SERVER_NAME} =<server_name>.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> And <server_name>.com-le-ssl.conf (where it wrapped it in mod_ssl and added the LE certificate lines) <IfModule mod_ssl.c> <VirtualHost *:443> # Load wsgi module LoadModule wsgi_module <details> # NOTE. When assigning a LetEncrypt certbot --apache the WSGI lines need to # be commented out. WSGIDaemonProcess <name> <details> WSGIProcessGroup <name> WSGIScriptAlias / <wsgi.py path> Alias /static <static_folder_path> <Directory <static_folder_path>> Require all granted </Directory> Alias /media <media_folder_path> <Directory <media_folder_path>> Require all granted </Directory> <Directory <Django_app_path>> <Files wsgi.py> Require all granted </Files> </Directory> ServerName <servername.com> Include /etc/letsencrypt/options-ssl-apache.conf ServerAlias www.<servername.com> SSLCertificateFile /etc/letsencrypt/live/<servername.com>/cert.pem SSLCertificateFile /etc/letsencrypt/live/<server_name>.com/cert.pem SSLCertificateKeyFile /etc/letsencrypt/live/<server_name>.com/privkey.pem SSLCertificateChainFile /etc/letsencrypt/live/<server_name>.com/chain.pem </VirtualHost> </IfModule> It also added an Include httpd.conf referencing the above. It may have added more. These were the changes I'm aware … -
activate python function with arguments using html in django
So, I'm trying to make a button where you can activate a python script using an HTML button, here's what I got. HTML <script> function login(){ $.ajax({ url: "/python_file", context: document.body }).done(function() { alert('finished python script');; }); } </script> <input id="clickMe" type="button" value="clickme" onclick="login();" /> urls.py urlpatterns = [ path('', views.home, name="index"), path('python_file', views.python_file), ] views.py from django.shortcuts import render def home(request): return render(request, "login/login.html") def python_file(email, password): pass but, how can I pass in an argument into the function? Any help is appreciated! -
How to filter form based on foreign key?
How can I filter fields in my TopForm in such a way that when a user selects a teacher, automatically all other fields show related values to the teacher. Suppose Adam is the teacher and in the Network department teaches network programming in the 4th semester(added in the admin). Now the user selects Adam, when Adam selected, the department dropdown shows only Network which is related to Adam and so on. forms.py class AnswerForm(ModelForm): class Meta: model = Student_Answer fields = ('answer',) labels = {'answer': ''} widgets = { 'answer': RadioSelect(choices=RATING_CHOICES)} class TopForm(forms.Form): teacher = forms.ModelChoiceField(queryset=Teacher.objects.all()) department = forms.ModelChoiceField(queryset=Department.objects.all()) subject = forms.ModelChoiceField(queryset=Subject.objects.all()) semester = forms.ModelChoiceField(queryset=Semester.objects.all()) models.py class Question(models.Model): question = models.CharField(max_length=200) class Department(models.Model): name = models.CharField(max_length=60) class Semester(models.Model): num = models.IntegerField(choices=SEMESTER, default=1) class Subject(models.Model): name = models.CharField(max_length=100) code = models.CharField(max_length=5, null=True) semester = models.ForeignKey(Semester, on_delete=models.CASCADE, null=True) department = models.ManyToManyField(Department) class Teacher(models.Model): name = models.CharField(max_length=200) last_name = models.CharField(max_length=200, null=True) department = models.ManyToManyField(Department) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) class Student_Answer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) department = models.ForeignKey(Department, on_delete=models.CASCADE) semester = models.ForeignKey(Semester, on_delete=models.CASCADE) answer = models.SmallIntegerField(choices=RATING_CHOICES, default=None) -
Reversing in Django - Trying to Reverse from Update View to Detail View in Django
I am trying to reverse to the Detail View after the Update View and to List View after Delete View. How can I implement this. I am getting an error reverse not defined. Thanks #Contents of Models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): OPTIONS_PROFILE_TYPE = ( ('single', 'Single'), ('family', 'Family'), ) OPTIONS_LOCATIONS = ( ('USA', 'USA'), ('Canada', 'Canada'), ) user = models.OneToOneField(User, on_delete=models.CASCADE, help_text='User Name') display_name = models.CharField(null=True, max_length = 16, help_text='Optional Display Name' ) profile_type = models.CharField(null=True, choices=OPTIONS_PROFILE_TYPE, max_length=10) location = models.CharField(null=True, max_length = 30, choices=OPTIONS_LOCATIONS, help_text='Optional Location') biography = models.CharField(null=True, blank=True, max_length = 500, help_text='Optional Biography') # Metadata class Meta: ordering = ['profile_type'] # Methods def get_absolute_url(self): #Returns the url to access a particular instance of MyModelName. return reverse('profile-detail', args=[str(self.id)]) def __str__(self): #String for representing the MyModelName object (in Admin site etc.). return self.user.username #Contents of Views.py from datetime import datetime from django.shortcuts import render from django.urls import path from django.http import HttpRequest from .models import Profile from django.views.generic import FormView, CreateView, DetailView, UpdateView, DeleteView, ListView from django.shortcuts import redirect from django.urls import reverse class ProfileListView(ListView): model = Profile def get_context_data(self, … -
from rest_framework.filters import SearchFilter generates error as cannot import name 'ORDER_PATTERN' from 'django.db
I found out that the line from rest_framework.filters import SearchFilter generates me an error as from django.db.models.sql.constants import ORDER_PATTERN ImportError: cannot import name 'ORDER_PATTERN' from 'django.db.models.sql.constants' (E:\anaconda\envs\AHG_web\lib\site-packages\django\db\models\sql\constants.py) I used that as below: class op_ViewSet(viewsets.ModelViewSet) : # permission_classes = (permissions.IsAuthenticated,) queryset = Op.objects.all().filter() serializer_class = op_Serializer # authentication_classes = [TokenAuthentication , SessionAuthentication , BasicAuthentication] # pagination_class = PageNumberPagination # pagination_class = StandardResultsSetPagination filter_backends = [DjangoFilterBackend , SearchFilter] filter_class = op_filter ordering_fields = ['close_date' , ] ordering = ['close_date'] search_fields = ['website' , 'title' , 'description' , 'organization__name'] @action(detail=True , methods=['Get']) def attachments(self , request , pk) : op = self.get_object() links = Attachments.objects.filter(op_id=op.id) serializer = attachments_Serializer(links , many=True) return Response(serializer.data) previously it was working fine, can anyone help me with the solution. -
Looping through wagtail contents
I’m using wagtail to manage content in my Django app. In my model, I used a structured block like so: class SectionBlock(blocks.StructBlock): header = blocks.CharBlock() content = blocks.RichTextBlock() My page is expected to have multiple distinct headers like introduction, conclusion, etc however the template iteration keeps looping through the first header (introduction). The question is do I rename each item in my SectionBlock class so I can directly access it in the template or there is a simpler solution? class SectionBlock(blocks.StructBlock): header1 = blocks.CharBlock() content1 = blocks.RichTextBlock() header2 = blocks.CharBlock() content2 = blocks.RichTextBlock() {% for block in blocks %} {{ block.value.header1 }} {{ block.value.header2 }} {% endfor %} -
Django Graphene testing - Variable "$input" of required type "PostInput!" was not provided
I have a blog application with Django and Graphene. I'm trying to test a GraphQL mutation query that creates a Post with PostInput fields. When I test the said mutation with a hardcoded query, it works. However, when I use $input, I am facing an issue - Variable "$input" of required type "PostInput!" was not provided.. Here are my schema and test cases. schema.py ... User = get_user_model() # Types class PostType(DjangoObjectType): class Meta: model = Post ... # Input object types class PostInput(graphene.InputObjectType): title = graphene.String(required=True) publish_date = graphene.DateTime() author = graphene.ID(required=True) content = graphene.String(required=True) ... # Mutations class CreatePost(graphene.Mutation): class Arguments: input = PostInput() # Reponse ok = graphene.Boolean() post = graphene.Field(PostType) @classmethod def mutate(cls, root, info, input=None): post_instance = Post( title = input.title, author_id = input.author, content = input.content ) post_instance.save() ok = True return cls(ok=ok, post=post_instance) ... class Mutation: create_post = CreatePost.Field() ... test.py post_create_query = ''' mutation createPost($input: PostInput!) { createPost(input: $input) { ok post { title content } } } ''' class TestPostMutations(GraphQLTestCase): def setUp(self): self.client = Client(schema) self.user = User.objects.create( username = "testuser", password = "tE$tp@$$d0)", email = "test@example.net" ) def test_post_create(self): """ Querying postCreate should create post and return post instance and … -
One-to-many relationship in django models (Relation of one Model with another two Models)
I want to save all the likes in a Like Table. Likes of both Comments and Post, in one table. Is their something like this to achieve this thing: Class Post: ... Class Comment: ... Class Like(models.Model): '''Either of Post or Comment will have to be selected in this field''' post_or_comment = models.Something([Post, Comment], on_delete=models.CASCADE) -
How to display django generic detail view inside a modal with ajax
I want to display the content of an announcement inside a modal when a user clicked on the announcement list. This will be the trigger for the modal in my announcement_list.html: <form name="form" action="#" id="form_have_product_{{y.id}}" method="POST"> {% csrf_token %} <a href="#" id="{{ announcement.pk }}" type="button" class="btn btn-info view-announcement" data-url="{% url 'announcement-detail' pk=announcement.id %}" style="float: right;">View</a> </form> This is my function in my views.py: def get_announcement(request, pk): announcement = Announcement.objects.filter(announcement_id=pk) context = { 'title': announcement.title, 'about': announcement.about, 'author': announcement.author, 'post_date': announcement.post_date } return render(request, 'announcement-details-modal.html', context) For the urls.py: urlpatterns = [path('announcement/<int:pk>/', get_announcement, name='announcement-detail'),] And this is the function for when the user clicks on the announcement list: $(".view-announcement").on("click", function() { var target_url = $(this).attr("data-url"); var csrftoken = $("[name=csrfmiddlewaretoken]").val(); $.ajax({ url: target_url, headers:{ "X-CSRFToken": csrftoken }, success: function(data) { $("#modal").modal("toggle"); $("#modal-content").html(data); } }); }); Currently this code returns the server responded with a status of 500 (Internal Server Error) -
Django+JS: Can't track likes on posts. Bad request 400
Little background: I'm creating twitter like app from the tutorial on youtube. So, I am a beginner in django and just know syntax of JS. Several days ago, I faced the problem where likes of a post are not counting. I think the problem is with serializers or with my environment (django 2.2; python 3.8.5; using VS Code). my action handling view: import random from django.conf import settings from django.http import HttpResponse, Http404, JsonResponse from django.shortcuts import render, redirect from django.utils.http import is_safe_url from rest_framework.authentication import SessionAuthentication from rest_framework.decorators import api_view, authentication_classes, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from .forms import TweetForm from .models import Tweet from .serializers import TweetSerializer, TweetActionSerializer ALLOWED_HOSTS = settings.ALLOWED_HOSTS @api_view(['POST']) @permission_classes([IsAuthenticated]) def tweet_action_view(request, *args, **kwargs): ''' id is required. Action options are: like, unlike, retweet ''' serializer = TweetActionSerializer(data=request.data) if serializer.is_valid(raise_exception=True): data = serializer.validated_data tweet_id = data.get("id") action = data.get("action") content = data.get('content') qs = Tweet.objects.filter(id=tweet_id) if not qs.exists(): return Response({}, status=404) obj = qs.first() if action == "like": obj.likes.add(request.user) serializer = TweetSerializer(obj) return Response(serializer.data, status=200) elif action == "unlike": obj.likes.remove(request.user) elif action == "retweet": new_tweet = Tweet.objects.create( user=request.user, parent=obj, content = content) serializer = TweetSerializer(new_tweet) return Response(serializer.data, status=200) return Response({}, status=200) … -
How to write DateField in django models?
How to write DateField in django models ? without use auto_now_add & forms. class Education(models.Model): e_id=models.AutoField(primary_key=True) University=models.CharField(max_length=90) College_Name=models.CharField(max_length=90) Specialisation=models.CharField(max_length=10) From=models.DateField() To=models.DateField() doc_clinic = models.ForeignKey(to=DoctorProfile, related_name='educationdoctor_clinic', on_delete=models.CASCADE) def __str__(self): return (self.doc_clinic_id) -
Unable to import 'ali.book.models'
Where is the problem with this code that I can not import the Book class? this code in views and The class I want to import is in Models: from django.http import HttpResponse, Http404 from django.shortcuts import render from .book.models import Book def search(request): if 'q' in request.GET and request.GET['q']: q = request.GET['q'] book = Book.objects.filter(title__icontins=q) return render(request, 'search_results.html', {'book' : book, 'query' : q}) else : return HttpResponse('please submit a search term.') class Book: class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) publisher = models.ForeignKey(Publisher, on_delete = models.CASCADE) publication_date = models.DateField(null = True ,blank=True) def __str__(self): return self.title my package: ali/ ali/ views.py book/ models.py