Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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." -
I am trying to host in AWS. This line not working for me "sudo ln /etc/nginx/sites-available/django.conf /etc/nginx/sites-enabled/"
If i run sudo ln /etc/nginx/sites-available/django.conf /etc/nginx/sites-enabled/ It shows ln: failed to create hard link '/etc/nginx/sites-enabled/django.conf': File exists If i run sudo nginx -t It shows nginx: [emerg] open() "/etc/nginx/sites-enabled/example.conf" failed (2: No such file or directory) in /etc/nginx/nginx.conf:62 Not understanding the problem. Please help. -
Django login keeps returning invalid login user details
I'm new to Django and trying to create a simple user registration and login page. The login page keeps returning invalid user login details according to the code but the details are correct. -
IngerityError when Posting textarea content in django
I'm working on a simple project that requires a candidate to enter a description of his/herself. Since this requires lots of text, I use models.TextField() in models.py file and <textarea> tag in html. In models.py class Candidate(Person, models.Model): #Other fields description = models.TextField() def __str__(self): return self.name In Html <!---some stuff up--> <label for="candidate_description">Describe yourself</label> <textarea id="candidate_description" placeholder="Description..."></textarea> <!---some stuff below--> views.py file def regCandidate(request): if request.method == 'POST': candidate = Candidate( description=request.POST.get('candidate_description'), ) candidate.save() return render(request, 'Election/registerCandidate.html', {}) When I run the server and try to submit I get a IntegerityError. I have did some done some research and found out the error is occurs when django receives a null value when it is required. I'm a beginner at django and I'm using custom forms. Can anyone help explain why django is receiving a None and how to fix it. -
Ignoring validator errors django
For my code, I would like to introduce a set of custom warning messages based on some logical arguments on the data being posted. However, when using the django warning messages, the posted data through API gets saved into the database. I was wondering if it is possible to create a custom validator in the serializers that will respond with a post error message and be able to incorporate a parameter that will allow the user to bypass the error if they choose to do so? Almost all the research I have done points towards bad practice in bypassing validator errors and also requires going into the code to ignore it. Since these are custom errors that will not pose any data inconsistencies for the database, I would like to know more. -
I have created a Bio application in django.. how could i stop user to create duplicate Bio or remove create Bio button
Here is my model class Bio(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,default="",null=True) name = models.CharField(max_length=200,null=True,blank=True) text = models.TextField(max_length=280) facebook = models.URLField(name='facebook',default=None,null=True) linkdin = models.URLField(name='linkdin',default=None,null=True) picture = models.ImageField(upload_to="bios/images", default="") def __str__(self): return self.name here is my views class BioCreateView(LoginRequiredMixin, View): template_name = 'bios/bio_form.html' form_class = BioForm success_url = reverse_lazy('bios:all') def get(self, request, pk=None) : form = BioForm() ctx = { 'form': form } return render(request, self.template_name, ctx) def post(self, request, pk=None) : form = BioForm(request.POST, request.FILES or None) if not form.is_valid() : ctx = {'form' : form} return render(request, self.template_name, ctx) here is my nav bar pic This the pic of Nav bar How can I stop the user to create duplicate Bio or remove that create bio button I already assigned an owner to that bio -
AttributeError: 'MetaDict' object has no attribute 'private_fields'
I am building a website in django. I am using Mongodb as a database. But I am getting an error "AttributeError: 'MetaDict' object has no attribute 'private_fields'" Whenever I run the server. Here is my code: model.py from django.db import models from mongoengine import * # # Create your models here. class User_Registration(Document): company_name=StringField(required=True,max_length=200) username=StringField(required=True,unique=True,max_length=15) password=StringField(required=True,unique=True,max_length=15) email=EmailField(required=True) forms.py from django import forms from .models import User_Registration class Registration_Form(forms.ModelForm): class Meta: model=User_Registration fields=('username','password','company_name','email') widgets={ 'company_name':forms.TextInput(attrs={'class':'form-control input-sm'}), 'username':forms.TextInput(attrs={'class':'form-control'}), 'password':forms.PasswordInput(attrs={'class':'form-control'}), 'email':forms.EmailInput(attrs={'class':'form-control'}), } admin.py from django.contrib import admin from .models import User_Registration # Register your models here. admin.register(User_Registration) -
AWS not showing images on Django website deployed on heroku
I am trying to show my media files on a Django website hosted on Heroku via Amazon AWS S3. Currently, my settings for the AWS is: AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = None AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400',} DEFAULT_FILE_STORAGE = 'register.storage_backends.MediaStorage' And in my storage_backends.py I have: from storages.backends.s3boto3 import S3Boto3Storage class MediaStorage(S3Boto3Storage): location = 'media' file_overwrite = False When I open my website and inspect the images I can even the url seems to be correct: https://mybucket.s3.amazonaws.com/media/defaults/user/default_u_i.png?AWSAccessKeyId=... However, I still cannot see the image and it shows me the default thumbnail. What am I doing wrong here? I have uploaded the files to my bucket and I have checked multiple times and they are in the correct directory. Thanks for all the help in advance! -
Save recorded audio file in django from javascript ajax
I am trying to record audio file using javascript and save in django backend. Here is ajax function function uploadAudio( blob ) { var reader = new FileReader(); reader.onload = function(event){ var fd = {}; fd["data"] = event.target.result; $.ajax({ type: 'POST', url: 'testing/', data: fd, dataType: 'text' }).done(function(data) { console.log(data); document.getElementById("response").innerHTML=data; alert(data); }); }; Here is the function in views.py file @csrf_exempt def test(request): if request.is_ajax(): print("Yes, AJAX!") print(request.DATA ) else: print("Not Ajax") return render(request,'testing.html',{'print':'message'}) How can i save the data as audio file