Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save a MultipleChoiceField in Django
I was wondering how can I save a MultipleChoiceField to Django's database (in form submission)? models.py class Model1(models.Model): field = models.CharField(max_length=200, null=False, blank=False, default='') forms.py OPTIONS = ( ('Option 1', 'Option 1'), ('Option 2', 'Option 2'), ('Option 3', 'Option 3'), ) class Model1Form(forms.ModelForm): field = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=OPTIONS) class Meta: model = Model1 fields = '__all__' If you need additional information let me know! Thanks for helping out. -
How to integrate paypal in React Js with server side ( Django REST ) payment execution?
I am trying to integrate paypal in my application. My application has to be built using React JS and backend should be in Django. I have done the Client Side Integration using one npm package which is https://www.npmjs.com/package/react-paypal-express-checkout This is my code in React JS import React from "react"; import ReactDOM from "react-dom"; import PaypalExpressBtn from "react-paypal-express-checkout"; import "./styles.css"; function App() { const client = { sandbox: "AXMUBOcaszqCzfEOC-r--Rn7rMVoEbH9c6XbmyKb04nURqcLhpFxWwwnaUytaMR9UTaE2vwLfi5tqKbT", production: "" }; return ( <div className="App"> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some magic happen!</h2> <PaypalExpressBtn client={client} currency={"USD"} total={500} onSuccess={(p) => console.log(p)} /> </div> ); } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement); I am getting the following response { paid: true cancelled: false payerID: "TLCF8J8F3CZUY" paymentID: "PAYID-MAADRGI6U311288V5285313C" paymentToken: "EC-32J40105H07711055" returnUrl: "https://www.paypal.com/checkoutnow/error?paymentId=PAYID-MAADRGI6U311288V5285313C&token=EC-32J40105H07711055&PayerID=TLCF8J8F3CZUY" address: Object email: "sb-ueclm4695520@personal.example.com" } After the payment, also my sandbox account balance is been deducted. So this is working fine. But I want to do the payment execution securely in server side. How do i achieve it in Django? I have read the docs, they mentioned use SDK. So I have looked into the python sdk which is https://github.com/paypal/Checkout-Python-SDK from paypalcheckoutsdk.orders import OrdersCaptureRequest # Here, OrdersCaptureRequest() creates a POST request to /v2/checkout/orders # Replace APPROVED-ORDER-ID with the actual … -
Error when converting pandas to postgers in django app
Goal: adding data from a fetched json file into a postgres database. Error when running the script: RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. After fetching the data from a link (json), i convert and edit it with pandas. Once done, the goal is to add it to the databas, but i get the mentioned error. The code snippet i use is taken from this answer. [https://stackoverflow.com/questions/37688054/saving-a-pandas-dataframe-to-a-django-model] second_pipeline.py (gets the error) import pandas as pd import requests fox_url = "https://saurav.tech/NewsAPI/everything/fox-news.json" fox_news = requests.get(fox_url).json() df = pd.json_normalize(fox_news) fox_articles = pd.json_normalize(df["articles"].loc[0]) del fox_articles['source.id'] fox_articles["date_publised"] = pd.to_datetime(fox_articles['publishedAt']) del fox_articles['publishedAt'] import os from django.conf import settings import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') settings.configure(DEBUG=True) django.setup() from sqlalchemy import create_engine from models import Article user = settings.DATABASES['default']['USER'] password = settings.DATABASES['default']['PASSWORD'] database_name = settings.DATABASES['default']['NAME'] database_url = 'postgresql://{user}:{password}@localhost:5432/{database_name}'.format( # user=user, # password=password, # database_name=database_name, article_author = fox_articles["author"], article_date_publised = fox_articles["date_publised"], article_title = fox_articles["title"], article_description = fox_articles["description"], article_url = fox_articles["url"], article_urlToImage = fox_articles["urlToImage"], article_content = fox_articles["content"], article_network = fox_articles["source.name"], ) engine = create_engine(database_url, echo=False) fox_articles.to_sql(Article, con=engine) models.py class Article(models.Model): article_author = models.CharField(blank=True, max_length=1000) article_date_publised = models.CharField(blank=True, max_length=500) article_title = models.TextField(blank=True) article_description = models.TextField(blank=True) article_url = models.TextField(blank=True) article_urlToImage = models.TextField(blank=True) article_content = models.TextField(blank=True) … -
match two models field (django)
I have a question answer quiz. I want each form to be responsible for each query when I publish the forms in html. For example I have it now current result. I have to choose the question manually. I want it to happen automatically, i.e. no matter how many questions I have so many forms for each question. what i want -> the end result. I do not understand what I have to change, view or formset should I use, please if you can help me change the code. models.py from django.db import models # Create your models here. class Question(models.Model): question=models.CharField(max_length=100) answer_question=models.CharField(max_length=100, default=None) def __str__(self): return self.question class Answer(models.Model): questin=models.ForeignKey(Question, on_delete=models.CASCADE) answer=models.CharField(max_length=100,blank=True) def __str__(self): return str(self.questin) views.py from django.shortcuts import render from django.shortcuts import render, HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import redirect from .forms import QuestionForm,AnswerForm from .models import Question import random def home(request): form=QuestionForm if request.method=='POST': form=QuestionForm(request.POST) if form.is_valid(): form.save() return render(request, "question/base.html", {"form":form}) def ans(request): form=AnswerForm e=Question.objects.all() if request.method=="POST": form=AnswerForm(request.POST) if form.is_valid(): form.save() return render(request, "question/ans.html", {"form":form, "e":e}) forms.py from django import forms from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Question,Answer class QuestionForm(forms.ModelForm): class Meta: model=Question fields="__all__" … -
Django - Display ValidationError using Ajax
I'm trying to display ValidationErrors using Ajax. I've read many posts about this and tried many things but can't get it to work. forms.py class ContactForm(forms.ModelForm): name = forms.RegexField( regex=r'^[a-zA-Z]+$', max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'}), error_messages={'invalid': _("Wrong First Name, use only letters")}) Error details are stored in data['error'] also having item is_valid. I inspected response data structure in console logging data in Ajax error. According to the structure access values and assign to elements. script - (Ajax error) error: function(data, xhr, errmsg, err){ console.log("data") console.log(data.responseJSON) //console.log(data.responseJSON.errors.name[0]) $('.error').html(data['error']) }, In views.py form.errors passed in JsonResponse() as a dictionary. def contact(request): form = ContactForm(request.POST) data = {} if request.is_ajax(): if form.is_valid(): form.save() return JsonResponse(data) else: data = { 'error': form.errors, 'is_valid': False } return JsonResponse(data, status=400) else: context = { 'form': form, } return render(request, 'pages/contact.html', context) In my script when using console.log('data.responseJSON') i see: In the above image I can access the error message for the field 'name' as data.responseJSON.error.name[0] In my eyes everything seems to be ok however i cannot display message in user. I'm using crispy forms in the template contact.html <div class="col-lg-6"> <div class="form-box"> <h3>Write A Comment</h3> <form class="form" id="contact" method="POST" action="" autocomplete="off"> {% csrf_token %} <div class="messages"></div> <div class="input__wrap … -
In django, when user registered using CustomForm tries to login using Oauth
My Django app has an option for login/register using CustomForm (inherited from the UserCreationForm) as well as Outh. Now the problem is if a user has already signed up using the CustomForm and if the next time he tries to log in using google Oauth then instead of logging in, google Oauth is redirecting to some other signup form which looks like: But as the user is already registered, if he enters the same username/email here then it displays says username taken. So how can I resolve this issue? I mean I want the user to be able to use both custom form as well as Oauth, how can I implement that? My register function in views.py: def register(request): if request.method == 'POST': form = CustomForm(request.POST or None) if form.is_valid(): form.save() return redirect('login') else: return redirect('register') else: return render(request, 'accounts/register.html') forms.py looks something like this: class CustomForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ("username", "email") -
In django, when user registered using CustomForm tries to login using Oauth
My Django app has an option for login/register using CustomForm (inherited from the UserCreationForm) as well as Outh. Now the problem is if a user has already signed up using the CustomForm and if the next time he tries to log in using google Oauth then instead of logging in, google Oauth is redirecting to some other signup form which looks like: But as the user is already registered, if he enters the same username/email here then it displays says username taken. So how can I resolve this issue? I mean I want the user to be able to use both custom form as well as Oauth, how can I implement that? My register function in views.py: def register(request): if request.method == 'POST': form = CustomForm(request.POST or None) if form.is_valid(): form.save() return redirect('login') else: return redirect('register') else: return render(request, 'accounts/register.html') forms.py looks something like this: class CustomForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ("username", "email") -
django: don't register ModelAdmin (exclude module-level code) when running makemigrations / migrate
I have made multiple changes to an existing django model (added new foreign key relation, etc). Before creating and applying these changes with manage.py makemigrations / migrate, I adapted the corresponding admin module's ModelAdmin for that app to reflect these unapplied changes. Running makemigrations now fails with "ProgrammingError: {new_field} does not exist". I figure this happens because when makemigrations runs system checks, the ModelAdmins in admin.py are registered (executing queries on non-existant models that I try to create with the migrations). Question: Is there any straight-forward way to exclude the ModelAdmins from being registered when running manage.py makemigrations / migrate without disabling system checks in total (see Django migration - disabel system checks)? I can solve the problem by deleting my admin.py modules when running makemigrations / migrate and recreating them afterwards. There is really no need to check the admin modules when migrating, but I guess this will happen when registering ModelAdmins on the module-level of admin.py (as in the examples in the django admin documentation). I do not use a custom AdminSite. On more general terms: is there any straight-forward way to exclude specific top-level module code from being executed when running a specific manage.py command like makemigrations … -
How to delete a record after a certain time of it's creation in Django?
I am building an application that has a 'Story Feature' which is quite similar to Instagram's story feature, So I want to delete a story after 24 hours of its creation. So if a story was created on 12:00 PM 1 January 2021, I want to delete it automatically at 12:00 PM 2 January, 2021. I am using django3.1 My Model: class Story(models.Model): user = models.ForeignKey(to=User, on_delete=models.CASCADE) text = models.CharField(max_length=200) image = models.ImageField(blank=True, null=True) video = models.FielField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) expiration_time = models.DateTimeField() I want to delete every record after their particular expiration time. [Expiration time is set in a post_save function ] -
how to create a dictionary from a merged django queryset
Django newbie here trying create a dictionary looking like this {<Course: Phonics>: [40,72,76], <Course: Social Studies>: [48,72,60]} from a merged queryset bla = result1 | result2 | result3 where result1 = Result.objects.filter(pupil__exact = pk,session = session1) result2 = Result.objects.filter(pupil__exact = pk,session = session2) result3 = Result.objects.filter(pupil__exact = pk,session = session3) Here is snippet Result & Session class in models.py class Result(models.Model): pupil = models.ForeignKey('Student', on_delete = models.CASCADE) subject_course = models.ForeignKey('Course', on_delete = models.CASCADE) subject_score = models.IntegerField(default=0) session = models.ForeignKey('Session', on_delete = models.CASCADE) def __str__(self): return '{}, {} result'.format(self.pupil.surname,self.session) class Session(models.Model): sessionedu = models.CharField(choices = SESSION ,max_length=20) term = models.CharField(max_length=15, choices=TERM) resumption = models.DateField(blank=True,default= one_month_away) #active = models.BooleanField(default=False) class Meta: verbose_name = "Session" verbose_name_plural = "Sessions" def __str__(self): return '{} {}'.format(self.sessionedu, self.term) `` thanks -
Django Migrate With Specific Database And Models
I was tried to create a multiple database and i did it. i wrote the code on setting.py like this : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'baseDB', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': '127.0.0.1', 'PORT': '1234', }, 'android': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'androidDB', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': '127.0.0.1', 'PORT': '1234', }, 'ios': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'iosDB', 'USER': 'admin', 'PASSWORD': 'admin', 'HOST': '127.0.0.1', 'PORT': '1234', } } And i was already create a two models.py like : class AndroidModel(models.Model): name = models.CharField(default=False) version = models.CharField() class Meta: app_label = 'android_label' class IosModel(models.Model): name = models.CharField(default=False) version = models.CharField() class Meta: app_label = 'ios_label' And than i created a routes with the name file is dbrouters and the class is MyDBRouter, and the code is like : from api.models import AndroidModel, IosModel class MyDBRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'android_label': return 'android' if UserJembatani._meta.app_label == 'ios': return 'ios' else: return 'default' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'android_label': return 'android' if UserJembatani._meta.app_label == 'ios_label': return 'ios' else: return 'default' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'android_label' or \ obj2._meta.app_label == 'android_label': return True if obj1._meta.app_label == 'ios_label' or \ … -
How to store an image without using django forms
All the solutions that I see are done using django forms, I want to avoid that as I have made a bigger form with image field plus some other input (and added styling and Js check for validation). So how to retrieve a file from a form and store it in django. html form: <form action="{% url 'newcomplaint' %}" class='newc' method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label for="fileToUpload">Add an image(optional)</label> <input type="file" name="fileToUpload" id="fileToUpload"> </div> <button type="submit" class="btn btn-dark bb">Post New Complaint</button> </form> views.py: Here I am getting "MultiValueDictKeyError at /hood/new" def newcomplaint(request): if request.method == "POST": # I dont know how to store a image here image = request.FILES['fileToupload'] #print(image) return HttpResponse('works') model.py from django.db import models from django.core.exceptions import ValidationError from django.contrib.auth.models import User class Complain(models.Model): image = models.ImageField(upload_to='images/', blank=True) -
Notify user if data has changed since page loaded
I have 3 users that can view and commit changes to a database. Let's take for example an app called "personel". These 3 users can view the list of personel, edit personel data, and remove personel entries, from custom views. I am trying to solve this scenario: User A goes to /view_personel_list/ User B goes to /edit_personel/3/, and saves changes. User A is still viewing the non-updated personel list. I know this could be solved using AJAX, but I do not want to refresh. I am looking for a way to notify User A that the database has been changed. -
How can I draw a plot for a model in a Django-admin change list template with all days of the year, including those without data in my model?
I am not very skilled for programming but our little research team has no mean to pay somebody for this project. I have a simple model that I want to display by creation date in django admin class Project(models.Model): date = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.DO_NOTHING) class Meta: ordering = ['-date'] # def get_identification_day(self): dt=self.date y=(dt.strftime("%b, %d, %Y")) z=y[0:5].replace(",",".")+y[5:] if z[5]=='0': z=z[0:5]+z[6:] return z I have a change-list template declared in admin.py, working fine to do graphs by user.username It can do a graph by date also but monday 11 january 2021 follows friday 8 2021 on the graph. How is it possible to insert saturday and sunday (no Project with the dates) with zero values? I have created a list of all the dates since 1/1/2020 in js and a list "predata1" of same length filled by "1" This can be seen on the graph So I prepared a list "predata0" filled by zeros I wanted to replace the "0" with the total of projects when they exist in my model. And there I am stuck. My function is not good. On console this work fine so I guess I couldn't figure out how to rewrite it … -
Django Admin form Taggit Library through model
I am using Taggit library. I need to use some additional fields like featured_tag and hence I created a through model. Now, I need to modify Django Admin for the same. So, on front end, I have used VueJs to create assign which tag is featured, but, how we would handle in BackEnd form while saving. As I understand, we need to call save_m2m() function, but how we will pass these addtional attributes. Any thoughts ? -
Filter itens without direct relation in Django Rest Framework API
I'm trying to implement some filters in my API endpoint for a property management company. I want to filter reservations in a range of check-in dates and properties. I have three models called Reservation, Listing and Property. The reservation has a Foreign Key to Listing, which has a Foreign Key to Property. I want to filter a reservation with a specific Property, but they don't have a direct relation, the Listing is in the middle. models.py from django.db import models from .helpers import support_models class Reservation(models.Model): code = models.CharField(max_length=50) listing = models.ForeignKey(Listing, on_delete=models.CASCADE) check_in_date = models.DateField(blank=True, null=True) check_out_date = models.DateField(blank=True, null=True) def __str__(self): return self.code class Listing(models.Model): code = models.CharField(max_length=50) property = models.ForeignKey(Property, on_delete=models.CASCADE) def __str__(self): return self.code class Property(support_models.Address): code = models.CharField(max_length=50) location = models.ForeignKey(Location, on_delete=models.CASCADE) def __str__(self): return self.code I have many more itens in the models, but I'm showing you only what I need. My views are looking like this at the moment: views.py from rest_framework import viewsets, permissions, filters from sapron import models, serializers class ReservationViewSet(viewsets.ModelViewSet): queryset = models.Reservation.objects.all() serializer_class = serializers.ReservationSerializer filterset_fields = { 'check_in_date': ['gte', 'lte'], 'listing': ['exact'], } The date range filter is working fine, but I want 'property' instead of 'listing' in … -
Django + sorl_thumbnail no thumbnails shown
i wanna use sorl_thumbnail to show thumbnails from my images uploaded by users. My key-value database is Redis. I've set things up but no images are shown, onlu broken links. Apparantly the path to the thumbnails is not correct?! Here is my setup: First i have installed Redis and pillow. After that i made following changes to the django settings.py file: #INSTALLED_APPS = [ ................. 'sorl.thumbnail', ] #sorl_thumbnail setup with a redis local key-value server THUMBNAIL_DEBUG = True THUMBNAIL_BACKEND = 'sorl.thumbnail.base.ThumbnailBackend' THUMBNAIL_KVSTORE = 'sorl.thumbnail.kvstores.redis_kvstore.KVStore' THUMBNAIL_REDIS_DB = 0 THUMBNAIL_REDIS_PASSWORD = '' THUMBNAIL_REDIS_HOST = 'localhost' THUMBNAIL_REDIS_PORT = 6379 THUMBNAIL_ENGINE = 'sorl.thumbnail.engines.pil_engine.Engine' # Setting up cache for sorl_thumbnail package. CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1/6379/1', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient' }, 'KEY_PREFIX': 'intra_' } } In my HTML-template i have the following for showing the thumbnails: {% load thumbnail %} <td> {% thumbnail stripboek.kaft.url "100x100" crop="center" as im %} <img src="{{ im.url }}"/> <!-- <img src="{{stripboek.kaft.url }}" width="100px" /> --> {% endthumbnail %} </td> When i inspect the thumbnail element on my website i see the following: http://192.168.178.24/media/cache/40/2a/402af0436a0c51c70391884f705938b1.jpg /media/ is the path from my MEDIA_URL in Django. I think the problem is that with the installation of Redis no Django Database/Model … -
Multiple filter parameters in the foreign key relation with reduce function
I have a model ToBePosted that has a foreign key to Campaign and Size. class Campaign(models.Model): name = models.CharField(max_length=100) class Size(models.Model): name = models.CharField(max_length=5) class ToBePosted(models.Model): campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, related_name='to_be_posted_posters') size = models.ForeignKey(Size, on_delete=models.CASCADE, related_name='to_be_posted_posters') My queryset in views.py: def get_to_be_posted_queryset_with_filter(self, request): filter_params = ToBePostedParameterConverter(request.GET) queryset = ToBePosted.objects.all() return queryset.filter(filter_params.get_filter()) And helpers.py where ToBePostedParameterConverter is located class ParameterConverter: # Convert url query params to queryset filter params query_patterns = { "campaign": 'to_be_posted__campaign__name', "size": 'reference__size__name', } def __init__(self, query_dict): self._query_dict = query_dict self._filter_params = [] self._convert() def _convert(self): for key in self._query_dict: for search_key in self._query_dict.getlist(key): if query_param := self.query_patterns.get(key): self._filter_params.append(Q(**{query_param: search_key})) def get_filter(self): if self._filter_params: return reduce(operator.or_, self._filter_params) return Q() class ToBePostedParameterConverter(ParameterConverter): query_patterns = { "campaign": 'campaign__name', "size": 'size__name', } def get_filter(self): if self._filter_params: return reduce(operator.or_, self._filter_params) return Q() The question is: when I try to get an object Tobeposted with a size of 666 but only associated with campaigns Acamp and Bcamp I get all objects that have a size of 666 regardless of the specified campaigns in the url EXAMPLE OF REQUEST URL WITH PARAMETERS: http://localhost:8000/api/v2/posters/get_lookups/?campaign=Acamp&campaign=Bcamp&size=666 How I can change the code to get only posters that are related to specified campaigns in the url paramters? I … -
Sort added elements inside Django autocomplete_fields
I have Django application and admin page. Inside admin page, I have one model that has autocomplete_fields. I can sort results but, I can't sort the results. It always sort by pk and not by value that I set. @admin.register(Assortment) class AssortmentAdmin(ImportExportActionModelAdmin): list_display = ['name'] exclude = ['customers'] # inlines = [ProductAssortmentInLine] autocomplete_fields = ['products'] @admin.register(Product) class ProductAdmin(ImportExportActionModelAdmin): exclude = ['associated_products', 'subsidiary_excluded', 'customers'] list_display = ['product_ref', 'name', 'price', 'group', 'retail_unit', 'active'] list_editable = ['price', 'retail_unit', 'active'] list_filter = ['group'] search_fields = ['product_ref', 'name', 'group'] resource_class = ProductResource # inlines = [CustomerInLine] def get_queryset(self, request): qs = super(ProductAdmin, self).get_queryset(request) qs = qs.order_by(Cast(F('product_ref'), IntegerField())) return qs How to solve this? -
Heroku-deployed Django application does not appear in mobile browser
Situation: I've bought a specific domain, let's say 'example.ch' for my Django application which is deployed in Heroku. I also created an automated SSL certificate on Heroku (ACM). This certificate is valid for the WWW-subdomain, i.e. ACM Status says 'OK'. It fails for the non-WWW root domain, so I deleted the root domain entry on Heroku. I use 'swizzonic.ch' as webhostserver. Question: The redirection from 'example.ch' to 'https://www.example.ch' does not work on my mobile device, while everything is fine when I use my Mac and all common browsers. I found an older (unanswered) similar post to this topic (Django app on heroku: content wont appear in mobile browser). I don't know where to start, since seemingly nobody else faces this issue... Many thanks for your help. -
custom view component into based view
how to make a custom component (for example a form) that can then be called from other views? for example class BaseFormView (FormView): template_name = 'pit / contact.html' form_class = ContactForm success_url = '/' def form_valid (self, form): return super (). form_valid (form) class TestView (View): template_name = loader.get_template ('pit / pit.html') title = "test" def get (self, request, * args, ** kwargs): view = BaseFormView () context = {"title": self.title, "view": view} return HttpResponse (self.template_name.render (context, request)) -
Include javascript files in a javascript file in a Django project
I'm using the chart library apexcharts and defined a javascript function for a chart that I'm using multiple times on different parts of the website. The function needs some other scripts to work. So at the moment, everytime I want to use that function (located in util.js), I have to import the scripts like this in my html template: <script type="application/javascript" src="{% static 'shared/js/apexcharts/apexcharts.min.js' %}"></script> <script type="application/javascript" src="{% static "shared/js/apexcharts/dependency2.js" %}"></script> <script type="application/javascript" src="{% static "shared/js/apexcharts/dependency1.js" %}"></script> <script type="application/javascript" src="{% static "shared/js/apexcharts/util.js" %}"></script> How can I include the first 3 in my util.js, so that I just have to import util.js? -
Django ValueError The view HomeFeed.views.AddCommentView didn't return an HttpResponse object. It returned None instead
I received this error from the code: ValueError at /HomeFeed/comments/testuser1-2 The view HomeFeed.views.AddCommentView didn't return an HttpResponse object. It returned None instead. Any idea why this is happening? Like which part is causing this problem too, is it the function or my reverse lazy line? models.py class Comment(models.Model): post = models.ForeignKey(BlogPost, related_name='comments', on_delete=models.CASCADE) name = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='name', on_delete=models.CASCADE) body = models.TextField() date_added = models.DateField(auto_now_add=True) class BlogPost(models.Model): chief_title = models.CharField(max_length=50, null=False, blank=False, unique=True) body = models.TextField(max_length=5000, null=False, blank=False) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['body'] widgets = { 'body' : forms.Textarea(attrs={'class': 'form-control'}), } views.py class AddCommentView(DetailView, FormView): model = BlogPost # change model to post because your are commenting on POSTS not COMMENTS form_class = CommentForm template_name = 'HomeFeed/add_comment.html' success_url =reverse_lazy('HomeFeed:main') def form_valid(self, form): comment = form.save(commit=False) #comment.user = self.request.user comment.name = self.request.user comment.post = self.get_object() comment.save() -
How to create a template in django that can be use any other page and that rander same / editable if needed
i created a base template home.html, there is footer and i pass categories on footer and it work fine in home.html but there is extended pages view.html when i go to this page the footer categories is not showing likewise footer is not showing in other pages how can i solve this problems . to incluse view.html in home.html home.html {% block body %} {%endblock%} <--footer--> <div class="col-xs-6 col-md-3"> <h6>Categories</h6> <ul class="footer-links"> {% for category in procategory %} <li><a href="foodgrains?category={{category.id}}">{{category.name}}</a></li> {% endfor %} </ul> </div> view.html {% extends 'home.html' %} {% load static %} {% block body %} <--my code --> {% endblock body %} problems is when i go to view,html the footer categories value is not showing can any one have any suggestion to solve ,how the footer categories show in different page i sloe use {% include 'footer.html' %} it also doesn't work -
Why are the contents of my static css and js files being replaced by html code?
I have a pure js application from which I have generated the build files using yarn build I have the following files I now need to serve these files using Django. Here is what I have tried I have added a frontend folder in the Django app as follows I have also added the following URL re_path("wazimap/", TemplateView.as_view(template_name="index1.html")) and updated the settings file with the following TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": ["frontend/build/dist"], ....More code STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), os.path.join(BASE_DIR, "frontend/build/dist"), ] now when I access the /wazimap/ URL, the HTML is served but the css/js that is being loaded contains the wrong code. I can see from the console that the files are being requested but index1.html is what is being placed inside all the css/js files i.e The contents of the css/js files are the content of the index1.html file. So a js file has something like <!DOCTYPE HTML>... which isn't a valid js thus causing errors. Any ideas why this is happening?