Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to register route with query parameters?
Im very new to Django, struggling to find the answer Im looking for. Please bear with me. In my app/urls.py file I have router = routers.DefaultRouter() router.register(r'drugs', views.DrugViewSet) In my views.py file I have class DrugViewSet(viewsets.ModelViewSet): queryset = Drug.objects.all().order_by('name') serializer_class = DrugSerializer And my DrugSerializer class looks like class DrugSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Drug fields = ('id', 'name', 'description', 'recommended_dose_mg', 'count', 'create_date', 'update_date') So when I do a GET on /drugs, I correctly get the list of drugs. And when I take a UUID (primary key) on a specific drug and do a GET on /drugs/<primary_key>, it correctly pulls the specific drug. However, I want the GET on /drugs/<primary_key> to display different data. I want to join it with another model that I have and return a new json response. How exactly would I do this? -
my chat app doesn't work after deployement - heroku django
I did a chatting part in my web app with django it works perfectly in local but after I deployed it to heroku , it doesn't work: this is my consumers.py class: from channels.generic.websocket import AsyncWebsocketConsumer from django.contrib.auth.models import User from django.db.models import Q from asgiref.sync import sync_to_async import json from chat.models import Thread, Message from users.serializers import UserSerializer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): friend = None me = self.scope['user'] # logged in user friend_name = self.scope['url_route']['kwargs']['friend'] # get the username of that user, whoom you want to chat friend_instance = await sync_to_async(User.objects.get, thread_sensitive=True)(username=friend_name) # get user object of friend # create a new Thread object if thread of specific chat does not exists, otherwise return the thread thread = None try: thread = await sync_to_async(Thread.objects.get, thread_sensitive=True)((Q(user1=me) & Q(user2=friend_instance)) | (Q(user1=friend_instance) & Q(user2=me))) except: thread = await sync_to_async(Thread.objects.create, thread_sensitive=True)(user1=me, user2=friend_instance) self.room_name = thread.room_name # room name await self.channel_layer.group_add( self.room_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): ''' disconnect the websocket connection. ''' await self.channel_layer.group_discard ( self.room_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] from_user = text_data_json['user'] to_user = text_data_json['friend'] from_user_instanse = await sync_to_async(User.objects.get, thread_sensitive=True)(username=from_user['username']) # get user object of friend to_user_instanse = await sync_to_async(User.objects.get, … -
How to actually prove that the user consented to data processing while he submitted the form?
A user submits a form and opts in to receive a newsletter. What do I need to do to prove later that he actually did opt in? If I store submitted form data in a db table then I am able to manually create and modify entries, so I could just change his False to True and therefore db entries don't prove anything. I have a django website if it makes any difference. -
Django render_to_string Returns NoneType Error
Using Django Pagination I'm trying to do endless pagination using AJAX. I followed the example here: https://www.progerhub.com/tutorial/adding-pagination-with-infinite-scroll-in-django/ My view returns the first page of results just fine, but when I attempt to build the content for the additional pages and return it as JSON using render_to_string I get an error while appending data onto my content variable. error message web_1 | Traceback (most recent call last): ... web_1 | File "/usr/src/django/media/views.py", line 74, in get web_1 | content += render_to_string('media_item.html', {'media': media, }, request=request) ... web_1 | new_obj = func(obj, *arg_vals) web_1 | File "/usr/local/lib/python3.8/site-packages/django/template/defaultfilters.py", line 784, in divisibleby web_1 | return int(value) % int(arg) == 0 web_1 | TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' models.py class Media(Audit): title = models.CharField( max_length=255) description = models.CharField( max_length=500, blank=True, null=True) poster = ProcessedImageField( blank=True, null=True, format='JPEG', options={'quality': 100}, processors=[ResizeToFill(1000, 1500)], upload_to=get_poster_path) class Meta: ordering = ( 'title', 'year') def __str__(self): return self.title views.py class MediaView(LoginRequiredMixin, JsonMixin, View): def get(self, request, *args, **kwargs): context = self.get_context_data() media = models.Media.objects.filter() page = int(request.GET.get('page', 1)) p = paginator.Paginator(media, 24) # number of media per page # try to get media for the given page try: media_page … -
Docker with venv or without?
I am new in Docker and learning it, and my question is that do I have to use venv in Docker or isn't it important? Because I couldn't configure venv in docker, it gives me an error like cannot import Django activate venv..., I read some answers but couldn't get answer, some people say need to use venv others not important. My DOckerfile FROM python:3.8 #set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN python3 -m venv venv #Set work directory WORKDIR /code/ #Install dependencies COPY requirements.txt . RUN . /venv/bin/activate && pip install -r requirements.txt COPY . /code/ If I don't use venv Docker runs fine, but when it comes to install package it gives me warning like WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead:... Can someone explain clearly it? Thanks in advance -
django AttributeError when saving data with DRF
I have a problem when I make a POST. the entry is created (I can see it in django Admin panel) but DRF is throwing me an error AttributeError at /api/v1/reviews/ 'Review' object has no attribute 'review_score' review_score beeing a SerializerMethodField in serializer.py needed for the frontend (GET is working perfectly) model.py class Review(models.Model): company = models.ForeignKey(Company, related_name='company_review', on_delete=models.CASCADE) title = models.CharField(max_length=255) comments = models.TextField() validated = models.BooleanField(default=False) note_quality = models.DecimalField(max_digits=5, decimal_places=2) note_timing = models.DecimalField(max_digits=5, decimal_places=2) note_qualprix = models.DecimalField(max_digits=5, decimal_places=2) note_react = models.DecimalField(max_digits=5, decimal_places=2) note_followup = models.DecimalField(max_digits=5, decimal_places=2) note_clean = models.DecimalField(max_digits=5, decimal_places=2) created_at = models.DateField(auto_now_add=True) created_by = models.ForeignKey(User, related_name='created_review', on_delete=models.CASCADE) def __str__(self): return self.title views.py class ReviewViewSet(viewsets.ModelViewSet): serializer_class = ReviewSerializer queryset = Review.objects.all() def get_queryset(self): company_id = self.request.query_params.get('company_id', None) return self.queryset.filter(company_id=company_id, validated=True).annotate( review_score = Sum(F('note_quality')+F('note_timing')+F('note_qualprix')+F('note_react')+F('note_followup')+F('note_clean'))/6, ) def perform_create(self, serializer): obj = serializer.save(created_by=self.request.user) obj.save() serializer.py class ReviewSerializer(serializers.ModelSerializer): created_by = UserCreateSerializer(read_only=True) review_score = serializers.SerializerMethodField() def get_review_score(self, obj): rounded = round_up(obj.review_score, 0.5) return rounded class Meta: model = Review read_only_fields = ('created_at'), fields = ('id','company','title','comments','validated','note_quality','note_timing','note_qualprix','note_react','note_followup','note_clean','created_at', 'created_by', 'review_score') -
Django: How to add html tag from string to the html template
Details: Client framwork: Django Web server: Python + Flask I have an HTML page which rendered with a data array. Each item in the array contains some fields. And one of the fields is a json object. In order to improve the visibility of the json i've converted the json obj to html table. Currently it's does't work. The results (on the browser) looks like that: PasswordPolicy <table border="1"><tr><th>MinimumPasswordLength</th><td>16</td></tr><tr><th>RequireSymbols</th><td>True</td></tr><tr><th>Re Flask code: @app.route("/PasswordPolicy", methods=["GET"]) @login_required def get_password_policy(): get_table_content = list(db_object.get_password_policy()) search_event = request.args.get('searchquery') at_type = request.args.get('audittype') print("**************") for e in get_table_content: print("Before:") print(e['PasswordPolicy']) e['PasswordPolicy'] = json2html.convert(json = e['PasswordPolicy']) print("After:") print(e['PasswordPolicy']) print("get_table_content:") print(get_table_content[0]) print("**************") return render_template( 'soc2/password_policy.html', get_list=get_table_content ) Html content: <table id="datatable-buttons" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%"> <thead> <tr class="headings"> <th class="column-title">BusinessUnit </th> <th class="column-title">ControllerNumber </th> <th class="column-title">PasswordPolicy </th> </tr> </thead> <tbody> {% for elements in get_list %} <tr class="even pointer"> <td> {{ elements["BusinessUnit"] }} </td> <td> {{ elements["ControllerNumber"] }} </td> <td> {{ elements["PasswordPolicy"] }} </td> </tr> {% endfor %} </tbody> </table> The question is how to tell to the browser to parse the table as html instead of simple string -
Is it safe to delete a Django QuerySet that may be empty?
Is it safe to attempt to delete a QuerySet that might be empty? In other words, if I am not sure if the name "MJ" exists, is there any functional difference between these 2 approaches? Is either preferred? 1) query = m.objects.filter(name="MJ") if query.exists(): query.get().delete() m.objects.filter(name="MJ").delete() -
Django model, ImportError attempted relative import with no known parent package
I'm making a small Django app, and i just want to make some tests over the QuerySet of my model. However, when running code outside the manage.py runserver environment, i get this error : from .models import Article Error: ImportError: attempted relative import with no known parent package As already said, this works perfectly when making views, i can import my Article model and create Articles from the admin dashboard. My app structure looks like this: app/ admin.py apps.py models.py (this contains my Article model) views.py file_where_ihave_my_error.py -
Django NEWBIE - TemplateDoesNotExist
(My project directory is called test and the app in question is called posts) Django tried loading these templates, in this order: Using engine django: django.template.loaders.app_directories.Loader: /path-to-app-dir/virtual/test/posts/templates/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /path-to-app-dir/virtual/platform/lib/python3.10/site-packages/django/contrib/admin/templates/index.html (Source does not exist) django.template.loaders.app_directories.Loader: /path-to-app-dir/virtual/platform/lib/python3.10/site-packages/django/contrib/auth/templates/index.html (Source does not exist) Views.py from django.shortcuts import render from django.http import HttpResponse def index(request): return render(request,'templates/index.html') Urls.py from django.urls import path from . import views urlpatterns=[ path('', views.index) ] I have mentioned the app in Settings.py so that probably shouldn't be an issue. What am I doing wrong ? -
Интеграция данных парсера с Django [closed]
Я хочу сделать сайт, на котором можно будет посмотреть информацию о разных вузах. У меня готовы парсеры, но я не понимаю, как можно правильно интегрировать парсеры в Django приложение... Когда я искал информацию по этому поводу, одним рекомендовали использовать django-admin команды, другим использовать парсеры. Я не понимаю, что использовать лучше, у чего какие плюсы и что стоит в итоге выбрать? На данный момент у меня парсеры заливают информацию в стороннюю бд и через класс вытягивается в html форму. Не думаю, что это правильное решение... -
Why am I getting a 404 Error when I've clearly defined my urlpatterns?
My project is storefront and when I run the server I get the error message "Page not found". I have my urls.py file in the storefront folder for you to look at. I've looked around on the internet and have had no luck yet. urlpatterns = [ path('admin/', admin.site.urls), path('playground/', include('playground.urls')) ] I thik the problem is in my urls.py specifically with "include" but not sure. -
Django Haystack select which fields to search
Suppose I have a Person model looking like this: class Person(models.Model): title = models.CharField(max_length=300, blank=True, null=True) first_name = models.CharField(max_length=300, blank=True, null=True) last_name = models.CharField(max_length=300, blank=False, null=False) And a Haystack search index like this: class NoteIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) title = indexes.CharField(model_attr='title') first_name = indexes.CharField(model_attr='first_name') last_name = indexes.CharField(model_attr='last_name') Say the template includes all three fields(firstname, lastname and title). If users should be able to choose in which fields to search for, do I need to build seperate indices for all possible permutations? Or can I narrow down the search to one or two of the three fields? If so how? I know that I am able to filter SearchQuerySets using .filter(). SearchQuerySet().filter(first_name='foo') But this filters the set for exact values. Even __icontains is limited to one field filtering. -
How to make django not render html?
I have model: class NewsItem(models.Model): meta_title = models.CharField(_('Meta title'), max_length=255, blank=True, null=True, help_text=mark_safe('Tag <title>')) But on the page I have: <div class="form-row field-meta_title"> <div> <label for="id_meta_title">Meta title:</label> <input type="text" name="meta_title" class="vTextField" maxlength="255" id="id_meta_title"> <div class="help">Tag <title></div> </div> </div> How to tell django not render html? -
Python Flask - Errors after creating a new project
After creating a new project and trying to run it, I get something like this: * Environment: development * Debug mode: off Traceback (most recent call last): File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 192, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\flask\__main__.py", line 3, in <module> main() File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\flask\cli.py", line 994, in main cli.main(args=sys.argv[1:]) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\flask\cli.py", line 600, in main return super().main(*args, **kwargs) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\click\core.py", line 1053, in main rv = self.invoke(ctx) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\click\core.py", line 1659, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\click\core.py", line 1395, in invoke return ctx.invoke(self.callback, **ctx.params) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\click\core.py", line 754, in invoke return __callback(*args, **kwargs) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\click\decorators.py", line 84, in new_func return ctx.invoke(f, obj, *args, **kwargs) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\click\core.py", line 754, in invoke return __callback(*args, **kwargs) File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\flask\cli.py", line 853, in run_command run_simple( File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\werkzeug\serving.py", line 1010, in run_simple inner() File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\werkzeug\serving.py", line 950, in inner srv = make_server( File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\werkzeug\serving.py", line 782, in make_server return ThreadedWSGIServer( File "C:\Users\Sebastian\PycharmProjects\informatyka\venv\lib\site-packages\werkzeug\serving.py", line 688, in __init__ super().__init__(server_address, handler) # type: ignore File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python38-32\lib\socketserver.py", line 452, in __init__ self.server_bind() File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python38-32\lib\http\server.py", line 139, in server_bind self.server_name = socket.getfqdn(host) File "C:\Users\Sebastian\AppData\Local\Programs\Python\Python38-32\lib\socket.py", line 756, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe6 in … -
Getting error while using migrate after inspectdb using sqlite
I need to make an API from an existing sqlite db. I used inspectdb for creating models from the database. Do I need to manually add the primary keys(id) for all tables after inspect in my models.py? After that what should I do, migrate? Makemigrations? I am getting error related to one of the tables in the databases after doing migrate,(issue with one table referencing other). Is there an issue with the db? Here is my settings.py """ Django settings for IMS project. Generated by 'django-admin startproject' using Django 4.0. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-u@yr4&95+m=v*6o53in2*82xn@292n(6-#ixj38-^8l8e3(4$h' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "Api.apps.ApiConfig", "rest_framework", ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'IMS.urls' TEMPLATES … -
Truncated or oversized response headers received from daemon process error with PiCamera library
I am hosting a simple Django website using Apache2 and WSGI. The website works fine but when I attempt to instantiate a PiCamera() object I get this error. All I am trying to do is initiate a photo capture and update the image on the website every time the website is refreshed. I feel like it should not be this difficult. I have searched all over and cannot find a solution. I have attempted to add WSGIApplicationGroup %{GLOBAL} to my sites-available/000-default.conf as well as my apache2.conf. I have also attempted to increase the head buffer size and neither solution work. Any help would be appreciated. Views.py from django.shortcuts import render from django.http import HttpResponse from .models import RelayList from .forms import RelayControl from .gpio import Update_Relays from django.contrib.auth.decorators import login_required from picamera import PiCamera from time import sleep def Snapshot(): camera = PiCamera() #<---THIS IS WHAT CAUSES THE TRUNCATED ERROR # camera.start_preview() # sleep(5) # camera.capture('/home/calabi/relay_site/power_relay/media/snapshot.jpg') # camera.stop_preview() # Create your views here. @login_required def index(response): curList = RelayList.objects.get(id=1) #retrieves the database object and places it into a variable Snapshot() #takes a photo and saves it to images directory # camera = PiCamera() # camera.start_preview() # sleep(5) # camera.capture('/home/calabi/relay_site/power_relay/media/snapshot.jpg') # … -
AttributeError: module 'PrivateSchools.views' has no attribute 'HomePage'
Am getting the above error when try to run the server. Below is the full error. AttributeError: module 'PrivateSchools.views' has no attribute 'HomePage' File"C:\Users\admin\Desktop\InstitutionFinderWebsite\ InstitutionFin derWebsite\urls.py", line 26, in <module>path('HomePage/', views.HomePage), AttributeError: module 'PrivateSchools.views' has no attribute 'HomePage' I had imported all the views from the three apps as below from django.conf.urls import include from django.contrib import admin from django.urls.conf import path from HomePage import views from PublicSchools import views from PrivateSchools import views On the urls.py have tried the 2 methods below but the are not all working. Method one here i used views. to map the urls. urlpatterns = [ path('admin/', admin.site.urls), path('HomePage/', views.HomePage), path('PublicSchools/', views.PublicSchools), path('PrivateSchools/', views.PrivateSchools), ] This is Method two in trying to solve it by trying to give the names. urlpatterns = [ path('admin/', admin.site.urls), path('HomePage/', views.HomePage, name='PrivateSchools'), path('PublicSchools/', views.PublicSchools, name='PublicSchools'), path('PrivateSchools/', views.PrivateSchools, name='PrivateSchools'), ] Kindly help out. Am stuck. -
AttributeError: 'Post' object has no attribute 'post_image'
I am using DRF and Django(4.0) to make posts in a Instagram Clone. The models of the following are available below. I have successfully implemented post request, but am having problems implementing get request. I have tried to nest two serializer inside the PostViewSerializer to serialize the data. However I am getting the following error when I do a get request. Got AttributeError when attempting to get a value for field 'post_image' on serializer 'PostViewSerializer'. The serializer field might be named incorrectly and not match any attribute or key on the `Post` instance. Original exception text was: 'Post' object has no attribute 'post_image'. Now, I should tell you that there is not requirement that the post should contain atleast one image or video it could contain entirely either videos or posts. So, could that be the cause of the above error. If so, how can I solve it? #models.py class Post(Authorable, Model): created_at = models.DateTimeField(default=timezone.now) caption = TextField(max_length=350) class Images(Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) images = models.FileField(upload_to="images/") class Videos(Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) videos = models.FileField(upload_to="videos/") #behaviours.py class Authorable(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: abstract = True def get_user(self): return self.user.id #serializers.py class ImageViewSerializer(serializers.ModelSerializer): class Meta: model = Images … -
Understanding Model.from_db() in Django
I was reading Django Official Doc for Model, it reads: classmethod Model.from_db(db, field_names, values)¶ The from_db() method can be used to customize model instance creation when loading from the database. The db argument contains the database alias for the database the model is loaded from, field_names contains the names of all loaded fields, and values contains the loaded values for each field in field_names. The field_names are in the same order as the values. If all of the model’s fields are present, then values are guaranteed to be in the order __init__() expects them. That is, the instance can be created by cls(*values). If any fields are deferred, they won’t appear in field_names. In that case, assign a value of django.db.models.DEFERRED to each of the missing fields. I am completely lost when reading above. 1st perception: "when loading from the database": for me, loading means reading / retrieving data from database, which means the model instance already exists or is created and stored in DB. 2nd perception: "be used to customize model instance creation", as well as the 2nd paragraph all makes me feel that this from_db() is for model instance creation, which conflicts with my 1st perception. Q: Can … -
How can I return the refresh token using python-social-auth and django-graphql-auth?
How can I return the refresh token when using social auth? I tried this solution here I don't know how to make this compatible with graphql. Here is my attempt: import graphql_social_auth from graphql_jwt.shortcuts import get_token class SocialAuth(graphql_social_auth.SocialAuthJWT): refresh_token = graphene.String() token = graphene.String() @classmethod def resolve(cls, root, info, social, **kwargs): return cls( user=social.user, token=get_token(social.user), refresh_token=social.extra_data['refresh_token'] ) The user and token fields are alright when I comment out the refresh token. I just don't know where to get the refresh token, it seems to be not in the extra_data. I am already dealing with this problem for hours and all the search results are no help. Please, any guidance is really appreciated. -
How to Add a comment section in Django using model form
I m New in Django I started a project of blog I wanted to add A comment section feature in my Project I Am Having a error Mode form is not defined in class view.py from Blog.models import Comment from Blog.forms import CommentForm def post_detail_view(request,year,month,day,post): post=get_object_or_404(Post,slug=post, status='published', publish__year=year, publish__month=month, publish__day=day) comments=Comment.objects.filter(active=True) csubmit=False if request.method=='POST': form=CommentForm(data=request.POST) if form.is_valid(): new_comment=form.save(commit=False) new_comment.post=post new_comment.save() csubmit=True else: form=CommentForm() return render(request,'blog/detail.html',{'post':post,'comments':comments,'csubmit':csubmit,'form':form}) if I tried to run this function I want to display a form in detail page and if end user submit the form then display same page detail.html <!doctype html> {% extends "blog/base.html" %} {% block title_block %} detail Page {% endblock%} {% block body_block %} <h1>This Is Your Content</h1> <div> <h2>{{post.title|title}}</h2> </div> <div> {{post.body|title|linebreaks}} <p>Publised of {{post.publish|title}} Published By {{post.author|title}}</p> <div> {% with comments.count as comments_count %} <h2>{{comments_count}} Comment{{comments_count|pluralize}}</h2> {% endwith%} <div> {%if comments %} {%for comment in comments %} <p> comment {{forloop.counter}} by {{comment.name}} on {{comment.created}} </p> <div class="cb">{{comment.body|linebreaks}}</div> <hr> {%endfor%} {%else%} <p>There are NO Comments Yet !!!</p> {%endif%} {%if csubmit %} <h2>Your Comment Added Succefully</h2> {%else%} <form method="post"> {{form.as_p}} {%csrf_token%} <input type="submit" name="" value="Submit Comment"> </form> {%endif%} </div> {%endblock%} here I defined my form forms.py from Blog.models import Comment class CommentForm(ModelForm): class … -
How to add a new obj from html in django
So im trying to make this page where i add new category which only has name. But when i try it, i just get a "non-string type" as the name. So it works i guess just doesn't take whatever i give it in my input in html. HTML: <input type="text" class="form-control" placeholder="Name" id = "category-create-name" name= "category_name"> <input type="submit" class="login-button" value="Post"> Model: class Category(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Form: class CategoryCreateForm(forms.ModelForm): class Meta: model = Category fields = ('name',) widgets = { 'category_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Name', 'id':'category-create-name'}), } View: class CategoryCreateView(CreateView): form_class = CategoryCreateForm template_name = 'product/new_category.html' success_url = '/dashboard/' -
Django Rest Framework trying to get similar products with serializer reversed
i`m new to DRF and im trying to serialize similar product on product. heres my code models.py class Product(models.Model): headline = models.CharField(max_length=150) category = models.ManyToManyField(Category, related_name="products") tag = models.TextField(null=True, blank=True) sku = models.CharField(max_length=50, unique=True) sell_limit = models.IntegerField(default=10) price = models.FloatField(default=0) class SimilarProduct(models.Model): on_product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True, related_name="on_products") product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True, related_name="products") serializers.py class ProductDetailSerializer(serializers.ModelSerializer): category = serializers.SerializerMethodField() similar = serializers.SerializerMethodField() in serializers i have written this type of code which dont works. #CODE : def get_similar(self, obj): product_query = Product.objects.filter(pk__in=obj.on_products.values_list("id")) return ProductListSerializer(product_query, many=True).data and heres my ProductListSerializer class ProductListSerializer(serializers.ModelSerializer): category = serializers.SerializerMethodField() price = serializers.SerializerMethodField() i want to get similar products of product but it dont works. any ideas how to solve? -
Vue.js and Django multiple image rendering
I am having some major issues trying to render multiple images to my Vue.js frontend from a static folder in my Django project. I can get one image showing without issues but it does not seem to work for multiple images. My images are uploaded via the admin section of the app. Any help would be really appreciated I have spent days on this!!!!! Here is my models.py: class Lesson(models.Model): DRAFT = 'draft' PUBLISHED = 'published' CHOICES_STATUS = ( (DRAFT, 'Draft'), (PUBLISHED, 'Published') ) ARTICLE = 'article' QUIZ = 'quiz' CHOICES_LESSON_TYPE = ( (ARTICLE, 'Article'), (QUIZ, 'Quiz') ) course = models.ForeignKey(Course, related_name='lessons', on_delete=models.CASCADE) title = models.CharField(max_length=255) slug = models.SlugField() short_description = models.TextField(blank=True, null=True) long_description = models.TextField(blank=True, null=True) status = models.CharField(max_length=20, choices=CHOICES_STATUS, default=PUBLISHED) lesson_type = models.CharField(max_length=20, choices=CHOICES_LESSON_TYPE, default=ARTICLE) image = models.ImageField(upload_to='uploads/', blank=True, null=True) def __str__(self): return self.title class LessonImage(models.Model): lesson_image = models.ForeignKey(Lesson, related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to ='uploads/') def save(self, *args, **kwargs): super(LessonImage, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 1125 or img.width > 1125: img.thumbnail((1125,1125)) img.save(self.image.path,quality=70,optimize=True) def get_images(self): if self.lesson_image: return settings.WEBSITE_URL + self.lesson_image.url And my serializers.py. * Im not sure I needed to implement the image models in the serializers but I have tried this to test: class …