Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to stop function and run other after x seconds in Django?
So basically I have a view which runs a function that is written in another file. Since I don't want the function running any longer than 25 seconds, is there any way for me to skip the function after it has ran for 25 seconds and just simply return the redirect reverse? Here is what my view looks like def radio(request): song_search = request.POST.get('search').capitalize() request.session['song'] = song_search if models.Genre.objects.filter(Song=song_search): song_query_createobject(request) else: song_query_createobject(request) song_finder(request) return redirect(reverse('songresult')) -
Django ValueError: The view cookbook.views.profile didn't return an HttpResponse object. It returned None instead
I've read through plenty of questions with this same error message but I could not find the same case as mine. Usually you would see if statement with no returns but this doesnt have if statements. error Traceback (most recent call last): File "C:\Users\locti\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\locti\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response raise ValueError( ValueError: The view cookbook.views.profile didn't return an HttpResponse object. It returned None instead. There are other views as well but I dont think they are related view.py def profile(request, name): try: user = User.objects.get(username=name) except User.DoesNotExist: return render(request, "cookbook/error.html") return render(request, "cookbook/profile.html", { "pageuser": user }) profile.html {% extends "cookbook/layout.html" %} {% block body %} <h2>{{ user.username }}</h2> {% endblock %} -
Randomly pick X objects with distinct names
The following attempt: Article.objects.filter(category__id="b5e20323-8cec-413a-b405-342b3809f9a4").distinct('title').order_by("?") Gives me: ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions I tried to drop to raw SQL. So I tried: SELECT * FROM (SELECT DISTINCT title from article WHERE category_id = '...') AS inner_distinct ORDER BY RANDOM() LIMIT 3 This works but I need to add an additional field to to the title. If I change my raw query to: SELECT * FROM (SELECT DISTINCT title, id from article WHERE category_id = '...') AS inner_distinct ORDER BY RANDOM() LIMIT 3 All of a sudden the DISTINCT keyword has no effect. How can I overcome this? -
Django table with query results and computed data
I am trying to list the last entry a user makes in a table along with the number of entries the user has made. The query I have so far gets me the last entry (there can only be one active at a time) data = Student.objects.filter(session=session, active=True) The objects are then sent over and displayed in a table {% for item in data %} <tr> <td>{{ item.name }}</td> <td>{{ item.category }}</td> <td align="center">{{ [count here]}}</td> </tr> {% endfor %} I would like the count for the number of times the user's name appears in the database in the same row as the object data itself. I would like the count displayed where "count here" is as above. -
why do I get "ModuleNotFoundError: No module named 'model-name'" error when I run my Django project after moving to python3.8.5?
I have a Django project which worked fine, but then I installed Python3.8.5, uninstalled the python27 I was using before, and installed Django 3.1.1 on my computer. Now when I run my project I get the error "ModuleNotFoundError: No module named 'model-name'". Seems like it can't find my models. How do I get my project to run properly? -
How to send POST request in order to add an object that has ForeignKey in Axios and Django Rest Framework
Code models.py class CustomUserManager(UserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('メールアドレスは必須項目です。') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password, **extra_fields) # Django提供のカスタムユーザーのFieldを決定 class User(AbstractUser): # AbstractUserでpasswordは定義済みのため、ここではpasswordを再定義しない(DBにはちゃんと保存される。) username = models.CharField(max_length=150, unique=True) email = models.EmailField(max_length=100, unique=True) profile = models.TextField(max_length=800, blank=True, null=True) icon = models.ImageField(blank=True, null=True) background = models.ImageField(blank=True, null=True) # AbstractUserはfirst_name,last_nameを保持しているため無効化 first_name = None last_name = None is_staff = models.BooleanField( ('staff status'), default=True, help_text=( '管理サイトへのアクセス権を持っているかどうか'), ) is_active = models.BooleanField( ('active'), default=True, help_text=( 'ユーザーがアクティブかどうか' ), ) is_superuser = models.BooleanField( ('superuser status'), default=True, help_text=( 'Designates that this user has all permissions without ' 'explicitly assigning them.' ), ) # createdAt, updatedAt は時系列順等に並べたいモデルに付与 created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = CustomUserManager() EMAIL_FIELD = 'email' USERNAME_FIELD = 'username' REQUIRED_FIELD = ["username", "email"] class Meta: db_table = "users" # ====== ======= ====== ====== ====== ====== ======= ======= class Bland(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Meta: db_table = "blands" # … -
compare fields in two different django models
I am trying fill a field (hours) in Employee model based on the aggregate of a field (time_worked) in Timesheet model. MODELS.PY class Employee(models.Model): ... user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='employees') hours = models.DurationField(null=True, blank=True) class Timesheet(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True,) time_worked = models.DurationField(null=True, blank=True) How do add up the time_worked in Timesheet model of only employee A and insert the results into hours column of Employee model for employee A? -
Django Static - Google Cloud Storage - CDN
I am still new with serving my Django static/media files to Google cloud storage. It's working now but I am not sure if this is right or is this enough already, do I still need to use CDN like Cloudfront or other similar services? I am really confused and any recommendation would be much appreciated. Below is my configuration. import os from google.oauth2 import service_account BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) GS_CREDENTIALS = service_account.Credentials.from_service_account_file( os.path.join(BASE_DIR, 'extras/google-storage.json') ) STATICFILES_STORAGE = 'extras.storage_backends.GoogleCloudStaticFileStorage' DEFAULT_FILE_STORAGE = 'extras.storage_backends.GoogleCloudMediaFileStorage' GS_PROJECT_ID = 'project_id' GS_STATIC_BUCKET_NAME = 'static_bucket' GS_MEDIA_BUCKET_NAME = 'media_bucket' STATIC_URL = 'https://storage.googleapis.com/{}/'.format(GS_STATIC_BUCKET_NAME) MEDIA_URL = 'https://storage.googleapis.com/{}/'.format(GS_MEDIA_BUCKET_NAME) GS_DEFAULT_ACL = 'publicRead' I am using the following: Django 2.2 Python 3.7 Thanks you so much! -
select serial number from the list given for user in django
i wrote a Django app but it's not complete. it's a kinda CRM app for Controlling my customers. how does it work? in the client section, I enter the customer's name, phone number, email, name of the app that he/she bought, and the SERIAL NUMBER image_one when I create a new user I have to manually type the serial number image_two but I don't want that. WHAT I Want?? in the product section, after I enter the product's name, I want a place to enter 1000 serial numbers ( serial numbers are generated in other app and that app gave me a text file with thousands of serial numbers). I want something like this in Django App: image_tree now the final part : in the client section, when I chose the product name (One product or more), I want a serial number picked up from the list and never use for another user. image_foure I know my English is bad. sorry for that :( please help any idea how I can do this? -
Python script to django html output
I want to put python script output to HTML using Django with a button. When the user clicks the button again and it changes the random number again. import random num = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] print(random.choice(num)) -
when should you employ the POST method over the GET method for submitting data from a form?
when should you employ the POST method over the GET method for submitting data from a form? 1-when you want the data to be cached 2- when efficiency is important 3- when the data in the form may be sensitive 4- when you want to use your browser to help with dubugging and explain the answer please -
Django Python POST Method not writing to database
I now have an issue with my POST Method not writing to the database and not showing in Admin site. the views.py file works until it gets to the 'if form.is_valid()' but doesn't go any further than that. What am I doing wrong? Please help, I've spent time trying to search for the answer but to no avail. code as below urls.py path('weekly/', user_views.weekly, name='weekly'), views.py def weekly(request): if request.method == 'POST': form = SubscriptionForm(request.POST) print('I got this far 3!') if form.is_valid(): form.save() messages.success(request, 'Thank you for your payment!') return redirect('classes') else: return render(request, 'clubex/weekly.html', {'title': '1 Week Free'}) else: return render(request, 'clubex/weekly.html', {'title': '1 Week Free'}) models.py (do these names have to match the 'id' in the HTML doc?) class Subscription(models.Model): firstName = models.CharField(max_length=100) lastName = models.CharField(max_length=100) username = models.CharField(max_length=100) sub_type = models.CharField(max_length=50) email = models.EmailField(max_length=100) address = models.CharField(max_length=100) address2 = models.CharField(max_length=100) state = models.CharField(max_length=100) country = models.CharField(max_length=100) zip = models.CharField(max_length=10) same_address = models.BooleanField() save_info = models.BooleanField() credit = models.BooleanField() debit = models.BooleanField() paypal = models.BooleanField() cc_name = models.CharField(max_length=100) cc_number = models.CharField(max_length=20) cc_expiration = models.CharField(max_length=10) cc_cvv = models.IntegerField() def __str__(self): return f'{self.firstName} {self.lastName} {self.sub_type}' forms.py (do these names have to match the 'id' in the HTML doc?) class SubscriptionForm(forms.ModelForm): … -
How to save variables into mysql database in django
so l have pulled the data from a movie website and l saved it into variables for example title but now I'm struggling to send this data to MySQL DB def index(request): response = requests.get( 'https://fmovies.to/api/list_movies.json', params={'limit':'20'}, ) json_response = response.json() movies = json_response['data']['movies'] #title = movies[0]['title'] #movie_url = movies[0]['url'] #description = movies[0]['description_full'] #movie_torrent_link = movies[0]['torrents'][0]['url'] #cover_image = movies[0]['medium_cover_image'] for value in movies: title = value['title'] movie_url = value['url'] description = value['description_full'] movie_torrent_link = value['torrents'][0]['url'] image = value['medium_cover_image'] rating = value['rating'] genre = value['genres'] runtime = value['runtime'] year_of_production = value['year'] slug = value['slug'] print(image) print(rating) print(runtime) print(year_of_production) print(slug) return render(request, 'index.html',{'title':title}) -
How to Login/Logout a User Django Rest
I am using DjangoRestFramework-SimpleJWT, The user is able to obtain a JSONWebToken. My Question is: How to create a Login and Logout API, were the user is able to Login/Logout? Thanks. -
compress and minifiying files failed at {% compress css %} in base.html file i'm using django, python. OS : Windows 8.1
I am developing a django-based application under windows 8.1 I install the following packages after activating my virtual environment: Django == 3.0.8 libsass == 0.20.0 django-libsass == 0.8 ... I strictly followed the modification of my setting.py to no avail. I may have a problem with the path of the sass package: ... my base.html template : <!DOCTYPE html> {% load static %} {% load compress %} {% load thumbnail %} <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{{APPLICATION_NAME}}</title> <link href="https://fonts.googleapis.com/css?family=Quicksand:300,400,500,700" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap- datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css" />` {% compress css %} <link href="{% static 'css/main.scss' %}" type="text/x-scss" rel="stylesheet"> <link href="{% static 'css/mention.scss' %}" type="text/x-scss" rel="stylesheet"> {% endcompress %} when I run python manage.py runserver and access http://127.0.0.1:8000 I get the blocking error: During handling of the above exception (No module named 'sass {infile} {outfile}'), another exception occurred: and above : Error during template rendering In template E:\Developpement\Langages\python\django\crm\templates\base.html, error at line 16 ({% compress css %}) thank you for unblocking me -
Live Console data to webpage using django
I'm creating a website using Django where I need to show the live console data of the pycharm to the webpage. How can I do that? -
Prepopulate form with it's instance if invalid using CreateView Django
I use generic CreateView to create a User instance. class SignUp(CreateView): template_name = 'reg.html' form_class = SignUpForm success_url = reverse_lazy('login') def form_valid(self, form): raw_password = form.instance.password form.instance.set_password(raw_password) return super().form_valid(form) How would I efficiently prepopulate form with it's own instance if any form error occurs? Without rewriting post methods or smth if possible. Thanks. -
Django forms - How to add class/id to class?
I think the question is pretty simple to understand, so I guess there is no need to copy and paste the code from models/forms. Here is how django renders my form: <div id="div_id_name" class="form-group"> <label for="id_name" class=""> Name: </label> <div class=""> <input type="text" name="name" maxlength="200" class="textinput textInput form-control" id="id_name"> </div> </div> How can I add a class or an id to the div (and not to the input) using Django widgets? I need something like this: <div id="div_id_name" class=" **myclass** form-group"> <label for="id_name" class=""> Thank you very much. -
Make object assigned to class variable aware of parent
I am trying to implement something similar to Django's model/manager pattern, but I can't figure out how Django makes the manager aware of the model it is managing. For example, I want to implement something as follows: class Manager: def create(self): # STUCK HERE return class FooModel: field1 = None field2 = None objects = Manager() class BarModel: field1 = None field2 = None objects = Manager() foo = FooModel.objects.create(...) bar = BarModel.objects.create(...) The idea is that the create() method will perform some database operation and return an instance of the class with the objects variable. Similar to how Django works when you call Model.objects.create(). I've looked through the Django code on GitHub but I'm having difficulty finding how this is acheived. How can I make the Manager instance aware of the object it is assigned to via the objects class variable? -
OperationalError at /admin/blog/blog/add/
I am getting the same error. Tried to fix it by using migrations commands everything I did but when I add a blog in Blog table and doesn't add. Please see the screenshot for your reference. OperationalError at /admin/blog/blog/add/ -
Django RSS feed: any way to cache M2M relationship to display in item_title?
Example models Author and Book are linked via M2M. I've found a way to cache the relationship in items, but that doesn't really help because I need to display some info about Author in the Book feed: def item_title(self, item): return f"{item.author_set.first().name} released {item.title}" Any way to somehow cache the M2M relationship here? -
What does the _, do in this context. (Python / Django)
I've been racking my brain for the past 30 minutes trying to figure out what underscore and comma do in the following code, right before declaring filenames: def list_entries(): """ Returns a list of all names of encyclopedia entries. """ _,filenames = default_storage.listdir("entries") return list(sorted(re.sub(r"\.md$", "", filename) for filename in filenames if (filename.endswith(".md") and filename != ("EntryNotFound.md")))) I know that an underscore can be used as a throwaway variable or to store the last variable called. But I cant see how that makes sense here. -
Django Form Not Re-Rendering On Page Refresh
I'm building a URL shorter in Django. I have a Django form to submit URLs, which has a default field with a random extension. When I finish submitting a URL to shorten, i'm returning a new form to the template, so that way you can submit a new URL. return render(request, 'bitly/index.html', { "form": NewBitForm() }) But when it renders, it leaves the old extension instead of rendering a new one, even after refreshing the page. How can I make it so that when I call NewBitForm(), it returns a different extension in the form? Template: <div class="card mb-3"> <div class="card-body"> <form action="{% url 'bitly:index' %}" method="post"> {{ form }} <input type="submit" class="btn btn-primary btn-sm form-control"> {% csrf_token %} </form> </div> </div> Form Class: ALPHA_NUMERIC_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890' class NewBitForm(forms.Form): def get_string(k): global ALPHA_NUMERIC_CHARS return ''.join(random.choice(ALPHA_NUMERIC_CHARS) for i in range(k)) url = forms.CharField(label="URL to shorten") url.widget.attrs.update({ 'class': 'card mb-3 form-control', 'spellcheck': 'false' }) extension = forms.CharField(label="Effective Extension") extension.widget.attrs.update({ 'id': 'extension-field', 'class': 'card mb-3 form-control', 'spellcheck': 'false', 'value': get_string(5) }) -
Django/Python. QuerySet data converted in objects list converts str/int values in Tuple
I have very strange problem in very simply operation. models.py NbProducts(models.Model): brand = models.CharField(max_length=45, blank=True, null=True) name = models.CharField(max_length=45, blank=True, null=True) cluster = models.CharField(max_length=45, blank=True, null=True) target_market = models.CharField(max_length=10, blank=True, null=True) cpu_vendor = models.CharField(max_length=45, blank=True, null=True) base_platform = models.CharField(max_length=45, blank=True, null=True) gpu_list = models.CharField(max_length=45, blank=True, null=True) screen_size = models.CharField(max_length=45, blank=True, null=True) screen_resulution_list = models.CharField(max_length=45, blank=True, null=True) touchscreen = models.CharField(max_length=45, blank=True, null=True) views.py list_Products = NbProducts.objects.\ filter(id__in=products_for_execute).\ values('brand', 'name', 'id') # list_Products: #<QuerySet [{'brand': 'Acer', 'name': 'Aspire R7-372T', 'id': 2713}, #{'brand': 'Acer', 'name': 'Aspire S7-393', 'id': 2716}, #{'brand': 'Acer', 'name': 'Swift SF514-51', 'id': 2743},.... class FProducts(object): def __init__(self, id, brand, name): self.id = str(id), self.brand = str(brand), self.name = str(name) print(self.id, self.brand, self.name) fproducts = list() for i in list(list_Products): fproducts.append(FProducts(id=i['id'], brand=i['brand'], name=i['name'])) >> {'2713',) ('Acer',) 'Aspire R7-372T' >> {'2716',) ('Acer',) 'Aspire S7-393' >> {'2743',) ('Acer',) 'Swift SF514-51' So. Without any commands it put two of argements - 'id' & 'brand' to Tuple. argument 'Name' - all right, just string. I dont need Tuple. And I dont understend what`s matter. Additionaly i put in init this. self.id = self.id[0] self.brand = self.brand[0] Ok, it helped, app is work. But I can`t see the source of the problem. Does it the proplem … -
TypeError in Django: save() got an unexpected keyword argument 'force_insert'
It's about a blog project in a course, that as it seems it works for many other students, but not for me. So I would like to see what is going wrong with my code. The error message is: TypeError at /register/ save() got an unexpected keyword argument 'force_insert' The relative with the issue files are the following: users/views.py: (in the 4th raw of register function is the save() method that fails) from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f"Your account has been created! You are now able to log in") return redirect('login') else: form = UserRegisterForm() return render(request, 'blog/register.html', {'form': form}) @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f"Your account has been updated!") return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'blog/profile.html', context) users/models.py: from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = …