Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 = … -
Username profile page url error in Django
I prepared a profile page for users. When he clicks on the username, going to this page. example username: maxfactor url: domain.com/user/maxfactor But if the username contains utf-8 characters, I cannot access this user's profile page. Example username: MAXFÜKTOR or LÜLÜY or Küçükzgard So the problem is the characters ğüşİçöı... When I want to go to this username, the browser automatically makes a wrong redirection as follows. domain.com/de/user/MAXF%25c3%259cKTOR but interestingly, it works fine when I try it on localhost. same code and localhost working like this: domain.com/de/user/MAXFÜKTOR/ and it works ... Now a few methods come to mind, but I don't know how to do it. 1- This structure works on localhost, but it doesn't work on my "plesk linux" server. I'm not sure if I installed something missing on the server. 2- I can block these characters while registering a member. I hope I could explain the problem. You can find my codes below. url.py from django.urls import path from user import views app_name = "user" urlpatterns = [ path('login/', views.loginUser,name="login"), path('logout/', views.logoutUser,name="logout"), path('users/', views.view_votes_that_user, name='alluser'), #path('listusers/', views.filter_user, name='listusers'), kullanıcıları listelemek için path('signup/', views.signup, name="signup"), path('register/', views.registerUser, name="register"), path('update/', views.edit_profile, name='edit_profile'), path('activate/<uidb64>/<token>/', views.activate, name='activate'), path('<str:username>/', views.filter_user_core, name='filtercore'), ] views.py … -
How to make self.request.user return the user attached to token?
I am using token authentication in Django Rest Framework, and am passing a token into the header of my request. This token is attached to a user. How would I make it so that when 'self.request.user' is called, the user attached to the token in the request is returned? Failing this, more specifically I need some sort of way to change the following 'perform_create()' function in my view to instead set 'author' to the user attached to the token. perform_create() function currently: def perform_create(self, serializer): serializer.save(author = self.request.user) I need it so 'author' is set to the user attached to the token in the header. Any help would be much appreciated. Thanks EDIT: I am unable to use session based authentication in this implementation -
no such column: articles_article.body (Django)
I am keep getting this error please check it whats the issue with this -
Django with postgresql deployment on aws elastic beanstalk
I’ve been trying to deploy a django application with postgresql db on aws elastic beanstalk and i ran into many issues that i surfed and solved. Now the application uploads fine however the environment is still not green and I constantly am receiving 502 bad gateway nginx. I’ve checked nginx logs which say 111 connection refused etc. I’ve tried changed the port to 8001 from 8000 but didn’t work out. Somebody please guide me on how to deploy my application successfully. -
Use parameter as part of the url and how to handle it on django rest framework
Noob question here. I have an endpoint configure in this way router.register(r'company-to-audit', myapp_views.CompanyToAuditViewSet, base_name='company-to-audit') and on views.py class CompanyToAuditViewSet(viewsets.ModelViewSet): ... @list_route(methods=['get'], url_path=r'companies') def get_companies(self, request, **kwargs): # Lots of logic, return a json with Response return Response(serializer.data, status=status.HTTP_200_OK) Currently, to call this endpoint, I need 3 parameters. One of them is mandatory, City, and the other two are optional. so, the calls look like this http://localhost:8001/company-to-audit/companies/?city=Austin or http://localhost:8001/company-to-audit/companies/?city=Austin&codeID=3&regulation=oldest How can I modify this so instead of using those URL, could use the following ones: http://localhost:8001/company-to-audit/Austin or http://localhost:8001/company-to-audit/Austin/?codeID=3&regulation=oldest So, basically, transform the mandatory City in part of the URL. And also, currently, I obtaining the parameters with request.query_params, for example request.query_params.get('city') If it is possible to transform City in part of the URL, how can I capture the value? -
check if today is due date django
I have a model like this class Tasks(models.Model): title = models.CharField(max_length=100,null=True,blank=True) due_date_time= models.DateTimeField(default=timezone.now) As due date is a date and time field, how I can check if today is due date of this task , while I am saving time and date both -
how to bind two models in django
please help a beginner. I'm trying to build a poll app in Django and I want to change my admin view so that I can change and add questions and choices in the same page iv already tried to create a new model and bind the question and choice model together but didn't work please help me. this is my models.py inside my poll app and another problem I have is that I want to have different numbers of choices for different questions but I don't know how to write from django.db import models # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text class Bind(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') add_question =Question(question_text=question_text,pub_date=pub_date) choice_text_1= models.CharField(max_length=200,default='yes') votes_1= models.IntegerField(default=0) choice_text_2= models.CharField(max_length=200,default='yes') votes_2= models.IntegerField(default=0) choice_text_3= models.CharField(max_length=200,default='yes') votes_3= models.IntegerField(default=0) choice_text_4= models.CharField(max_length=200,default='yes') votes_4= models.IntegerField(default=0) add_choice1=Choice(choice_text=choice_text_1,votes=votes_1) add_choice2=Choice(choice_text=choice_text_2,votes=votes_2) add_choice3=Choice(choice_text=choice_text_3,votes=votes_3) add_choice4=Choice(choice_text=choice_text_4,votes=votes_4) def __str__(self): return self.question_text return self.choice_text and this is my admin panel id like to change it that I can add question with different number of choices and when I save I can find save question in question model pannel and … -
Django set_language request working but not changing language
I did makemessages, translated my strings that are {% translate 'my_string' %} in templates, and then compilemessages. But set_language does not seem to be working. My only translated language is es, en in the other hand is the native language of my project. navbar.html: <form action="{% url 'set_language' %}" method="POST" enctype="application/x-www-form-urlencoded"> {% csrf_token %} <input id="id_language" name="language" value="es" type="hidden"> <button type="submit" class="btn btn-outline-info mx-1"><i class="fas fa-language"></i></button> </form> urls.py: urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), # ... ] That's what I have. Then I put a pdb.set_trace() in one of my middlewares in order to check if the request is working as expected, and it does, when on debugger I type request.POST it has both the csrf_token and a language field with 'es' value. After response, the language is still set to en instead of es. What could be happening? Am I missing something? Thanks! -
How i can make a request in Django project [closed]
My website contains some workers, each worker has a specific job, I want to make the user click on the service request button to request the service from the desired worker and this worker can see this request in his profile models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) job = models.ForeignKey('Category', on_delete=models.CASCADE, blank=True, null=True) place = models.CharField(max_length=50) WORKSlug = models.SlugField(blank=True, null=True) def save(self, *args, **kwargs): self.WORKSlug = slugify(self.user) super(Profile, self).save(*args, **kwargs) class Request(models.Model): client_name = models.CharField(max_length=50) email = models.EmailField() address = models.CharField(max_length=50) phone = models.CharField(max_length=15) message = models.TextField() def __str__(self): return self.client_name forms.py class RequestForm(forms.ModelForm): class Meta: model = Request fields = ['client_name', 'email', 'phone', 'address', 'message']' views.py def make_request(request): if request.method == 'POST': form = RequestForm(request.POST) if form.is_valid(): form.save() else: form = RequestForm() return render(request, 'accounts/requests.html', {'form': form}) workers_list.html {% for worker in workers %} <div class="card mb-3 mx-auto" style="max-width: 540px; max-height: 300px;"> <div class="row no-gutters"> <div class="col-md-4"> {% if worker.photo %} <img src="{{worker.photo.url}}" style=" max-height: 300px;" class="card-img" alt="..."> {% else %} <img src="{% static 'img/default_img.png' %}" alt=""/> {% endif %} </div> <div class="col-md-8"> <div class="card-body"> <a href="{{ worker.get_absolute_url }}"><h5 class="card-title font-weight-bolder mx-auto">{{ worker}}</h5></a> <p class="card-text mx-auto">{{worker.job}}</p> <p class="card-text mx-auto"><small>{{worker.place}}</small></p> <a href="{% url 'accounts:make_request' %}" class="btn btn-info">Request Service</a> </div> … -
My first Django App - don't know how to create a homepage
I have been learning python for some time now and I want to make one of my small programs available to more people. I am learning how to make URLs for my project now and I cannot create a URL for a homepage. As I found in one of the courses for older django version, you should create a function in your urls.py file that looks like this: from django.http import HttpResponse def home(request): return HttpResponse('this is the test homepage') and pair it with some lines in views.py: path('^$', views.home) This doesn't work for me. I also tried to create a path like this: path('/', views.home) Please, help or direct me to up to date guides for django 3.1.1. -
How to automatically create an object for a model in Django, if it doesn't exist?
I have two models. One is for UserProfile and the other is for Company. class UserProfile(models.Model): company_name = models.ForeignKey(Company, on_delete = models.CASCADE, related_name = 'company') class Company(models.Model): name = models.CharField(max_length = 100) I am using Django Rest Framework for user creation. What I want to achieve is when I create a new user, I want to assign a company_name to that user. And if that company_name is not present in the db, then I want to create it on the go. But it is throwing an error. "Invalid hyperlink - No URL match."