Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to render HTML template based on tuple choice
I have created a model, views and templates like so: MODEL project_choices = ( ('Speaker', ( ('help', 'Freedom'), )), ('Money', ( ('invest', 'Investment'), ) ), ( 'Children', ( ('mc', 'Mother & Child'), ) ), ) class Blog(models.Model): title = models.CharField(max_length=250) description = CKEditor5Field('Text', null=True) limitation = models.BooleanField( null=True, max_length=50, choices=project_choices) def __str__(self): return self.title Now the VIEW def view_portfolio(request): blog= Blog.objects.all() template = 'blog/blog.html' context = {'blog': blog} return render(request, template, context) then the hmtl template {% for blog in blog%} {% if blog.limitation['**help**'] %}**//I have also tried {% if portfolio.limitation == project_choices['AI']%}** <div class="col-lg-4 col-md-6"> <div class="portfolio-wrap"> <img src="{{blog.featured}}" class="img-fluid" alt=""> <div class="blog-info"> <h4>{{blog.title}}</h4> <p></p> <div class="portfolio-links"> <a href="{{blog.featured}}" data-gall="blogGallery" class="venobox" title="{{blog.title}}"><i class="bx bx-plus"></i></a> <a href="blog-details.html" title="More Details"><i class="bx bx-link"></i></a> </div> </div> </div> </div> {% endif %} {%endfor%} My goal is to show blogs based on ONLY help as the chosen choice please how can I achieve this? I am using django3 -
TodayArchiveview is not detected in urls.py(Django)
I created several date-based views in Django, and while views for year and month function as expected, the view to display today is not detected. For instance, if I try to get http://127.0.0.1:8000/blog/archive/2021/, or http://127.0.0.1:8000/blog/archive/2021/jan or http://127.0.0.1:8000/blog/archive/2021/jan/07/ the views will be displayed, http://127.0.0.1:8000/blog/archive/today/ will fail. I understand that the problem must be with urls.py configuration, but I just cannot find it in documentation. urls.py from django.urls import path, re_path from blog import views app_name = 'blog' urlpatterns = [ # Example: /blog/ path('', views.PostListView.as_view(), name='index'), # Example: /blog/post/ (same as /blog/) path('post/', views.PostListView.as_view(), name='post_list'), # Example: /blog/post/django-example/ re_path(r'^post/(?P<slug>[-\w]+)/$', views.PostDetailView.as_view(), name='post_detail'), # Example: /blog/archive/ path('archive/', views.PostArchiveView.as_view(), name='post_archive'), # Example: /blog/archive/2019/ path('archive/<int:year>/', views.PostYearArchiveView.as_view(), name='post_year_archive'), # Example: /blog/archive/2019/nov/ path('archive/<int:year>/<str:month>/', views.PostMonthArchiveView.as_view(month_format = '%b'), name='post_month_archive'), # Example: /blog/archive/2019/nov/10/ path('archive/<int:year>/<str:month>/<int:day>/', views.PostDayArchiveView.as_view(), name='post_day_archive'), # Example: /blog/archive/today/ path('archive/today/', views.PostTodayArchiveView.as_view(), name='post_today_archive'), ] views.py from django.shortcuts import render # Create your views here. from django.views.generic import ListView, DetailView, ArchiveIndexView, YearArchiveView, MonthArchiveView, \ DayArchiveView, TodayArchiveView from blog.models import Post class PostListView(ListView): model = Post template_name = 'blog/post_all.html' context_object_name = 'posts' paginate_by = 2 class PostDetailView(DetailView): model = Post class PostArchiveView(ArchiveIndexView): model = Post date_field = 'modify_dt' class PostYearArchiveView(YearArchiveView): model = Post date_field = 'modify_dt' make_object_list = True class PostMonthArchiveView(MonthArchiveView): model = … -
Query set is empty for long search input python django
When i am querying from database its gives queryset empty for long query input in the search eg. if i type "shiv" it gives all matches to this like "shivamshankhdhar" but i type "shivamshankhdhar" its return empy queryset this is my code def account_search_view(request, *args, **kwargs): context = {} if request.method == "GET": search_query = request.GET.get("q") print(f"query for {search_query}") if len(search_query) > 0: print("querying data.....") print(type(search_query)) search_results = Account.objects.filter(email = search_query) # user = request.user print(search_results) accounts = [] # [(account1, True), (account2, False), ...] for account in search_results: accounts.append((account, False)) # you have no friends yet context['accounts'] = accounts return render(request, "accounts/search_result.html", context) -
using django-synchro trying to synchronize two database and getting psycopg2.IntegrityError: duplicate key value violates unique constrain
Following is the exception getting in one database of postgres and sync is happening properly from another side. while testing in local it is working properly but when we imported users from existing database this exception occuring. Following is the exception getting in one database of postgres and sync is happening properly from another side. while testing in local it is working properly but when we imported users from existing database this exception occuring. Following is the exception getting in one database of postgres and sync is happening properly from another side. while testing in local it is working properly but when we imported users from existing database this exception occuring. Finding ref for ct: User, id: 51 found ref Reference object (869) and remote administrator@gmail.com Exception: duplicate key value violates unique constraint "synchro_reference_content_type_id_local_object_id_f2c39050_uniq" DETAIL: Key (content_type_id, local_object_id)=(21, 475) already exists. Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 486, in get_or_create return self.get(**lookup), False File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 399, in get self.model._meta.object_name synchro.models.Reference.DoesNotExist: Reference matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: duplicate key value violates unique constraint "synchro_reference_content_type_id_local_object_id_f2c39050_uniq" … -
ModuleNotFoundError: No module named 'models' in django
https://github.com/prathmachowksey/Attendance-System-Face-Recognition im using this repo and facing this issue can help me -
How do I play only a portion of a video stored on AWS?
I have videos hosted on AWS S3 and ideally I would access them via something like <video muted autoplay loop><source src="https://mybucket.aws.com/videos/test.mp4#t0,15"></source></video>, causing only a certain part of the video to play and have it on loop. The issue is that the bucket is not public and so involves generating a pre-signed URL. I am using Django and boto3 in order to generate the pre-signed URL, but as soon as I attempt to insert #t0,15, it fails (either the # and , will be decoded, the #t0,15 string will be removed or the URL will return access denied, depending on what was attempted). How might I go about this? -
Load external data into an admin model - DJANGO
Is it possible to load external data into a field for filling in? Example: A field with for product names. However we already have the names of the products in another location, we just need to list these products within the field in the default django admin. Using resquets. Thank you very much for your attention. -
django.db.utils.IntegrityError: UNIQUE constraint failed: new__Boutique_boutique.product_id
I had 7 unapplied migrations when I ran manage.py migrate I got a unique constraint error Models.py : from django.db import models import uuid class boutique(models.Model): product_id = models.AutoField desc = models.CharField(max_length=300) pub_date = models.DateTimeField(auto_now_add=True) product_name = models.CharField(max_length=50) category = models.CharField(max_length=50, default="") price = models.IntegerField(default=0) image = models.ImageField(upload_to='index/images', default="") slug = models.SlugField(unique=True, default=uuid.uuid1) def __str__(self): return self.product_name I have added the slug field according to a similar question on stack but that doesn't work. Views.py : ` from django.shortcuts import render from math import ceil from .models import boutique from django.http import HttpResponse def Boutique(request): allProds = [] catprods = boutique.objects.values('category', 'id') cats = {item['category'] for item in catprods} for cat in cats: prod = boutique.objects.filter(category=cat) n = len(prod) nSlides = n // 4 + ceil((n / 4) - (n // 4)) allProds.append([prod, range(1, nSlides), nSlides]) # params = {'no_of_slides':nSlides, 'range': range(1,nSlides),'product': products} # allProds = [[products, range(1, nSlides), nSlides], # [products, range(1, nSlides), nSlides]] params = {'allProds': allProds} return render(request, 'Boutique/Boutique.html', params) def individual(request,product_id): #fetching product using the id all_products = boutique.objects.filter(id = product_id) context = {'all_products' : all_products[0]} return render(request,'Boutique/individual.html' , context ) -
DayArchiveview is not detected in urls.py(Django)
I created several date-based views in Django, and while views for year and month function as expected, the view to display days is not detected. For instance, if I try to get http://127.0.0.1:8000/blog/archive/2021/, or http://127.0.0.1:8000/blog/archive/2021/01 the views will be displayed, http://127.0.0.1:8000/blog/archive/2021/01/07 will fail. I understand that the problem must be with urls.py configuration, but I just cannot find it in documentation. I also tried passing day_format='%d' to as_view method, without any results. urls.py from django.urls import path, re_path from blog import views app_name = 'blog' urlpatterns = [ # Example: /blog/ path('', views.PostListView.as_view(), name='index'), # Example: /blog/post/ (same as /blog/) path('post/', views.PostListView.as_view(), name='post_list'), # Example: /blog/post/django-example/ re_path(r'^post/(?P<slug>[-\w]+)/$', views.PostDetailView.as_view(), name='post_detail'), # Example: /blog/archive/ path('archive/', views.PostArchiveView.as_view(), name='post_archive'), # Example: /blog/archive/2019/ path('archive/<int:year>/', views.PostYearArchiveView.as_view(), name='post_year_archive'), # Example: /blog/archive/2019/nov/ path('archive/<int:year>/<int:month>/', views.PostMonthArchiveView.as_view(month_format = '%m'), name='post_month_archive'), # Example: /blog/archive/2019/nov/10/ path('archive/<int:year>/<int:month>/<int:day>/', views.PostDayArchiveView.as_view(), name='post_day_archive'), # Example: /blog/archive/today/ path('archive/today/', views.PostTodayArchiveView.as_view(), name='post_today_archive'), ] views.py from django.shortcuts import render # Create your views here. from django.views.generic import ListView, DetailView, ArchiveIndexView, YearArchiveView, MonthArchiveView, \ DayArchiveView, TodayArchiveView from blog.models import Post class PostListView(ListView): model = Post template_name = 'blog/post_all.html' context_object_name = 'posts' paginate_by = 2 class PostDetailView(DetailView): model = Post class PostArchiveView(ArchiveIndexView): model = Post date_field = 'modify_dt' class PostYearArchiveView(YearArchiveView): model = Post date_field … -
How to use PermissionRequiredMixin in FBV?
I am thinking about how I can use PermissionRequiredMixin in FBV.(I have used the same in CBV and it is working as expected). Please find the FBV(here need to implement permission). I don't want to use @login_required() @login_required() This will check only if the user is authenticated or not. def delete_viewgen(request,PermissionRequiredMixin,id): oneuser=ShiftChange.objects.get(id=id) permission_required = ('abc.add_shiftchange',) oneuser.delete()# delete return redirect('/gensall') I am getting ERROR : missing 1 required positional argument: 'PermissionRequiredMixin' CBV Case where it is working fine. class ShiftChangeUpdateView(PermissionRequiredMixin,UpdateView): permission_required = ('abc.change_shiftchange',) login_url = '/login/' model=ShiftChange fields='__all__' In CBV it is working fine and if user is not having change permission it is giving 403 Forbidden how to implement same in FBV and also how to customize 403 Forbidden message. Thanks! -
int() argument must be a string, a bytes-like object or a number, not 'NoneType' - Django
I'm creating a way on a website, for a user to 'bid' on an item, similar to ebay. I'm getting the error: int() argument must be a string, a bytes-like object or a number, not 'NoneType' This is for the line: user_bid = int(request.POST.get("bid")) I think it thinks 'bid' is None or NoneType. But I'm not sure why. Is there a way to convert this into a float or int? When I do: int(float('bid') or int(float(request.POST.get('bid') it also doesn't work. I need to convert it to int or float because I cannot use the > with a string, I just get another error. I'd appreciate any insight you have! views.py def new_bid(request, listingid): current_bid = Listings.objects.get(id=listingid) current_bid = current_bid.starting_bid if request.method == "POST": user_bid = int(request.POST.get("bid")) if user_bid > current_bid: listing_items = Listings.objects.get(id=listingid) listing_items.starting_bid = user_bid listing_items.save() try: if Bid.objects.filter(id=listingid): bidrow = Bid.objects.filter(id=listingid) bidrow.delete() bidtable = Bid() bidtable.user = request.user.username bidtable.title = listing_items.title bidtable.listingid = listingid bidtable.bid = user_bid bidtable.save() except: bidtable = Bid() bidtable.user = request.user.username bidtable.title = listing_items.title bidtable.listingid = listingid bidtable.bid = user_bid bidtable.save() Bid.objects.filter(id=listingid) return render(request, "auctions/listing.html", { "i": "id" }) else: response = redirect('listingpage', id=listingid) response.set_cookie('error', 'Bid should be greater than current price', max_age=3) return … -
python crash course heroku ModuleNotFoundError: No module named 'bootstrap4'
I am currently following along python crash course to deploy my learning log project to heroku, having errors. Would appreciate any help as I am new to this. Running 'heroku open' in cmd gives me the application error page, which I have tried to fix but running 'heroku run python manage.py migrate' gives me the following error Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/app/.heroku/python/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'bootstrap4' in settings.py at the very bottom I have added import django_heroku django_heroku.settings(locals()) and at the top INSTALLED_APPS = [ #My apps 'learning_logs', 'users', #Thirsd party apps. 'bootstrap4', #Default django apps. 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] my pipfile(which I have locked while trying to follow other solutions) [[source]] … -
(begginner) how complete is really django?
Hello i am new in python programmation and programation in general(even if i have some IT related knowledge) i have few basic questions to be sure about how django work so as i understand its a framework for web, and you can use it fully with python What are the limitations of django compared to "basic" html/css/sql/php/js combo ? i also know that django is server side framework which make it work kinda like an app running on your web browser Is it possible/most convenient to do a website ONLY by using python with django ? does the framework really take care of all by itself and we can use python for anything ? How does it handle sql ? does it do some kind of local sql base ?(i only knew basic of sql) Thank you -
Django RelatedObjectDoesNotExist at /HomeFeed/comments/slug-1
Comments Functionality I decided to add a "comments" functionality for anyone to post comments on anyone's post. Everything works except one line of code which is giving me the problem. I receive the following error: RelatedObjectDoesNotExist at /HomeFeed/comments/slug-1 Comment has no post. The error is directed to the views.py Specifically this line of code: form.instance.post.slug = self.kwargs['slug'] Please kindly advise how this code can be altered to remove the error. views.py class AddCommentView(CreateView): model = 'Comment' form_class = CommentForm template_name = 'HomeFeed/add_comment.html' def form_valid(self, form): form.instance.post.slug = self.kwargs['slug'] return super().form_valid(form) success_url =reverse_lazy('main') urls.py path('comments/<slug>', AddCommentView.as_view(), name= "add_comment"), forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['name', 'body'] widgets = { 'name' : forms.TextInput(attrs={'class': 'form-control'}), 'body' : forms.Textarea(attrs={'class': 'form-control'}), } models.py class BlogPost(models.Model): chief_title = models.CharField(max_length=50, null=False, blank=False) body = models.TextField(max_length=5000, null=False, blank=False) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='blog_posts', blank=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) date_published = models.DateTimeField(auto_now_add=True, verbose_name="date published") def __str__(self): return self.chief_title def total_likes(self): return self.likes.count() class Comment(models.Model): post = models.ForeignKey(BlogPost, related_name='comments', on_delete=models.CASCADE) name = models.CharField(max_length=255) body = models.TextField() date_added = models.DateField(auto_now_add=True) def __str__(self): return '%s - %s' %(self.post.chief_title, self.name) add_comment.html (this html is for ppl to add their comments) <div class="form-group"> <form method="POST"> {% csrf_token … -
NoReverseMatch at /admin/ when add custom url
I'm trying to add a custom page in django admin. I wrote code as I've learned, but everytime I try to access the custom page I created, NoReverseMatch exception keeps occuring. NoReverseMatch at /admin/order/order/date_view/ Reverse for 'app_list' with keyword arguments '{'app_label': ''}' not found. 1 pattern(s) tried: ['admin/(?P<app_label>auth|fcuser|product|order)/$'] I've tried various code I could find online, but none is working. Following is my code. class OrderAdmin(admin.ModelAdmin): .... def get_urls(self): urls = super().get_urls() # urls = super(OrderAdmin, self).get_urls() custom_urls = [ # path('date_view/', self.admin_site.admin_view(self.custom_date_view)) # url(r'^date_view/', self.admin_site.admin_view(self.custom_date_view)) path('date_view/', self.custom_date_view) ] return custom_urls + urls def custom_date_view(self, request): context = dict() return TemplateResponse(request, 'admin/order_date_view.html', context) None of the comment solved the issue. I'd be really grateful if anyone can help me out. I want my OrderAdmin class keeps inheriting ModelAdmin. -
how to make attribute in django 3
(myvenv) basekmacbook@BASEK-MACBOOK-PRO portfolio-project % python manage.py makemigration Traceback (most recent call last): File "/Users/basekmacbook/Desktop/portfolio-project/manage.py", line 22, in main() File "/Users/basekmacbook/Desktop/portfolio-project/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/basekmacbook/Desktop/myvenv/lib/python3.9/site-packages/django/core/management/init.py", line 401, in execute_from_command_line utility.execute() File "/Users/basekmacbook/Desktop/myvenv/lib/python3.9/site-packages/django/core/management/init.py", line 377, in execute django.setup() File "/Users/basekmacbook/Desktop/myvenv/lib/python3.9/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/basekmacbook/Desktop/myvenv/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File"/Users/basekmacbook/Desktop/myvenv/lib/python3.9/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python@3.9/3.9.1_3/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1030, in _gcd_import File "", line 1007, in _find_and_load File "", line 986, in _find_and_load_unlocked File "", line 680, in _load_unlocked File "", line 790, in exec_module File "", line 228, in _call_with_frames_removed File "/Users/basekmacbook/Desktop/portfolio-project/jobs/models.py", line 3, in class Job(models.Model): File "/Users/basekmacbook/Desktop/portfolio-project/jobs/models.py", line 5, in Job summary = models.Charfield(max_length=200) AttributeError: module 'django.db.models' has no attribute 'Charfield' -
Django foreign key field not updating with selected value from React Select component
I have a webpage in my issue tracker project that allows a project manager to assign a user to a project. I am using React Select to allow the manager to select a user from a dropdown. When they click the add user button, the selected value gets sent to the backend through an api call. I have an APIView called assignuser, which takes in the post request and updates the user foreign key field in my Project model. Am I referencing the selected value wrong? I have tried sending selectedValue.value to my backend but it keeps on coming up as undefined. React Frontend import React, { Component } from "react"; import { useState, useEffect } from "react"; import { Grid, TextField, Button, Typography } from "@material-ui/core"; import { FixedSizeList as List } from 'react-window'; import css from './style.css'; import Select from 'react-select'; import {useLocation} from "react-router"; const manageusers = () => { const [role, setRole] = useState([]); const location = useLocation(); const [project_name, setProjectName] = useState(); const [selectedValue, setSelectedValue] = useState() const rolelist = []; const handleChange = obj => { setSelectedValue(obj); } useEffect(() => { fetch("/api/manageroles") .then((response) => response.json()) .then((data) =>{ setRole(data) }) }, []) const post = … -
TemplateDoesNotExist at
I have a problem with REQUEST. Add myapp, so that it recognizes the parameters in request, however, it keeps throwing me an error when reloading the page. What is the problem? Ilustration of problem in WEB CMD def index(request): def index(request): html= """ <h1>Inicio</h1> <p>Años hasta 2050:</p> <ul> """ year =2021 while year<=2050: if year%2 == 0: html+=f"<li>{str(year)}</li>" year+=1 html +="</ul>" #return HttpResponse(layout + html) return render(request, 'index.html') (Index function) -
I Want to create a unique id in django model with customer-auto incremented number
There are 2 models, customer model and ticket creation for a customer class cust_M(models.Model): customer = models.TextField(max_length=8) class TKT(models.Model): tkt_unique_id = models.ForeignKey(customer) + autoincremented when ever we create a instance for the TKT i want to increment the number for the customer. eg: customer1 - 1 customer1 - 2 customer1 - 3 customer2 - 1 customer2 - 2 customer2 - 3 ... ... -
Django custom form - is_valid does not call clean method when __init__ method available
I have the following custom form code in Django: class JoinMeetingForm(forms.Form): meeting_id = forms.UUIDField(help_text="Enter the UUID") def __init__(self,user,*args,**kwargs): self.user=user super(JoinMeetingForm,self).__init__(*args) def clean_meeting_id(self): data = self.cleaned_data['meeting_id'] meeting = Meeting.objects.filter(pk=data) querySuccess = False if len(meeting) == 1: if(meeting[0].joined_user==None): querySuccess = True # ToDo return data First, I call JoinMeetingForm(request.user), which calls the init method. Then, I call form.is_valid(), however, this does not call the clean_meeting_id() method - why is this the case? Strangely, if I comment out the init method, the is_valid() method calls the clean_meeting_id() method. Thanks in advance! -
ValueError: The view mode.views.userSettings didn't return an HttpResponse object. It returned None instead
I am trying to fix this error but I don't know what is the reason for getting it. I am working on a Django Project trying to add a Theme Selection Functionality. The user can select the theme either Light or Dark and it reflects in the backend by the CSS file under the setting.value. The idea is that when a user selects a theme it is saved in the backend and it doesn't chage(unless another theme is chosen). The problem now is that when I refresh the page it returns back to the initial theme and I receive the below error: Traceback (most recent call last): File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\base.py", line 186, in _get_response self.check_response(response, callback) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\base.py", line 307, in check_response raise ValueError( ValueError: The view mode.views.userSettings didn't return an HttpResponse object. It returned None instead. Here is the model.py class Setting(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="mode",null=True,blank=True) name = models.CharField(max_length=200, null=True) value = models.CharField(max_length=200) def __str__(self): return self.name Here is the views.py def userSettings(request): user, created = User.objects.get_or_create(id=1) setting = getattr(user, 'setting', None) if setting: seralizer = UserSerailizer(setting, many=False) return JsonResponse(seralizer.data, safe=False) def updateTheme(request): data = json.loads(request.body) theme = data['theme'] user … -
Many-to-many and hierarchical database design
i'm designing a database and run into some problems: I have a Document entity consisting of many fields. Mostly i want to use the same version of that document but sometimes users should be able to customize some of the fields for a specific usage of the document. Not customized fields should use the value of the parent document as a default. Changes to the parent document should get propagated to any not customized field of a specific usage. I have a table Document: Document: id | field1| field2 | field3| parentDocumentId For parent documents is parentDocumentId = Null. Customized usages of a document have the new value for the customized fields saved and for not customized fields simply null. Is this a good design? Furthermore the Document entity has a many-To-many relationship with another entity Course. My problem now is when i look at a row of Document with parentDocumentId != null and courses = null i can't determine if the relationship is either not customized by the user yet and i should use the value of the parent document or the field is customized by the user and simply has no courses. How can i solve that? Thanks -
Django Error - Reverse for 'new_bid' with arguments '('',)' not found. 1 pattern(s) tried:
I'm somewhat new to Django and creating a way for users to 'bid' on items, similar to ebay. I am getting the error: Reverse for 'new_bid' with arguments '('',)' not found. 1 pattern(s) tried: ['new_bid/(?P[0-9]+)$'] I know I have some things mixed up, specifically the end of views.py in the return render request but I'm not sure what I need to have there. I know in the html {% url 'new_bid' i.id %} is also not correct, but I'm struggling to figure out what should be here as well. Any help is appreciated as I'd like to learn more. views.py def new_bid(request, listingid): current_bid = Listings.objects.get(id=listingid) current_bid = current_bid.starting_bid if request.method == "POST": user_bid = int(request.POST.get("bid")) if user_bid > current_bid: listing_items = Listings.objects.get(id=listingid) listing_items.starting_bid = user_bid listing_items.save() try: if Bid.objects.filter(id=listingid): bidrow = Bid.objects.filter(id=listingid) bidrow.delete() bidtable = Bid() bidtable.user = request.user.username bidtable.title = listing_items.title bidtable.listingid = listingid bidtable.bid = user_bid bidtable.save() except: bidtable = Bid() bidtable.user = request.user.username bidtable.title = listing_items.title bidtable.listingid = listingid bidtable.bid = user_bid bidtable.save() Bid.objects.filter(id=listingid) return render(request, "auctions/listing.html", { "i": "id" }) else: response = redirect('listingpage', id=listingid) response.set_cookie('error', 'Bid should be greater than current price', max_age=3) return response else: return redirect('index') The urls in urls.py path("listings/<int:id>", views.listingpage, … -
Return the instance of the model, if a value in it contains a string passed in by a user. Django Rest Framework, filtering
So lets say i have a model called Article, which hold a field called article_title(CharFiled). On the client side, the user passes in a keyword and sends it to the server. Can i make a serialized view, which returns every database instance, on a condition that it contains the passed in keyword in the article_title field? Is there a way to implement this? -
When building forms in Django, is it good practice to use one 'fat' model to contain all my fields for multiple forms?
Context: I am building a car dealership app and have multiple forms to create such as: A basic contact requesting a name, email, phone and comments. A service form requesting the above along with the users make, model and mileage A sales form, requesting all the above again along with a few other similarly relevant questions. Problem: So I'm trying to find out is it best practice to have one 'fat' model containing all these fields and then create multiple forms from them or to create a model per form? I know that I should stick to the DRY practices but I would really benefit from a stronger understanding.