Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NameError: name 'Watchlist' is not defined although I defined it
I'm implementing a watchlist page but Im getting this error. This is the line of code that is failing: def watchlist(request, listing_id): watchlist = Watchlist(user=request.user, mylist=listing_id) Why am i getting a name error if I have it defined here? class Watchlist(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) mylist = models.ForeignKey(Listing, on_delete=models.CASCADE) This model is at the end of models.py, so this is not a problem where i am referencing something that I havent previously defined. I also have it imported in admin.py. Any ideas? -
(django)i created a todo app in django but everytime i update the task. It creates a new object
It creates new object everytime i update the task. I tried alot but it still does mot work correctly .Help me please def index(request): task = Task.objects.all().order_by('-created_on') form= TaskForm() if request.method=='POST': form= TaskForm(request.POST) if form.is_valid(): form.save() return redirect ('/') return render(request('task/list.html',{'task':task,'form':form}) def update_task(request,pk): task =Task.objects.get(id=pk) form= TaskForm(instance= task) if request.method=='POST': form= TaskForm(request.POST,instance=task) if form.is_valid(): form.save() return redirect('/') return render(request,'task/update_task.html', {'form': form}) -
how to save the data in unbound ModelForm, after user puts in the missing values in the rendered form, to the database in Django 3.0?
I am a beginner in Django and don't know what I am missing. Here's the issue: I am creating a ModelForm to create an offer on a property where I am putting in initial values to some of the fields such as property's address, offer price, user_id, property_id and leave some fields upto the user to fill in like whether he wants to pay in cash or loan, what's the down payment etc. So after the user makes some changes and presses submit at the bottom of the form, I want the form to save to the corresponding table in the postgres db. Here's the code: #models.py class Offers(models.Model): listing = models.ForeignKey('something.something', on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=100) email = models.EmailField() street_address = models.CharField(max_length=200) city = models.CharField(max_length=50) state = models.CharField(max_length=2) and so on... # forms.py from django import forms from .models import Offers class OfferForm(forms.ModelForm): class Meta: model = Offers fields = ['name', 'email', 'street_address', 'city', 'state', 'zipcode', 'offer_price', 'some', 'other', 'fields'] exclude = ['some', 'fields'] #views.py def make_offer(request): if request.method == 'POST': # create a form instance and populate it with data from the request: # I am successfully able to populate these fields with initial values … -
Image not uploading through forms on registration
I am having an issue with my forms, I've been trying to upload an image when a user registers but it does not submit because an error message is sent which says "This field is required". I'm not too sure where the issue is but I have tried to do this "a_form=InformationForm(request.POST, request.FILES)". But I still got the error message("This field is required") upon registration of the user, even though I have selected the image to be uploaded with the user when registering. I would like to know if a solution could be proffered. The image and code snippet show the issue too. Thanks FORMS from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Information class UserRegisterForm(UserCreationForm): email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder': 'Email'})) username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Username'})) first_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'First name'})) last_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Last name'})) password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'})) password2 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Confirm'})) class Meta: model = User fields = ['username','first_name','last_name', 'email', 'password1', 'password2'] class InformationForm(forms.ModelForm): #sex=forms.ChoiceField(choices=CHOICES) department = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Department'})) majors = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Majors'})) nationality = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Nationality'})) date_of_birth = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'yyyy/mm/dd'})) passport_number = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Passport number'})) phone_number = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Phone number'})) student_passport = forms.ImageField() class Meta: model=Information fields=['department','majors','degree','years','nationality','date_of_birth','passport_number','phone_number','sex','student_passport'] class UserUpdateForm(forms.ModelForm): email = … -
How to create a link between Posts List View and Items List View of the same User
I am creating a project where there are Posts and Items, 2 different models in 2 different apps and each has a user who can be the same. I have created a page for each user to post all related posts called Userpost List view, and I want to add an if statement or a queryset to show a button to link the items related to the same user called Designerpost List view. I don't know how to proceed as I can fix the NoReverse Error Here is the models.py class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) Here is the views.py class UserPostListView(ListView): model = Post template_name = "user_posts.html" context_object_name = 'posts' queryset = Post.objects.filter(admin_approved=True) paginate_by = 6 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(designer=user, admin_approved=True).order_by('-date_posted') Here is the template user_posts.html {% if item %} <a class="primary btn-lg" href="{% url 'core:designer-posts' item.designer %}" role="button">Go to items</a> {% else %} <a href="{% url 'core:designer-posts' item.designer %}"> <button type="button" class="btn btn-primary btn-lg btn-block">Go to items</button> </a> {% endif %} here is the item models.py class Item(models.Model): designer = models.ForeignKey( User, on_delete=models.CASCADE) title = models.CharField(max_length=100) here is the designerlist views.py that I am trying to link to from the user … -
CSRF samesite header in django
Hello I am attempting to use csrf tokens in Django, however I am getting this error, when I submit forms: CSRF verification failed. Request aborted. You are seeing this message because this HTTPS site requires a “Referer header” to be sent by your Web browser, but none was sent. This header is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable “Referer” headers, please re-enable them, at least for this site, or for HTTPS connections, or for “same-origin” requests. If you are using the <meta name="referrer" content="no-referrer"> tag or including the “Referrer-Policy: no-referrer” header, please remove them. The CSRF protection requires the “Referer” header to do strict referer checking. If you’re concerned about privacy, use alternatives like <a rel="noreferrer" …> for links to third-party sites. Here are relevant settings I have configured in django: HOST_SCHEME = "https://" X_FRAME_OPTIONS = 'DENY' SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_SECONDS = 15768000 SECURE_FRAME_DENY = True SECURE_REFERRER_POLICY = "same-origin" SECURE_BROWSER_XSS_FILTER = True SECURE_CONTENT_TYPE_NOSNIFF = True How do I fix this? Thanks so much for the help! -
How to store thumbnails in the same folder with Django ImageKit?
Does anyone have experience using ImageKit to manage thumbnails? I currently have the following in my models.py: class Item(models.Model): id = models.AutoField(primary_key=True) owner = models.ForeignKey( get_user_model(), on_delete=models.SET_NULL, null=True, blank=True ) image = ProcessedImageField( upload_to=image_upload, blank=True, validators=[validate_image], format='JPEG', help_text="Max file size is 3 MB." ) image_thumbnail = ImageSpecField( source='image', processors=[ResizeToFill(50, 50)], format='JPEG', options={'quality': 60} ) I'd like to rename the thumbnail and store it in a particular folder (not the CACHE/images/ folder that ImageKit defaults to), but can't figure out how to do that (and adding an "upload_to" to the thumbnail gives me an error). All help greatly appreciated! Thank you! -
Django Form Validation Error When Filtering by Count
I'm utilizing Django Forms for my web application's server-side filter functionality, and I've made a few customizations so that the checkboxes are rendered in the template with custom labels to include dynamic counts (representing # of student paper submissions), as follows: [x] Doug Funny (5) [ ] Skeeter Valentine (3) [x] Patti Mayonnaise (1) [ ] Roger Klotz (0) Right now, the field's queryset will return Student names for students who haven't submitted any papers (count = 0). As this is a bit too expensive from a page loading / performance perspective (there's a lot of student names, and a lot of paper submissions), I've decided to tweak the queryset so as to not include Student names with 0 counts in the list. To make this change, I've simply added a new filter to the query (.filter(count__gt=0)). students = Student.objects.annotate( num_papers=Coalesce( Subquery( Paper.objects.filter(student=OuterRef('pk')) .values('student') .annotate(cnt=Count('pk')) .values('cnt') ) ,0) ).filter(count__gt=0) This succesfully removes student's who haven't submitted any papers from the filter list. But now, once I select any other name in the list to filter on, I receive the following error: {'studentCheckbox': [ValidationError(['Select a valid choice. 588 is not one of the available choices.'])]} It seems that the form.is_valid() call … -
Why is Django not rendering all HTML elements?
I installed TinyMCE in my Django project so I can write a post with formatting such as bulleted lists, tables, etc. When I try to render the text box, it some elements (like a bullet) is missing, and has no formatting. TinyMCE is indeed working, as I can get a code block with syntax highlighting, but for some reason bulleted lists and even bold just appear as normal text. I put the safe flag as well. -
Get all months and years in a range
I am writing a django application where I have records stored on the basis of datetimefield. first_record = MyModel.objects.filter().order_by('-added').first() first_record = (first_record.added.month, first_record.added.year) last_record = MyModel.objects.filter().order_by('-added').first() last_record = (last_record.added.month, last_record.added.year) Now I want to make a list of all months/year between the first record and last record. A rough idea is: for i in range(first_record, last_record): # do something Where the range function is supposed to give me a list to iterate over which looks like this: [(01,2018),(02,2018),(03,2018),....,(11,2020),(12,2020)] Any ideas how do I do that? Also is (last_record.added.month, last_record.added.year) the right way to get a tuple containing month and year. Note that I want months in the format 01 instead of 1 for first month for example. -
How to make django channels group_send() send to everyone connected after a time.sleep() delay?
I have a consumers.py class method that sends a message to everyone in the channels group with group_send(), and it works great. My issue is that I have a separate, independent class method where I want to call group_send(), then time.sleep(), then group_send() again. For example: self.returnState() time.sleep(5) self.returnState() It's working (kind of) right now, but the issue is that it sends the message to everyone in the group EXCEPT the person who initially triggered the event (sent a message from the front end to consumers.py). I have no idea why this would be happening, as I would expect that if group_send() was triggered and the message was sent to one person in the group immediately, it should be sent to all. I understand asyncio.sleep() might be a more robust solution, but that would require me changing my entire consumers.py class to async. I'm very lost and any feedback would be greatly appreciated. -
Jquery script in Django project isn't detecting form submission
I'm creating a website using Django, and using Ajax to prevent site reload after submitting a form. Right now, I have orders being displayed on the site with an x button beside each order. Clicking the x cancels the order on the database (a post request that changes a value rather than simply deleting it) and also reloads the div in which the orders are housed. I have other forms on this website that are working correctly (they do have fields, though and use crispyforms). The problem I'm facing is that the script isn't detecting that the form is submitted. Here are the pertinent parts of my project: views.py class CancelForm(ModelForm): class Meta: model = Order fields = ['Filled'] ... def cancelorder(request, pk): form = CancelForm(request.POST) if request.is_ajax and request.method == "POST": order = Order.objects.get(pk=pk) order.Filled = "C" instance = order.save(update_fields=["Filled"]) return JsonResponse({"canceled": pk}, status=200) return JsonResponse({"error": ""}, status=400) urls.py urlpatterns = [ path('', views.orderpage, name="order-index"), path('cancel_order/<int:pk>/', views.cancelorder, name="cancel_order"), path('post/ajax/order/', views.postorder, name = "post_order"), path('yourorders/', views.yourorders, name="your_orders"), path('allorders/', views.allorders, name="all_orders"), ] orderpage.html (this is my main page, with the div that is to be reloaded on yourorders.html) <div class="container-fluid ActiveOrderInfoDiv" id="YourOrdersDiv"> {% include 'order/yourorders.html' %} </div> yourorders.html <form action="{% url … -
Why does it shows error in the log in form in Django?
I'm trying to create a website with a log in and registration form in django, the registration works well, it saves the accounts in the database, but when I try to log in, it doesn't work at all, here's the code: views.py from django.shortcuts import render from .forms import UserForm from django.contrib.auth import authenticate, login, logout from django.urls import reverse from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect, HttpResponse # Create your views here. def index(request): return render(request, 'app1/index.html') @login_required def user_logout(request): logout(request) return HttpResponseRedirect(reverse('index')) def register(request): registered = False if request.method == "POST": user_form = UserForm(data=request.POST) if user_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() registered = True else: print(user_form.errors) else: user_form = UserForm() return render(request, 'app1/register.html',{'user_form':user_form, 'registered':registered}) def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password = password) if user: if user.is_active: login(request, username) return HttpResponseRedirect(reverse('index')) else: return HttpResponse("Account Not Active") else: print("Someone tried to login and failed") print(f"Username: {username} and password {password}") return HttpResponse ("Invalid Login details supplied") else: return render(request, 'app1/login.html') models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) forms.py from django import forms from django.contrib.auth.models import User from … -
Creating a function to Specify Directory for Uploaded Images Location
I have created a function for my items model where there are images to be uploaded according to the name of the user and the title of the item. Now I am trying to add more images to this item and there is a foreign key with the image, but now instead of creating randomly uploading the new images to another folder, I want to upload these images to the same folder that was previously determined according to the same item. I have tried to alter the previous function but it returned with an error upload_design_to() takes 1 positional argument but 2 were given I assume because i didn't add self to the function but I don't know what to replace it with. The functions below will be more descriptive: Here is the models and the function where the images is uploaded to a location as per the users name and the title of the item: class Item(models.Model): def upload_design_to(self, filename): return f'{self.designer}/{self.title}/{filename}' designer = models.ForeignKey( User, on_delete=models.CASCADE) title = models.CharField(max_length=100) image = models.ImageField(blank=False, upload_to=upload_design_to) Now I have created a new an Image model to add more images to this item and want them to be uploaded to the very … -
JavaScript Event Listeners not running
I a currently taking CS50w and I am working on the project mail. Most of the code provided is distributed code and I have to add specific features to complete the assignment. I am currently trying to do the following specification "Send Mail: When a user submits the email composition form, add JavaScript code to actually send the email. You’ll likely want to make a POST request to /emails, passing in values for recipients, subject, and body. Once the email has been sent, load the user’s sent mailbox." In order to achieve that I have added an Eventhandler that will listen when the form is submitted and run the sent_email function. However, it is not working and automatically runs the load_mailbox('inbox') function. However, I don't want to remove that line because it was provided but I am at a loss on how to get it run my sent_email function. https://cs50.harvard.edu/web/2020/projects/3/mail/ document.addEventListener('DOMContentLoaded', function() { // Use buttons to toggle between views document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox')); document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent')); document.querySelector('#archived').addEventListener('click', () => load_mailbox('archive')); document.querySelector('#compose').addEventListener('click', compose_email); // Get data document.getElementById('compose-form').onsubmit = () => { sent_email(); } // By default, load the inbox load_mailbox('inbox'); }); async function sent_email(){ try { const response = … -
Checked radio button in Django form
I'm trying to render in template two radio button. But one of them must be checked initialy. My form.py: class ChangeAddressForm(forms.Form): CHOICES = [('current', ''), ('new', '')] address = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect) This is the way I'm writing in template to show them up: {{ address_form.address.0 }} {{ address_form.address.0 }} How can I have the first radio button checked, please? Thank you! -
Including an Item Context to a Post Model to activate if statement in Django
I am trying to add an Item to a list view, the UserPost list view has already a Post context. In my project, a user can add a post and add an item each is a different app with different models. So In my UserPost list view, I have my Posts looped related to a specific user related to it. What I am trying to do is check if this post.user has an item filtered by the same user and if it does exist a button show appears in the page linking to another page with this list of items related to this user. To be more descriptive I want to check for Item for the designer__post and link to this page which is {% url 'core:designer-posts' item.designer %} I hope this clears my question if there are any more clarifications required or code please let me know to add it. I tried to use make use of an Exists subquery [Django-doc] but I didn't succeed it perfecting it Here is the models.py class Post(models.Model): designer = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) Here is the views.py class UserPostListView(ListView): model = Post template_name = "user_posts.html" context_object_name = 'posts' queryset = Post.objects.filter(admin_approved=True) … -
Adding a Field to AbstractUser results in an Operationalerror: no such column
I added this field to AbstractUser: class User(AbstractUser): listed = models.IntegerField(blank=True, null=True) Then I did python makemigrations python migrate And it says that no changes were detected, dont'really know why. I've just added a field Then I refreshed my localhost and I get the following error: no such column: auctions_user.listed And the error points to this line of code if request.user.is_authenticated: If i delete the field, everything goes back to normal, but i dont know why im getting this error -
How to display image from Django form ImageField input without models/database
I'm trying to display an image from a form ImageField on my template once the user has actioned the form. All the previous examples I have read about revolve around saving the image as a static file. Is this necessary? Is it possible to pass the image from the form through a view back onto a template without interaction with the database? I am not using any models and instead, my goal is to send the image to a restful API for classification and display it. ### forms.py from django import forms class FileForm(forms.Form): image = forms.ImageField(help_text="Upload image: ", required=False) ### home_template.py <h2>Tower Predictor</h2> <form method="post" enctype='multipart/form-data'> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> # Display image {% if image %} <img src="{{ image.url }}" alt="img"> {% endif %} ### views.py from django.shortcuts import render import requests from .forms import FileForm def home(request): if request.method == 'POST': form = FileForm(request.POST, request.FILES) if form.is_valid(): image = request.FILES['image'] form = FileForm() context = {'form': form, 'image': image} return render(request, 'web_ui/home.html', context) else: form = FileForm() return render(request, 'web_ui/home.html', {'form': form}) -
How to position objects with initial values?
I have a page made in Django that allows dragging objects, what I do is save the position in X and Y of each object, I store the data in a database, I already have the data, now what I want to do is that when the page is updated, the position of the objects is maintained, already having this data in the database, how do I pass those coordinates to the objects so that when they update they remain in the same position? These are the variables where I have the coordinates: {{ qst.posX }} {{ qst.posY }} Part of the HTML CODE: {% if qst %} <div id="containment-wrapper"> {% for device in qsd %} <div id="{{ device.device_name }}" class="draggable"> <span class="dot" title="{{ device.device_name }}" style="background-color: #197f32"><br/><b><p style="color: #ce3830;"> {{ device.device_name }}</p></b></span> </div> {% endfor %} <button id="save">Save Position</button> </div> {% endif %} JavaScript: $(document).on("ready", function () { $(".draggable").draggable({ containment: "#containment-wrapper" }); }) $(document).on("mouseup", ".draggable", function () { var elem = $(this), id = elem.attr('id'), desc = elem.attr('data-desc'), pos = elem.position(); console.log('Left: ' + pos.left + '; Top:' + pos.top + '; ID:' + id); }); $('#save').on('click', function () { $(".draggable").each(function () { var elem = $(this), id = … -
problem with django url dispatcher , unable to resolve the url
i got latest django installed and working through hello world tutorial i got problem with getting url dispatcher working i got configured as follow in django_web/urls.py i got urlpatterns = [ path('TEST1', include('newpage.urls')), #path('admin/', admin.site.urls), ] in newpage/urls.py i got urlpatterns = [ path('', views.index, name='index'), path('TEST' ,views.index2, name='cokolwiek'), ] if i hit localhost:8000/TEST1 - works fine if i hit localhost:8000/TEST1/TEST - does not work i got followin message Using the URLconf defined in django_web.urls, Django tried these URL patterns, in this order: TEST1 [name='index'] TEST1 TEST [name='cokolwiek'] The current path, TEST1/TEST, didn't match any of these. how the hell is that not working -
Django: same Form inside for loop for different posts doesn't save state when other is applied to
I am trying to have this html gallery to show a for loop of posts, and inside each post is a form to fill out if they want to apply, I am passing the id through to the view from the template but when I submit one form, and then another, the first form doesn't show the success message anymore. So I can bounce between the same two posts and be able to apply to both infinity because the state resets each time. I need to make it to where it tracks the state of what's been applied to on the page without reloading the page. function submitMore(id) { $('#application-form-el'+id).submit(function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: '/contact/career-applicant/', data: $('#application-form-el'+id).serialize(), success: function(data) { console.log(data.form_html) $('#plugin-wrapper-{{ section.id }}').html(data.form_html); }, error: function(data) { alert(data.form_html); }, }); e.preventDefault(); // avoid to execute the actual submit of the form. }); $('select').chosen({ disable_search_threshold: 20 }); } Here is the view method def view_career_applicant(request): success = False id = 0 json_data = {} career_thank_you = '' career_form = ApplicationForm(request.POST, request.FILES) # TODO: need to check id for submitting correct success message if career_form.is_valid(): job = Career_posting.objects.get(pk=request.POST['post_id']) # <--- post_id to connect to form. cleaned_data = career_form.cleaned_data applicant … -
django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known
Below is my docker-compose.yml code. version: '3.8' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:11 volumes: - postgres_data:/var/lib/postgresql/data/ environment: POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: testpassword volumes: postgres_data: Below is my Dockerfile code: # Pull base image FROM python:3.8 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ Upon runnning "docker compose up" in command, I receive the following message, ERROR: for db Cannot create container for service db: Duplicate mount point: /var/lib/postgresql/data ERROR: Encountered errors while bringing up the project. -
Wagtail Multi-sites vs Apache Virtual Hosts
I've been to this site countless times but never made an account. I'm working on my first big project, so, first question: I intend to make a few websites that will be sharing the same droplet instance from hosting provider (DO). Wagtail offers multiple-sites on a single codebase. It lets you manage all sites from a single dashboard. Apache lets you create multiple domains/individual websites - known as 'virtual hosts' - and directs the user to the specific directory where the requested website is located. The websites I'm working on will share a single database to a certain degree (one of the sites will act as checkout page for some of the other sites, for example, where cart contents are retrieved via api/jason (I don't know yet)) Wagtail seems to be the best choice but I want to make sure Apache isn't required regardless of how I solve this problem (ex: if DO requires apache to be able to serve my websites as opposed to directly serving from django, for example) tvesday -
Send activation email to Admin/Superuser on user signup in Django
I am trying to send an activation email to my inbox when a user signs up so I can choose whether to accept the user or not. Currently I have a sitewide permission that I just add to each user I want to allow but thought there might be a more efficient and cleaner method.