Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Update specific part of template by button click
I have a text field <input type="text" value="This is a test." name="mytextbox" size="10"/> and separated from that a button <button type = "button" class="btn btn-primary"> <font size="1">Run</font> </button> that should update a list and update the value of the text field itself. Sometimes forms are used in this context, but I would have to wrap the forms tag around the whole template when the input and button are separated on the screen. Since I am relatively new to Django, I would like to know the best strategy to solve the problem. a) Reload the complete page template with changed arguments/context b) Create a html template of the specific part that extends the main template and only try to render/update this one. c) Do something smarter. There are some answers in a (much older) post from 8 years ago but I am interested in the state-of-the-art solution. -
My login.view fails and say didnt return a http response object
I am having this trouble to make a login form for 2 different types of user. Since I implemented this code, my renderer is failing. def Login_View(request): context = {} user = request.user if request.method == 'POST': form = AuthencationForm(request.POST) if form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(request,email=email, password=password) if user is not None: if user.is_active: login(request, user) type_user = user.user_type if user.is_authenticated and type_user == "1": return redirect('requests' % request.user.FKLab_User.id) elif user.is_authenticated and type_user == "2": return redirect('distributor-view' % request.user.FKDistrib_User.id) return messages.info(request,"Your account is disabled.") return messages.info(request,"Username and password are incorrect.") else: form = AuthencationForm() return render(request, 'accounts/login.html', {'form': form}) This login view came from the user model, that is: class CustomUser(AbstractBaseUser, PermissionsMixin): USER_TYPE_CHOICES =( (1, 'LAB_USER'), (2, 'DISTRIB_USER') ) FKLab_User = models.ForeignKey('HospitalViewRoleForUsers', on_delete=models.PROTECT, null=True, blank= True) FKDistrib_User = models.ForeignKey('distrib_api.Distributor', on_delete=models.SET_NULL, null=True, blank= True) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES, default=0, null=True, blank=True) email = models.EmailField(_('email address'), unique=True) name = models.CharField(max_length=255, blank=True, null=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) telephone = models.CharField(max_length=15, blank=True, null=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() class Meta: db_table = 'customuser' indexes = [ models.Index(fields=['name'], name='first_name_idx'), ] def __str__(self): return self.email I want to make a webapp where theres … -
Issue with djongo EmbeddedFields
I'm using Djongo with Django and MongoDB, however I am stuck at the following issue when trying to implement an embedded field ValueError: Value: [OrderedDict([('userID', 1), ('username', 'o'), ('admin', False)])] must be an instance of <class 'dict'> These are the models concerned: from djongo import models class groupMembership(models.Model): membershipID = models.ObjectIdField() userID = models.IntegerField() username = models.CharField(max_length=50) admin = models.BooleanField(default=False) class group(models.Model): groupID = models.ObjectIdField() title = models.CharField(max_length=100) createdDate = models.DateField() members = models.EmbeddedField(model_container = groupMembership, null = True) Here are the serializers I am using: class groupMembershipSerializer(serializers.ModelSerializer): class Meta: model=groupMembership fields=('membershipID', 'userID', 'username', 'admin') class groupSerializer(serializers.ModelSerializer): members = groupMembershipSerializer(many = True) class Meta: model=group fields=('groupID','title','createdDate','members') Error is thrown when I try to send in the following POST request: { "title" : "l", "createdDate" : "2021-07-07", "members" : [{ "userID" : "1", "username": "o", "admin" : "False" } ] } Any help is appreciated! -
Does this many-to-many relationship make sense?
I'm writing a django app and I have the following models below, however I am unsure about the relatinonships of order_id and product_id in DetailedOrder and customer_id in Demand model. In the DetailedOrder model, there can be multiple order_id (O0001) if the customer orders multiple product_id. Then the order_id can be used in the Order model to find who the customer was. Or should the product_id in the DetailedOrder be a many to many relationship because there can be multiple products for 1 order_id - i think this makes more sense. Also by this logic, does this mean customer_id in the Ordermodel should be a many-to-many relationship because there can be multiple customer_ids to multiple order_ids? Any advice is appreciated! class Customer(models.Model): customer_id = models.CharField(primary_key=True, max_length=150) customer_name = models.CharField(max_length=150, null=True) class Product(models.Model): product_id = models.CharField(primary_key=True, max_length=100) product_name = models.CharField(max_length=150) class Order(models.Model): order_id = models.CharField(primary_key=True, max_length=100) customer_id = models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL) class DetailedOrder(models.Model): order_id = models.ForeignKey(Demand, null=True, on_delete= models.SET_NULL) product_id = models.ForeignKey(Product, null=True, on_delete= models.SET_NULL) quantity = models.IntegerField() -
Skip Django Rest Throttling Counter
How can I prevent Django rest throttling count the request when the user request is invalid or the server failed to complete the process? For example, I need params from the user, but when the user does not give the params, Django rest throttling still counts it. Is there any solution to skipping the throttling counter when the request is not successful? Example class OncePerHourAnonThrottle(AnonRateThrottle): rate = "1/hour" class Autoliker(APIView): throttle_classes = [OncePerHourAnonThrottle] def get(self, request): content = {"status": "get"} return Response(content) def post(self, request): post_url = request.POST.get("url", None) print(post_url) content = {"status": "post"} return Response(content) def throttled(self, request, wait): raise Throttled( detail={ "message": "request limit exceeded", "availableIn": f"{wait} seconds", "throttleType": "type", } ) -
Django Model for associating Favourites
Use case: Want to let an admin create favourite relationships between users. To do this, I am creating a model called Favourites. class Favourite(models.Model): user = models.ForeignKey(to=CustomUser, on_delete=models.CASCADE) otheruser = models.IntegerField() However, both user and otherusers are both objects in CustomUsers. In the admin console, when adding a favourite I get a list of users, but I do not get a list of other users obviously. What model field can I use so that when adding a favourite I get a list of users, and when choosing the otheruser that is also a list of users? -
I am taking Cs50 lecture3 Django in which there is a problem that not works the name variable we assigned to each path in urls.py, and create a link
this is my django+html code {% extends "tasks/layout.html" %} {% block body %} <h1>Tasks Lists</h1> <a href="[% url 'tasks:add' %]"> Add a task</a> {% endblock %} this is where i use varriable name add and link it to another page. Urls.py from django.urls import path from . import views app_name = "tasks" urlpatterns=[ path("",views.index,name="index"), path("add",views.add,name="add") ] this is where i use the varriable name "add". -
AttributeError: 'bool' object has no attribute 'rsplit' error on Django 2.x 3.x 4.x with postgres database
This error may point to a model but it is mainly an incompatibility with Postgres package. In a new postgres databases it may include following error when doing initial migration: "AssertionError: database connection isn't set to UTC" I got same error with Python 3.8 & 3.10 + Django 3 & 4. -
How do I construct a Complex Django Query where sometimes the conditions are ALL
Let's say I have three Choicefields and I know their values in my view. For example: fpriority = filtform["priority"].value() fstatus = filtform["status"].value() fassigned = filtform["assigned"].value() The values of each will be an integer (for example, 1-3) that relates to the appropriate column in the Table. So my first thoughts on Query is this: tasks = Task.objects.filter(Q(priority=fpriority) & Q( status=fstatus) & Q(assigned_to=fassigned)) The problem I have though, is that I also want a choice for all. So lets say I include zero (0) in each ChoiceField to signify ALL So now each of the above Q conditions must include the possibility that the variable is 0 and therefore means ALL for that part of the condition. Any thoughts on a clean way to do this? -
Is there any method to join one level past a related_name?
I'm repeatedly running into a data situation that I feel django probably has a shortcut for, but I can't find it... I want to access a model one relationship beyond a queryset I selected via a related_name. It feels like there should be a one-liner for this, but the best I've figured out is: for p in team.players: do_whatever(p.user.email) Using select_related will precache the data, but won't actually give it to me in a usuable form. team.players.select_related('user') # still returns queryset of Players, not Users It just seems like there should be some way for me to get a query_set of the associated users via one call. Something like annotate: users = team.players.annotate('user') # doesn't work Is there any method that does what I'm looking for? Or is the "for - in" loop the only way to go? The basics of my classes (greatly simplified): class Team(models.Model): name = models.CharField() class Player(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="players") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="players") captain = models.BooleanField() Is there any one-liner or optimization beyond doing a select_related followed by a for-in? -
Github Actions implementation in project with test machine
Current architecture of our project is pretty simple: Multiple Github repos merge in Master and deploy to Server. But we want to add Testing to it. And currently I'm investigating Github Actions possibility. Is it possible to make this setup: Code getting merged to "Develop" branch and trigger Github Action Github Action push code to Test server and run all Unit Tests return test result, maybe as Email or something. If tests are successful Develop branch getting merged to Master. Is it possible to setup all of this just with Github Action or we will need to add Jenkins or Travis?? Thank you for your time. -
ERROR: ServiceError - Create environment operation is complete, but with errors. For more information, see troubleshooting documentation
I am trying to deploy Django app on AWS elasticbeanstalk and I am following the official document carefully https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html .but still I am getting an error when I run eb create django-env , which first error saying Instance deployment failed to install application dependencies. The deployment failed. the bunch of errors follow(see the screenshot) my folder structure seems alright and I have the requirements.txt in the root directory with all the dependency specified I am using: Django==4.0.3 my machine is Mac M1 I have installed awsebcli on the venv and globally just on case -
File handling in django
I am trying to access the csv file which i passed in my form and saved in media directory. I am able to access the file if i manually enter the path(localhost://8000/media/1.csv) but it throws an error saying "No such file or directory" when accessing from open function. def home(request): print("Rendering Home...") if request.method == "POST": uploaded_file = request.FILES['csvFile'] fs = FileSystemStorage() name = fs.save(uploaded_file.name,uploaded_file) url = fs.url(name) csv_fp = open(f'{url}', 'r') //ERROR:"No such file or dir media/1.csv" reader = csv.DictReader(csv_fp) headers = [col for col in reader.fieldnames] out = [row for row in reader] return render(request, 'home.html', {'data' : out, 'headers' : headers}) return render(request,"home.html") -
How to host Django + Selenium Scrapper on ubuntu properly or how to host scrapper in the cloud?
basically I am facing a problem regarding my Django and selenium website. My Django function contains selenium code to go and scrape details sent by my front end. It works perfectly fine on my PC. The scrapper must run until the end of the page and it usually takes hours before reaching the end. It is basically calling my API endpoint which starts scraping and then returns "done" as a response. Now I want to host it on ubuntu server on AWS EC2 instance. Which I did and works perfectly fine. But as I said the scrape works for hours, and till the end of the page it doesn't return anything in response and the request stays alive for hours, which as you know is against the security feature of Nginx and the request dies with a 503 error. The default time for Nginx request is I think 30 seconds or something but I tried changing it but no luck. Is there a different way of hosting scrappers? This scrapper will be used by one person but I am thinking of making it public so more people will use it in the future. That's why I would like to know … -
Why the html custom form is not working django
I have a contact page with a simple form. Here is views.py: def contact_view(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, settings.ADMIN_EMAILS) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "base/contact.html", {'form': form}) def success_view(request): return HttpResponse('Success! Thank you for your message.') this is contact.html: {% block content%} <main class="page contact-page"> <section class="portfolio-block contact"> <div class="container"> <div class="heading"> <h2>Contact me</h2> </div> <form method="post"> {% csrf_token %} <div class="mb-3"><label class="form-label" for="name">Your Name</label><input class="form-control item" type="text" id="name"></div> <div class="mb-3"><label class="form-label" for="subject">Subject</label><input class="form-control item" type="text" id="subject"></div> <div class="mb-3"><label class="form-label" for="email">Email</label><input class="form-control item" type="email" id="email"></div> <div class="mb-3"><label class="form-label" for="message">Message</label><textarea class="form-control item" id="message"></textarea></div> <div class="mb-3"><button class="btn btn-primary btn-lg d-block w-100" type="submit" value="submit">Submit Form</button></div> </form> </div> </section> </main> {% endblock %} When I use form.as_p it works very well but when I use this template it is not working it only shows in the terminal that a post request was made. -
GeoDjango - set initial value (location) for PointField in form (OSMWidget)
I want to create a form to choose a location with PointField. I use OSMWidget as a widget, and I want the initial location to be defined by user's ip. I use the following standard method of CreateView for it: def get_initial(self): init = super().get_initial() try: (lat, lon) = utils.get_user_coords(self.request) print(lat, lon) init['residence_location'] = Point(lon, lat) except geoip2.errors.AddressNotFoundError: pass print(init) return init However, it locates the map at (0,0) (i guess? somewhere under Ghana) whatever the (lat, lon) is. I know it sees this data, because if I remove this function altogether, it locates the point at France (the default location per docs). Why it doesn't work? -
I can't install django-celery
When trying to install Django-celery on both desktop and laptop, these errors occur. After reading various forums and using various installation options, I was able to install Django-celery. At least that's what pip tells me. But when trying to import django-celery the following errors occur. Why do these errors occur and what do I need to do to fix them? I'm using Python 3.1. -
model relationship and Queries in Django not a clear
what does these lines of code mean in Django View: i couldn't find a details explanation, I came to Django from a Laravel background, so I can understand the models and relationships... thanks customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) -
installing channels redis in windows10 without errors
am trying to use Redis as the back store channel layer in Django but am getting installation errors when it comes to building the wheel for hiredis module. Am on Windows 10 and have just learned it is not supported in windows. what should I do so as to use RedischannelLayer backend settings in Django settings.py file -
No Reverse Match coming up with URL keyword
This seems like I must be missing something really simple. I'm trying to use the url command for a link. I keep getting a NoReverseMatch error. The code in the HTML looks like this: Batch Upload test I'm just learning this so I duplicated the link, one in a button and one as an url. If I take out the second line the HTML loads find and the button takes me to the correct page. When I add the second line I get the NoReverseMatch error. I have it added to the installed apps in the settings page but I would think if I had done this wrong the first button wouldn't work at all. If instead I link it to a name in the base module like this: test it works fine. Is there some place special I need to list the MyApp application in order for python to find it when using url? -
The model TokenProxy is already registered in app 'authtoken'
I am facing this problem with migrating in Django admin after I updated the app name 'rest_framework.authtoken' in django project settings. It gives me error The model TokenProxy is already registered in app 'authtoken'. I know I should have added this and migrate before creating super user but now I have already created the project and migrated lots of models and there is a data in it. Can help me how I can resolve this problem. I also tried to undo migrations with command python manage.py migrate books but it again does not recognize the word books. Please help me with this. Here is my apps in settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'traderskamp_app', 'rest_framework.authtoken', 'rest_framework', 'corsheaders', ] Here is the exact error: File "C:\Python39\lib\site-packages\rest_framework\authtoken\admin.py", line 51, in admin.site.register(TokenProxy, TokenAdmin) File "C:\Users\Anwar\AppData\Roaming\Python\Python39\site-packages\django\contrib\admin\sites.py", line 126, in register raise AlreadyRegistered(msg) django.contrib.admin.sites.AlreadyRegistered: The model TokenProxy is already registered in app 'authtoken'. -
Does changing Django database backend require code modification?
I'm currently using sqlite3 as Django database backend. However I'm looking forward to use MySQL in the future. Does changing database backend require source code modifications such as models.py, forms.py, views.py..etc.(other than files that link Django to DB such as settings.py) My guess(not sure) : As my codes interacting with database backend are written in python scripts(not SQL) I guess no source code modification will be needed since it means Django automatically generates SQL querys with my python codes that match with current linked database backend. -
How to write a way to the file for django-upgrade whithout an error?
I have a Django project, that names 'dj_post', and I have 2 apps in it: 'dj_post' and 'testdb'. Then I wanted to use the django-upgrade library to get rid of problems with the code in file of main app urls.py I installed that library and then wrote the text below to the command promt: django-upgrade --target-version 4.0 dj_post/dj_post/urls.py And then I had this: ` Traceback (most recent call last): File "c:\users\денис\appdata\local\programs\python\python38\lib\runpy.py", line 194, in _ru n_module_as_main return _run_code(code, main_globals, None, File "c:\users\денис\appdata\local\programs\python\python38\lib\runpy.py", line 87, in _run _code exec(code, run_globals) File "C:\Users\Денис\AppData\Local\Programs\Python\Python38\Scripts\django-upgrade.exe\__ma in__.py", line 7, in <module> File "c:\users\денис\appdata\local\programs\python\python38\lib\site-packages\django_upgrad e\main.py", line 53, in main ret |= fix_file( File "c:\users\денис\appdata\local\programs\python\python38\lib\site-packages\django_upgrad e\main.py", line 70, in fix_file with open(filename, "rb") as fb: FileNotFoundError: [Errno 2] No such file or directory: 'dj_post/dj_post/urls.py' ` And tell me, actually, please, how to write the way to my project file correct. Thanks in advance. -
Django unable to serve static files from s3 bucket
I created a few models and pushed my project to a development server on an AWS EC2 instance. I used Django storages and followed the docs to configure my settings.py. when I run manage.py collectstatic the static files are pushed to the bucket successfully, but when I access the Django admin the CSS is missing. Can anyone help me fix this? My bucket permissions { "Version": "2012-10-17", "Id": "Policy1650117254896", "Statement": [ { "Sid": "Stmt1650117250899", "Effect": "Allow", "Principal": "*", "Action": "s3:*", "Resource": "arn:aws:s3:::agristore.001/*" } ] } My settings file STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR / 'static/' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media/' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' AWS_ACCESS_KEY_ID = '***' AWS_SECRET_ACCESS_KEY = '***' AWS_STORAGE_BUCKET_NAME = '****' AWS_S3_FILE_OVERWRITE = False AWS_QUERYSTRING_AUTH = False My Nginx settings server { server_name <my ip>; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/venv/src; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } -
Django Page not found error on url redirect
So I'm dealing with a little problem here. So what i wanna do is: sign up an user, then redirect him to a new page that contains a form which will collect some additional info about him and then after he submits the form, it should redirect him to the login page. I want this version because only new users should complete this form. signup view class SignUpView(CreateView): form_class = SignupForm success_url = reverse_lazy('user_ski_experience:user_questions') template_name = "signup/signup.html" additional info view class CreateInfoView(LoginRequiredMixin, CreateView): model = AdditionalInfoModel form_class = AdditionallnfoModelForm template_name = "user_ski_experience/additional_info.html" def get_form_kwargs(self): variable_to_send = super(CreateInfoView, self).get_form_kwargs() variable_to_send.update({'pk': None}) variable_to_send.update({'pk_user': self.request.user.pk}) return variable_to_send def get_success_url(self): return reverse('login')