Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
For angular-django webapp. How to setup cloudfront with s3 and beanstalk
I have an angular app for the frontend and Django for my backend. I am using beanstalk to deploy my Django app. What is the best way to make use of s3, CloudFront, route53, and beanstalk? angular hosting on s3 with Django being used for APIs angular in Django angular hosting on s3 with CloudFront while Django being used for APIs. Here 3rd method is much faster than the other two, I used the s3 bucket for hosting and directed cloudfront to s3 and then made a domain alias in route53 to CloudFront. it is working fine, but how to direct APIs to Django which is in the beanstalk? -
DeleteView not working with Ajax and Bootbox in Django
I'm using Bootbox along with Ajax to delete a listing in my app which is calling a DeleteView but after I confirm the deletion, nothing changes. View.py class FileDelete(DeleteView): model = Uploaded success_url = reverse_lazy('index') template_name = 'FileManagement/delete_file.html' Script <script> $(".delete-file").click(function () { var button = $(this); var id = button.attr("data-id"); console.log(id); bootbox.confirm("Are you sure you want to delete this file?", function (result) { if (result) { $.ajax({ method: "GET", url: "delete/" + id, success: function(){ } }); } }); }); </script> Urls.py url(r'^delete/(?P<pk>\d+)/$', views.FileDelete.as_view(), name="delete_file") I haven't finished the success part but it's still not deleting from the database. -
django operational error:attempt to writw a read only database
Request Method: POST Request URL: http://127.0.0.1:8000/basic_app/register/ Django Version: 3.0.8 Exception Type: OperationalError Exception Value: attempt to write a readonly database Exception Location: C:\Users\Shobit\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 396 Python Executable: C:\Users\Shobit\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.8 Python Path: ['E:\DjangoProject1\learning_users', 'C:\Users\Shobit\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\Shobit\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\Shobit\AppData\Local\Programs\Python\Python37-32\lib', 'C:\Users\Shobit\AppData\Local\Programs\Python\Python37-32', 'C:\Users\Shobit\AppData\Local\Programs\Python\Python37-32\lib\site-packages'] Server time: Sun, 13 Sep 2020 16:04:41 +0000 -
I have a problem with python manage.py runserver
I am new with Django.. I flowed the steps in the main website I had installed pip, django and python . I had done everything but when I use the manage.py runserver I have an error and it wouldn't workenter image description here -
How to override Django many to many field add() and remove() methods
I am trying to set up a Facebook-like activity notification system using Django-Activity-Stream. The library provides a special action signal for creating the actions. According to the documentation, to trigger this action, You can do it through custom forms or by overriding predefined model methods, such as Model.save(). The logic is to simply import the action signal and send it with your actor, verb, target, and any other important arguments. For example, action.send(request.user, verb='reached level 10') However, I have an intermediate through model from which the action signal has to be sent. Since Model.save() method is not called when M2M add() or remove() methods are instead used, I want to know if there is any way to override those add() and remove() methods. I have thought about using M2M changed signals but soon realized that I wouldn't be able to easily access request.user in M2M changed signals. (I need to always know who request.user is to generate any useful activity notifications). I am concerned that accessing a user instance in a signal (by creating a separate middleware to store request.user in a thread, for example) may be costly and unsafe. If it is a reliable option, please tell me. -
Nested for in Django template with dynamic key
I have two query set results group = [{'id': 1, 'group1'}, {'id': 1, 'group2'}] sub_groups = [{1: [{'id': 1, 'sub_group1'}, {'id': 2, 'sub_group2'}], {2: [{'id': 3, 'sub_group3'}, {'id': 4, 'sub_group4'}] I need to show group and its sub group in template. So, I am looping through the groups and then I need to loop through sub_groups. I can't able to access the sub_groups by group id. Getting Could not parse the remainder: '[group.id]' from sub_groups[group.id]' <ul class="list-group"> {% for group in groups %} <li class="list-group-item">{{group.name}}</li> <ul> {% for sub_group in sub_groups[group.id] %} <li class="list-group-item">{{sub_group.name}}</li> {% endfor %} </ul> {% endfor %}