Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django boto3 with s3 not working in production
So I am currently trying to enable large file uploads for my site www.theraplounge.co/ the only problem is I’m using boto3 to upload directly to s3 with https://justdjango.com/blog/how-to-upload-large-files as a guide. The good thing is large files get uploaded when I’m on development server. When I launch code to production server on heroku large files don’t upload anymore. I don’t think code would work locally but not in production which leads me to think the problem may be heroku 30s timeouts although I’m not sure. Anyone got a glue or a hint at what’s going on? -
Reverse for 'category-detail' with arguments '('',)' not found
I get this error when I try accessing my home page. I've tried reading similar solutions but I can't directly relate them to my case. I'm clearly missing something here but I can't see it. this is the traceback error message: Traceback (most recent call last): File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Muhumuza-Ivan\Desktop\JobPortal\jobapp\views.py", line 68, in index return render(request, 'index.html', context) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\shortcuts.py", line 24, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\backends\django.py", line 62, in render return self.template.render(context) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 175, in render return self._render(context) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 167, in _render return self.nodelist.render(context) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 1000, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 1000, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\base.py", line 958, in render_annotated return self.render(context) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\template\defaulttags.py", line 472, in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\base.py", line 88, in reverse return resolver._reverse_with_prefix(view, prefix, *args, **kwargs) File "C:\Users\Muhumuza-Ivan\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 802, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'category-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['jobapp/category/(?P<slug>[-a-zA-Z0-9_]+)/\\Z'] Index.html The error … -
Wagtail-2fa token doesn't work when setting up 2fa after new admin user registration
New users can't seem to set up 2fa--token always fails at set up with wagtail-2fa. Background: I set up a wagtail site a few months ago with Wagtail-2fa (which is based on django-otp). When I first set up an admin user with 2fa, the token works fine. That admin login has no problems using 2fa. When I try to set up new users, I can register the user, but when the user logs in for the first time, it requires 2fa set up (which is the desired behavior) but the token always fails. I've tried Google Authenticator, Symantec VIP, and Duo Mobile. None of them work for new users. Wagtail-2fa uses TOTP so I checked the time on the device and on the server and they appear to match at least to the minute. I've tried the same process on my localhost, staging, and production (the latter two on heroku), and none of them work (but the original admin with 2fa works). My main hypothesis now is that something broke with wagtail-2fa when I upgraded several packages: django 3.1.11 --> 4.0.5 wagtail 2.15.1 --> 3.0.1 It could be that wagtail-2fa doesn't support wagtail 3.0.1 or django 4.0.5. I'm going to … -
POST http://localhost:8000/api/project/create/ 400 (Bad Request) error when sending POST data from the React app using fetch() to Django API
I am working on a simple DRF + ReactJS app, but when I came across making a POST data from React app to the Django API, this error happens on the web console POST http://localhost:8000/api/project/create/ 400 (Bad Request) and it says the problem is on my Create.jsx This is my Create.jsx file: import React, { useState, useEffect} from 'react' import { useNavigate } from 'react-router-dom' import axios from 'axios' const Create = () => { const history = useNavigate() const [title, setTitle] = useState("") const [body, setBody] = useState("") const createProject = async () => { fetch('http://localhost:8000/api/project/create/', { method: "POST", headers: { 'Content-Type': 'application/json' }, title: JSON.stringify(title), body: JSON.stringify(body), }) console.log('title', title) console.log('BODY', body) } return ( <div className="create-project"> <p> <input type="text" onChange={e => setTitle(e.target.value)} value={title} ></input> <textarea type="text" onChange={e => setBody(e.target.value)} value={body}></textarea> <button onClick={createProject}>Submit</button> </p> </div> ) } export default Create And this is the APIView in django: views.py class CreateProject(CreateAPIView): queryset = Project.objects.all() serializer_class = ProjectSerializer urls.py if needed: path('project/create/', CreateProject.as_view(), name="create-project"), -
How to link properly sphinx index.html file to a view
My sphinx documentation is generated properly with custom theme. The documentation file is called index.html which I use as template in a django view to render the documentation. Problem : I lost the the theme sphinx_rtd_theme and links between pages. Could you please help me? -
CKEditor doesn't load on Django admin site
I deployed my project on Heroku but when I login to the admin site on Django, CKEditor doesn't load. I'm using CKEditor in order to implement RichTextField in my models. This is the error GET https://portfolio-jpl.herokuapp.com/static/ckeditor/ckeditor-init.js net::ERR_ABORTED 404 (Not Found) GET https://portfolio-jpl.herokuapp.com/static/ckeditor/ckeditor/ckeditor.js net::ERR_ABORTED 404 (Not Found) Settings.py file # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'general', ] 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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' # Other settings STATIC_URL_DEFAULT_IMAGE = '/static/base/img/default.png' STATIC_URL_PROFILE_IMAGE = '/static/base/img/personal/' STATIC_URL_IMG = '/static/base/img/portfolio/' I'm a little confused due to I don't have CKEditor folder in the static directory. -
Change field using setter in Admin panel
I have following structure: (Models) class Lessons(models.Model): status_choice = [ ("COMING", _("Coming soon..")), ("PROGRESS", _("In progress")), ("DONE", _("Done")), ("CANCELED", _("Canceled")) ] _status = models.CharField(max_length=15, choices=status_choice, default=COMING_SOON) @property def status(self): return self._status @status.setter def status(self, value): #some validation self.save() And admin.py: @admin.register(Lessons) class AdminLessons(admin.ModelAdmin): list_display = ("class_name", "get_full_status", "time_start", "time_end") @admin.display(description="Status") def get_full_status(self, obj): return [item[1] for item in Lessons.status_choice if item[0] in obj.status] How to implement a setter when the field is changed by the admin panel? Code (above) works when we got requests for changes but how to implement him when changes are made by the admin panel? I will be grateful for your help! -
How to create users in Django?
I am trying to use Django's user model, but when I cannot create a new user. I already ran python manage.py makemigrations and python manage.py migrate. If I try to run the commands again, I get a "No Changes Detected" message. I was able to create a superuser for Django admin, and I can use that user to log into my web application using the views that I created, but if I try to create a user, it does not appear in Django admin. models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): pass views.py for creating the user from django.db import IntegrityError from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User def register(request): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] confirm = request.POST["confirm"] if password != confirm: return render(request, "capstone/register.html",{ "error_message": "Your passwords must match." }) try: user = User.objects.create_user(username, password) user.save() except IntegrityError: return render(request, "capstone/register.html",{ "error_message": "You will need to pick another username." }) login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "capstone/register.html") I have also added AUTH_USER_MODEL = 'capstone.User' to my project's setting.py. … -
Django - Giving a view access to multiple models
I followed a tutorial on Youtube that makes a website to create posts. Currently, I am working on displaying other people's profiles and their posts on their profile pages. I did it by accessing the author of the first post, but it only works if the user posted something. Is there another way to do it? The view: class UserProfileView(ListView): model = Post template_name = 'blog/user_profile.html' # defaults to <app>/<model>_<viewtype>.html--> blog/post_list.html context_object_name = 'posts' #defaults to objectlist paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') user_profile.html: {% extends 'blog/base.html' %} {% block title %}{{ view.kwargs.username }}'s Profile{% endblock title %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ posts.first.author.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ view.kwargs.username }}</h2> <p class="text-secondary">{{ posts.first.author.email }}</p> <p class="article-content">{{ posts.first.author.profile.bio }}</p> </div> </div> {% if posts.first.author == user %} <a class="btn btn-outline-secondary ml-2" href="{% url 'change_profile' %}">Edit Profile</a> {% endif %} </div> <br> {% if posts.first.author == user %} <h3 class="ml-2 article-title">Blogs You Posted</h3> {% else %} <h3 class="ml-2 article-title">Blogs By {{ view.kwargs.username }}</h3> {% endif %} And the Post and Profile module: class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self) … -
Django upgrade to 4.0 Abstract models cannot be instantiated
I'm upgrading my Django App from 2.2 to 4.0.6. I made different code upgrades and have the APP mostly working. But I get the following error "Abstract models cannot be instantiated" and can't find clues on how to solve this (without downgrading Django versiion as in this post Models class AbstractMes(models.Model): mes = models.DateField(blank=False, null=True) operaciones = models.IntegerField(blank=True, null=True) facturacion = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) unidades = models.IntegerField(blank=True, null=True) diferencia = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) diferencia_porc = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) diferencia_media_movil = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) class Meta: abstract = True def __str__(self): return str(self.mes) class Meses(models.Model): mes = models.DateField(blank=False, null=True) operaciones = models.IntegerField(blank=True, null=True) facturacion = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) facturacion_dolar = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) unidades = models.IntegerField(blank=True, null=True) def __str__(self): return str(self.mes) In views meses = Meses.objects.all() abstract_meses = AbstractMes(meses) Any clues welcome. Thanks! -
Django dependent smart-select not working properly
django smart-select not working properly The first column is working but second column is not working , I added the scripts in the html page , but my problem not solved I added this scripts <script type="text/javascript" src="{% static 'smart-selects/admin/js/chainedfk.js' %}"></script> <script type="text/javascript" src="{% static 'smart-selects/admin/js/chainedm2m.js' %}"></script> <script type="text/javascript" src="{% static 'smart-selects/admin/js/bindfields.js' %}"></script> in url I added urlpatterns = [ path('admin/', admin.site.urls), path('', include('hospitalapp.urls')), path(r'^chaining/', include('smart_selects.urls')), ] -
How dynamically change video resolution on a web-site
I have my own video hosting created on django, and I want to add the ability to change the quality of the video. What is the best way to do this? I save multiple copies of videos with different resolutions, and when users change the quality, I change the displayed video, but how can I dynamically change the resolution and not store many copies? -
choose one value multiple time in many to many field of Django
i'm creating a Ecommerce website & i have a order item model which has many to many relationship with product model so customer can add products to their order. everything is okay with my system but the customer can't order one product twice or more since Many to many field choose an option once! how can i add one value twice in a many to many field?? also if you think there's a better way rather than using this system & many to many field, you can suggest! #my_views_py from django.db import models from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User,null=True,blank=True,on_delete=models.SET_NULL) name = models.CharField(max_length=100,null=True) email = models.CharField(max_length=100,null=True) def __str__(self): return self.name or str(self.id) class Product(models.Model): title = models.CharField(max_length=200) price = models.FloatField() image = models.ImageField(upload_to='static/images') def __str__(self): return self.title class Order(models.Model): customer = models.ForeignKey(Customer,on_delete=models.SET_NULL,blank=True,null=True) date = models.DateField(auto_now_add=True,blank=True) complete = models.BooleanField(default=False,null=True,blank=False) transaction_id = models.CharField(max_length=200,null=True,blank=True) def __str__(self): return str(self.id) class OrderItem(models.Model): product = models.ManyToManyField(Product,blank=True) order = models.ForeignKey(Order,on_delete=models.SET_NULL,null=True,blank=True) date = models.DateField(auto_now_add=True) def __str__(self): return str(self.order) -
Multiple Count annotations in Django filtering causing ProgrammingError
I am running a search page on a model which has two linked models with a ManyToMany (ForeignKey) relationship. class Session(models.Model): ... fields ... class Tuition(models.Model): session = models.ForeignKey(Session, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) ... class Housing(models.Model): session = models.ForeignKey(Session, on_delete=models.CASCADE) ... I would like to filter on aggregate Counts of these two models. For Housing it's just a simple Count, I want to filter by if there is housing available for that session (aka if housing_count__gt=0) queryset.annotate(housing_count=Count('housing', distinct=True)) For Tuition I'm including a filter in the Count, because I want to account for both those where the price is listed and those where it's null. And thus, I want to again filter for sessions where only at least tuition with that price (or one null price) is linked. (tuition_count__gt=1) queryset = queryset.annotate(tuition_count=Count('tuition', filter=Q(Q(tuition__price__lte=max_tuition_passed) | Q(tuition__price__isnull=True)), distinct=True)) **However, I keep running into an issue, **seemingly in particular with the tuition_count (I've tried commenting out one/both at a time). ProgrammingError at /search/programs/summer-intensives function count(integer, boolean) does not exist LINE 1: ...ECT COUNT(*) FROM (SELECT "session"."id" AS Col1, COUNT(DIST... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. I've tried … -
pgAdmin Table not showing in database after successfull migration
I am trying to create a REST API using psql and Django , i've reached the stage of applying migrations to add tables to my database, these migrations are successfull but when i open pgadmin to view my database their are no tables no matter how many times i refresh. Below is how i run the migrations: python manage.py makemigrations ExampleApp python manage.py migrate ExampleApp Any help would be much appreciated as I am completely lost at this stage :) -
Choose how to order Django Model choices
When displaying the below choices, I want to be able to order them as follows Preparation, Review, Update, Finalised and Completed. Right now, they are ordered alphabetically. The below is a simple model: class Choice(models.Model): status_choices = [ ("", "Select Current Status"), ("Preparation", "Preparation"), ("Review", "Review"), ("Update", "Update"), ("Finalised", "Finalised"), ("Completed", "Completed"), ] current_status = models.CharField( max_length=32, choices = status_choices, default = "Select current status", ) class Meta: ordering = ["current_status"] I read that assigning a number in the Tuple can allow them to be ordered, which I tried per the below: status_choices = [ ("", "Select Current Status"), ("1", "Preparation"), ("2", "Review"), ("3", "Update"), ("4", "Finalised"), ("5", "Completed"), ] However, this made no difference. forms.py listed below: class TaskForm(ModelForm): class Meta: model = Choice fields = [ 'current_status', ] widgets = { 'current_status' : forms.Select(attrs={'placeholder':'Select Current Status', 'class':'table_data_request_status'}), } I feel like this should be very simple but maybe not. Any help would be greatly appreciated. I have searched previous questions but no luck. -
Creating a separate comments app for a ticket app. Keep getting NoReverseMatch error
I'm creating a separate comments app for a ticket app project. How do I get the ticket pk from the Ticket model into get_absolute_url method that's within my Comment model? These are my models ticket models.py class Ticket(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) assignee = models.ForeignKey(Profile, on_delete=models.SET_NULL, blank=True, null=True) status = models.BooleanField(choices=MARKED, default=True) priority = models.TextField(choices=PRIORITIES, default='None', max_length=10) label = models.CharField(choices=TYPES, default='Misc', max_length=100) def __str__(self): return self.title def get_absolute_url(self): return reverse('ticket-detail', kwargs={'pk': self.pk}) comment models.py class Comment(models.Model): ticket = models.ForeignKey(Ticket, related_name='comments', on_delete=models.CASCADE, null=True) title = models.CharField(max_length=20) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('tickets:ticket-detail', kwargs={'pk': self.ticket_id}) -
accordion items in jinja2 flaks for loop collapse and show together and not independently
my accordion items do not expand separately when one is clicked on. They either both show their content or both remain close. I tried interactive IDs but this did not work. {% for study in studies %} <div class="accordion" id="accordionExample"> <div class="accordion-item"> <h2 class="accordion-header" id="heading{{ study.uid }}"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs- target="#collapse{{ study.uid }}" aria-expanded="true" aria-controls="collapse{{ study.uid }}"> {{ study.uid }} </button> </h2> <div id="collapse{{ study.uid }}" class="accordion-collapse collapse" aria- labelledby="heading{{ study.uid }}" data-bs-parent="#accordionExample"> <div class="accordion-body"> text </div> </div> </div> {% endfor %} is it maybe something to do with jquery and bootstrap not being the same version? Inspecting the code shows that each accordion item in the loop has a different ID...enter image description here -
Heroku "Application error" on a Django/React app
I'm currently working on a to do list project for my studies and I was able to chose the technologies involved. I decided to use Django, React, MongoDB for the app and Heroku for the hosting. I had previous experience with React MongoDB and NodeJS and managed to host the app on heroku very easily. However with this new project I always get an "Application Error" whenever I try to access the website. I struggled to find up to date information on how to properly host a Django/React app on Heroku and none of the answers I found solved my problem. What concerns me the most is that the deployment log do not show any major issue during the build process : > Enumerating objects: 7, done. Counting objects: 100% (7/7), done. Delta compression using up to 8 threads Compressing objects: 100% (4/4), done. Writing objects: 100% (4/4), 356 bytes | 356.00 KiB/s, done. Total 4 (delta 3), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpacks: remote: 1. heroku/nodejs remote: 2. heroku/python remote: -----> Node.js app detected remote: remote: -----> Creating runtime environment remote: … -
django form not submitting when rendering specific fields in template
I have an UpdateUserForm: class UserUpdateForm(UserChangeForm): email = forms.EmailField() first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) username = forms.CharField(max_length=100, widget=forms.TextInput()) last_login = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'type': 'hidden'})) is_superuser = forms.CharField(max_length=100, widget=forms.CheckboxInput(attrs={'type': 'hidden'})) is_staff = forms.CharField(max_length=100, widget=forms.CheckboxInput(attrs={'type': 'hidden'})) is_active = forms.CharField(max_length=100, widget=forms.CheckboxInput(attrs={'type': 'hidden'})) date_joined = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'type': 'hidden'})) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'last_login', 'date_joined') def update_user_notification(self): email = self.cleaned_data['email'] username = self.cleaned_data['username'] if self.is_valid(): update_user_notification_task.delay(email, username) and a UserUpdate view: class UserUpdate(generic.UpdateView): model = User form_class = UserUpdateForm template_name = 'accounts/update_user.html' def get_object(self): return self.request.user def form_valid(self, form): instance = form.save() form.update_user_notification() return HttpResponseRedirect(reverse('user_detail', args=[str(instance.pk)])) I originally wrote this form in the template as {{form.as_p}} and it worked, but there were some things I wanted to fix: <h1>Update Information...</h1> <form method="POST"> {% csrf_token %} {{form.as_p}} <button>UPDATE</button> </form> <br></br> <a href="{% url 'user_detail' user.pk %}">Back</a> <a href="/">Home</a> {% endblock %} Rendered as this: I wanted to get rid of those password related things at the bottom so I changed my form to: <form method="POST"> {% csrf_token %} <p><label>{{form.email.label}}: </label>{{form.email}}</p> <p><label>{{form.username.label}}: </label>{{form.username}}</p> <p><label>{{form.first_name.label}}: </label>{{form.first_name}}</p> <p><label>{{form.last_name.label}}: </label>{{form.last_name}}</p> <button>UPDATE</button> </form> This worked on the frontend, but now my form isn't submitting. When I click update, the page looks as if it's … -
How to populate model with having model django?
I have model People: with name, phone email, address fields using Django's management commands I want populate Contact model with the same fields command file: from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Sorting leads ' def handle(self, *args, **kwargs): pass 1.Multiple People with the same name and phone number should be merged together, so the resulting Contact contains all emails and addresses from merged Leads. 2. Multiple People with the same name, but different phone number and e-mail should be saved as separate contacts How have I do it ? Should I do with raw sql or there is better solution. -
Django ModelForm DateField value render
models.py class MyModel(models.Model): date = models.DateField() views.py if request.method == 'GET': instance = MyModel.objects.get(pk=pk) form = MyModelForm(instance=instance) return render(request, 'update.html', context={'form': form}) update.html <input type="date" name="date" value="{{ form.date.value.isoformat }}" /> Works fine. But in POST method if the form is not valid I rerender the template with errors and I want to render values got from POST data. views.py if request.method == 'POST': instance = MyModel.objects.get(pk=pk) form = MyModelForm(request.POST, instance=instance) form.is_valid(): pass return render(request, 'update.html', context={'form': form}) But then form.date.value is in isoformat already (because it came from POST) and the template's code stops render date value properly. How to fix it? The solution I have found is value="{{form.start_date.value.isoformat|default:form.start_date.value}}" but I don't think it is good. -
Django Forms Show Extra Categories For Users Part Of Group
I'd like to show these categories below additionally with users who have the blogger category. The current issue is.. For a blogger user it's only showing blogger categories when it should be showing all For a normal user it's showing blogger categories when it should only be showing the original 3 forms.py class PostCreateForm(ModelForm): class Meta: model = Post fields = [ "title", "category", "associated_portfolios", "body", ] exclude = ('allow_comments',) def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) blogger = User.objects.filter(groups__name='blogger').exists() print("Current User:", user) print("Blogger User:", blogger) super(PostCreateForm, self).__init__(*args, **kwargs) self.fields['category'].choices = ( ("Watchlist", "Watchlist"), ("Lesson/Review", "Lesson/Review"), ("General", "General"), ) if User.objects.filter(groups__name='blogger').exists(): self.fields['category'].choices = ( ("Analysis", "Analysis"), ("Milestone", "Milestone"), ("Features", "Features"), ("Tutorials", "Tutorials"), ("Careers", "Careers"), ("Community", "Community"), ) -
How to model complex left join Django
I have two Django models that have a relationship that cannot be modelled with a foreign key class PositionUnadjusted(models.Model): identifier = models.CharField(max_length=256) timestamp = models.DateTimeField() quantity = models.IntegerField() class Adjustment(models.Model): identifier = models.CharField(max_length=256) start = models.DateTimeField() end = models.DateTimeField() quantity_delta = models.IntegerField() I want to create the notion of an adjusted position, where the quantity is modified by the sum of qty_deltas of all adjustments where adj.start <= pos.date < adj.end. In SQL this would be SELECT pos_unadjusted.id, pos_unadjusted.timestamp, pos_unadjusted.identifier, CASE WHEN Sum(qty_delta) IS NOT NULL THEN pos_unadjusted.qty + Sum(qty_delta) ELSE qty END AS qty, FROM myapp_positionunadjusted AS pos_unadjusted LEFT JOIN myapp_adjustment AS adjustments ON pos_unadjusted.identifier = adjustments.identifier AND pos_unadjusted.timestamp >= date_start AND pos_unadjusted.timestamp < date_end GROUP BY pos_unadjusted.id, pos_unadjusted.timestamp, pos_unadjusted.identifier, Is there some way to get this result without using raw sql? I use this query as a base for many other queries so I don't want to use raw sql. I've looked into QuerySet and extra() but can't seem to coerce them into having this precise relationship. I'd love for position and PositionUnadjusted to have the same model and same API with no copy-pasting since right now updating them is a lot of copy pasting. -
Getting NOT NULL CONSTRAINT from both views using django
I have an app that displays a folder which also allows you to create a subfolder within that folder. Within both the folder and the subfolder, you can upload files. Whenever I try to do that, I get the NOT NULL CONSTRAINT error. If I try uploading a file in the parent folder i get NOT NULL constraint failed: documents_document.subfolder_id and if I try uploading a file in the subfolder I get NOT NULL constraint failed: documents_document.folder_id. parent folder detail view @login_required @group_required('Document Supervisor') def folder_detail(request, pk): folder = Folder.objects.get(id=pk) documents = Document.objects.filter(folder=folder) form = DocumentForm() subfolders = SubFolder.objects.filter(folder=folder) if request.method == "POST": form = DocumentForm(data=request.POST or None, files=request.FILES or None) if form.is_valid(): form = form.save(commit=False) form.folder = folder form.created_by = request.user form.name = str(form.file.url) form.name = form.name.replace("/media/", "") form.save() messages.success(request, "Document added successfully!") return redirect(f"/documents/folder/{folder.id}") context = { "folder": folder, "documents": documents, "form": form, "subfolders": subfolders, } return render(request, "documents/folder_detail.html", context) subfolder view @login_required @group_required('Document Supervisor') def subfolder_detail(request, pk): sub = SubFolder.objects.get(id=pk) documents = Document.objects.filter() form = DocumentForm() if request.method == "POST": form = DocumentForm(data=request.POST or None, files=request.FILES or None) if form.is_valid(): form = form.save(commit=False) form.sub = sub form.created_by = request.user form.name = str(form.file.url) form.name = form.name.replace("/media/", "") form.save() …