Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Include search/filtering in my choicefield django
I have a CrispyForm where I have a ChoiceField called "act_cuenta" with choices that I load from a query. I want that in this field the user has the option to type and search for one of the options within the list. form.py class MayoresForm(Form): act_cuenta = () act_fechaini = DateField( widget=DatePickerInput( format=Form_CSS.fields_date_format, options=Form_CSS.fields_date_opts, attrs={'value': Form_CSS.fields_current_date} ), label="Fecha desde: ", required=True, ) act_fechafin = DateField( widget=DatePickerInput( format=Form_CSS.fields_date_format, options=Form_CSS.fields_date_opts, attrs={'value': Form_CSS.fields_current_date} ), label="Fecha hasta: ", required=True, ) def __init__(self, *args, **kwargs): self.AIGN_OPCIONES = kwargs.pop("AIGN_OPCIONES") self.PERMISOS = [] # para recuperar los permisos de la tabla __json_values = json.loads(json.dumps(self.AIGN_OPCIONES)) self.PERMISOS = recuperarPermisos(__json_values, 'con.transaccioncab') self.AIGN_PER_ID = kwargs.pop("AIGN_PER_ID") super(MayoresForm, self).__init__(*args, **kwargs) self.fields['act_cuenta'] = ChoiceField(label='Cuenta: ', choices=self.get_choices(), required=True) for form in self.visible_fields(): form.field.widget.attrs['autocomplete'] = Form_CSS.fields_autocomplete form.field.widget.attrs['class'] = Form_CSS.fields_attr_class self.helper = FormHelper(self) self.helper.form_method = 'post' self.helper.form_id = Form_CSS.getFormID(self) self.helper.attrs = Form_CSS.form_attrs self.helper.form_tag = True self.helper.label_class = 'col-sm-3 text-right form-control-sm' self.helper.field_class = 'col-sm-6' self.helper.layout = Layout( Div( DivHeaderWithButtons(instance_pk=None, remove_create=False, remove_delete=True, remove_print=True, remove_cancel=False, permisos=self.PERMISOS, save_name=' Consultar'), Div( Div( Div( Div( Div( HTML("<h3 class='card-title'>Buscar por:</h3>"), css_class='card-header' ), Div( Div( 'act_cuenta', css_class='card-body' ), Div( 'act_fechaini', 'act_fechafin', css_class='card-body' ), css_class="row" ), css_class='card card-secondary' ), css_class='col-sm', ), css_class='row', ), css_class='card-body' ), css_class='card' ), ) def get_choices(self): all_tipoaux = Con_Cuenta.objects.filter(cue_grupo='M', cue_estado=1, per_id=self.AIGN_PER_ID).order_by( 'cue_codigov').values() … -
Django to register multiple URL Nested and default
This is my URLs of the app router = routers.DefaultRouter() router.register(r'school', SchoolView, 'school-view') router.register(r'student', StudentView, 'student=view') school_router = routers.NestedDefaultRouter(router, r'school', lookup='school') school_router.register(r'students', StudentSchoolView, basename='student-school') urlpatterns = router.urls And am registering my URLs in the project URLs from django.contrib import admin from django.urls import path, include from student_school.urls import urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('', include(urlpatterns)) ] I want to have both the routes in my app URL, right now am only getting the URLs from the router(Default) but I also want to get the routes of the Nested Routes -
Django recursive models with through
I'm trying to set up a model such that the parts of the model can have parent or child relations to each other. It was working using the automatically generated 'relationship' table, but I needed to add an additional column for quantity. I thought I had hit gold when I found this in the documentation, but I can't seem to make it work. Here's my code: class Part(models.Model): name = models.CharField(max_length=100) parent = models.ManyToManyField( 'self', symmetrical=False, through='Relationship', through_fields = ('parent', 'child'), blank=True) class Relationship(models.Model): qty = models.IntegerField(default=1) parent = models.ForeignKey(Part, on_delete=models.CASCADE, related_name='+', null=True) child = models.ForeignKey(Part, on_delete=models.CASCADE, related_name='+', null=True) When I go to add a part, I can't add a parent to it. -
How to pass extra arguments to startapp command in bash?
I want to pass values to template_context and the docs says: Any option passed to the startapp command (among the command’s supported options) What I understand is, that any extra argument that I pass, it will be set to the context dictionary. But I'm receiving the same error (django-admin startapp: error: unrecognized arguments: --options=ok) django-admin startapp name_app --template="./templates" --options="ok" I also tried with - and without it django-admin startapp name_app --template="./templates" -a_value="ok" and django-admin startapp name_app --template="./templates" some_value="ok" How am I supposed to add the extra arguments? I know must be something easy, but I'm stuck for too much time now, and I couldn't find an example that uses it. -
Users instead id , Django(wagtail) , Vue
I want to make a class that returns usename of all users who liked the post. Users will be sent to Vue. currently the code returns in Vue consol log - 0: {likex: 'ideas.IdeaPage.None'} models.py class IdeaPage(Page): intro = models.CharField(max_length=250) body = RichTextField() tags = models.CharField(max_length=100, null=True, blank=True) likex = models.ManyToManyField(User, related_name="likex", blank=True) serializer.py class LikeSerializer(serializers.ModelSerializer): likex = serializers.CharField() class Meta: model = IdeaPage fields = ["likex"] views.py @authentication_classes([authentication.TokenAuthentication]) @permission_classes([permissions.IsAuthenticated]) class Like(APIView): def get(self, request, id, format=None): ideasl = IdeaPage.objects.get(id=id) likepost = IdeaPage.objects.get(id=id) likepostZ = likepost.likex.all() if request.user in likepost.likex.get_queryset(): likepost.likex.remove(request.user) else: likepost.likex.add(request.user) serializer = LikeSerializer(likepostZ, many=True) return Response(serializer.data) why code return likex: 'ideas.IdeaPage.None'? -
Celery delay task gets called twice but triggers only once
I am trying to run a celery task with multiple files. Simply put in a for loop I am calling the delay method on the task and I know that it gets called because I can see the logs before being called. However, the action inside the task itself gets executed only once. in my code I have something like this: def operation(*args, **kwargs): for arg in *args: time.sleep(2) # 2s interval celery_task.delay(kwargs) And the task actually look like this @shared_task(bind=True) def celery_task(**kwargs): do_something() # async So my question is: is there some kind of check that I can't see that prevents multiple tasks to be sent, or does it have something to do with different threads? Consider that I am not sending all the tasks at once, I am using an interval of 2 seconds before calling the task each iteration in the loop. -
How to make a django api view accessible to all users?
I'm creating a Django API view for a game by extending the rest_framework.views.APIView class. It's very likely that most users will not be authenticated. How can I enforce that? As far as I know there is no permissions.IsNotAuthenticated or similar. This is the part where I have trouble in my view, where I am trying to create a game round and game session object. I have tried working around this issue by creating a pseudo-user if the user isn't authenticated: if not isinstance(request.user, CustomUser): current_user = '1' else: current_user = request.user However, I keep getting this Value error message: Cannot assign "'1'": "Gamesession.user" must be a "CustomUser" instance. Below the code section from views.py current_score = 0 if not isinstance(request.user, CustomUser): current_user = '1' else: current_user = request.user gamesession = Gamesession.objects.create( id=controller.generate_random_id(Gamesession), user=current_user, gametype=gametype, created=datetime.now() ) gameround = Gameround.create({ 'id': controller.generate_random_id(Gameround), 'user': current_user, 'gamesession': gamesession, 'created': datetime.now(), 'score': current_score, }) gameround_serializer = GameroundSerializer(gameround) -
auth_token for unittest in Django
I've been trying to test my login system using the following code from django.test import TestCase, Client from rest_framework.test import force_authenticate class DeckTestCase(TestCase): @classmethod def setUp(cls): test_user1 = User.objects.create(first_name='tester',username='test1', password='123', email='testuser@something.com') def test_if_logged(self): factory = Client() user = User.objects.get(username='teste1') request = factory.post('/login', {'username': 'test1', 'password': '123'}, format='json') force_authenticate(request,user=user) print(request) But i keep getting this response, which is 401 (Unauthorized) <Response status_code=401, "application/json"> Can someone help me? I don't know how do I send an auth_token with test_if_logged -
How can I hide item entries in foreign key forms when they have 0 quantity in django forms?
I want to hide the item entries that are 0 or doesn't have any in stock, my current code for the item borrowing process is. Models.py class Activity(models.Model): Item = models.ForeignKey(Item, on_delete=models.CASCADE, null=True) staff = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) project_site = models.ForeignKey(Projects, on_delete=models.CASCADE, null=True) Quantity = models.PositiveIntegerField(null=True, default=1, validators=[ MaxValueValidator(100), MinValueValidator(1) ]) date_created = models.DateTimeField(auto_now_add=True) is_draft = models.BooleanField(default=True) request_status = models.IntegerField(default=0, validators=[ MaxValueValidator(3) ]) return_status = models.IntegerField(default=0, validators=[ MaxValueValidator(3) ]) note = models.TextField(max_length=255, null=True) class Meta: verbose_name_plural = 'Item Request' def __str__(self): return f'{self.Item}' Forms.py class ActivityForm(forms.ModelForm): class Meta: model = Activity fields = ['Item', 'Quantity', 'project_site'] -
Django passing the post id from a button to the form
I got a button in html that is on the given post. This button opens up a form, that is hidden, until pressing the button. and the form itself is written further down on the page. The button <button class="btn btn-info" data-toggle="modal" data-target="#note-update-modal">Update</button> Then on the form for updating the post, i pass inn the post id, but it does not get the post id. the form, further down the html, that open up, when the update button is pressed <form method="POST" action="{% url 'update_notes' note.id title.slug %}" class="modal fade" id="note-update-modal" tabindex="-1" aria-hidden="true"> This form updated the post, but not the given post that the button presses, only takes the last posted post. I need a way to pass the id from the button, that is pressed to open the form, so that the form get the right id. Is there a way to do this? If somehow the question is not making sense please write, and yes the update function, the view, urls, everything work, it is just to get the right post. -
Django DigitalOcean Apps Deployment
I have a very small application that I am working on. I have everything up and running locally but can't get it deployed to DigitalOcean Apps. I have re-read all the tutorials and just can't get past this one spot. See the error below ModuleNotFoundError: No module named 'dj_database_url' So I have manually created the static file directories in the project, I ran the python manage.py collectstatic --noinput command locally and it did its job and put the files in the STATIC_ROOT directory. I also changed things out and the module name will change based on the order of the requirements.txt I really have no idea what I can do to fix this. Any help would be greatly appreciated. It feels like it is a really simple fix but I don't know what it is. -
I am getting this error Attribute Error and I have checked for the typos but found none
AttributeError at /api-auth/ Got AttributeError when attempting to get a value for field name on serializer UserDetailsSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'name'. my model from django.db import models # Create your models here class UserDetails(models.Model): name = models.CharField(max_length=100) password = models.CharField(max_length=100) virtualId = models.TextField(null=True, blank=True) photo = models.ImageField(upload_to='uploads/') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name serializers: from rest_framework.serializers import ModelSerializer from .models import UserDetails class UserDetailsSerializer(ModelSerializer): class Meta: model = UserDetails fields = '__all__' views : from rest_framework.response import Response from rest_framework.decorators import api_view from .models import UserDetails from .serializers import UserDetailsSerializer # Create your views here. @api_view(['GET']) def getAllUserdata(request): user = UserDetails.objects.all() serializer = UserDetailsSerializer(user) return Response(serializer.data) -
Problems with CustomUser model in Django
I am new using Django and I am trying to build a project that requires to use a Custom User Model. I have encountered many problems on my way, tried to resolve them on my own but after more than one week I am exhausted, so I ask for your help. I think the main problem is that I don't understand well how to create a CustomUser model. I need a user to have many fields (E.g full_name, mobile_phone, etc), but one of the critical fields which I've had problems is: division_id (wich is a foreign key for a model created in another app named 'divisions'). I've had a lot of problems because there is no any migration yet (its supposed that your first migration must be when you created your custom user model), so there isn't any values in 'division' model. Is it possible to refer a foreign key in that case considering that the model referred isn't created yet? I mean, the first migration can create a custom user model and a division model simultaneusly, or what I have to do? Another problem I have, is that when I'm trying to refer the Division model into my CustomUser … -
How to import file from a nested directory with django
I am building a django web application. For the code, I have a few helper functions I am trying to import, but django gives me a ModuleNotFoundError. This is my file structure ── stock_predictor ├── __init__.py ├── admin.py ├── apps.py ├── models.py ├── models_helper │ ├── __init__.py │ ├── arma.py │ ├── data_handler.py │ └── yahoo_stock_data.py ├── tasks.py ├── templates │ ├── base.html │ └── homepage.html ├── tests.py ├── urls.py └── views.py Here the models_helper directory contains a list of files I want to import in the tasks.py file. I tried adding the __init__.py file to the models_helper directory, but this does not solve the issue. I also tried adding the path to sys.path. That, too, does not seem to solve the problem. My imports in the tasks.py files are as follows. from models_helper.yahoo_stock_data import YahooStockData from models_helper.data_handler import DataHandler from models_helper.arma import AlgoARMA The error I get is as follows. ModuleNotFoundError: No module named 'models_helper' NOTE: This seems to be a django issue as I can import using sys and run the python script directly from the terminal. These are the links I followed to get the code to work, but it does not. Importing modules from nested folder … -
Permission denied error on django-s3direct
When uploading a file to S3 there comes error like this in console [WARNING][220126 010447] Forbidden: /s3direct/get_aws_v4_signature/ [26/Jan/2022 01:04:47] "POST /s3direct/get_aws_v4_signature/ HTTP/1.1" 403 31 and Permission denied(like javascript alert, but why??) popup is shown on browser. I have checked the credential and Bucket name again and again, but there is no typo. and I can upload the file with this credential from aws-cli However this django code show the permission error. Where should I check ?? in settins.py setup AWS environment. AWS_ACCESS_KEY_ID = '**********' AWS_SECRET_ACCESS_KEY = '*******************' AWS_STORAGE_BUCKET_NAME = 'vr-dev-bot-resource-bucket' AWS_S3_REGION_NAME = 'ap-northeast-1' AWS_S3_ENDPOINT_URL = 'https://s3.ap-northeast-1.amazonaws.com' S3DIRECT_DESTINATIONS = { 'example_destination': { # "key" [required] The location to upload file # 1. String: folder path to upload to # 2. Function: generate folder path + filename using a function 'key': 'uploads/images', # "auth" [optional] Limit to specfic Django users # Function: ACL function 'auth': lambda u: u.is_staff, # "allowed" [optional] Limit to specific mime types # List: list of mime types 'allowed': ['image/jpeg', 'image/png', 'video/mp4'], # "bucket" [optional] Bucket if different from AWS_STORAGE_BUCKET_NAME # String: bucket name 'bucket': 'custom-bucket', # "endpoint" [optional] Endpoint if different from AWS_S3_ENDPOINT_URL # String: endpoint URL 'endpoint': 'custom-endpoint', # "region" [optional] Region if different from AWS_S3_REGION_NAME … -
what is the use of room in the in the render section?
***python Django framework I can't understand what is the use of {'rooms':rooms}) in the render section please help i am just learning django import imp from django.shortcuts import render from django.http import HttpResponse rooms =[ {'id':1, 'name':'learn python'}, {'id':2, 'name':'learn html and javascript'}, {'id':3, 'name':'at last learn django'}, ] # Create your views here. def home(request): return render(request,'home.html', **{'rooms':rooms})** def room(request): return render(request, 'room.html') -
Django how to prevent to showing inbound forms data to others forms?
in my blog page I have comment section where I am rending forms after each comment. Right now if any comment forms didn't successfully submitted then it's showing inbound data to others forms. How to prevent to to showing inbound forms data or invalid data to others forms? here is code: views.py: ...my others code if request.method == "POST": comment_form = CommentFrom(request.POST or None) if comment_form.is_valid(): isinstance.save() ...my others code my html #this is parent forms <form method="POST"> <input type="text" name="name" {% if comment_form.is_bound %} value="{{ comment_form.name.value }} {% endif %}"> <textarea>{% if comment_form.is_bound %}{{ comment_form.comment.value }} {% endif %} </textarea> </form> #this is child forms after every comment inside my for loop <button type="button" data-toggle="collapse" data-target="#collapseExample{{i.sno}}" aria-expanded="false" aria-controls="collapseExample{{i.sno}}"> Replay </button> <form method="POST"> <input type="text" {% if comment_form.is_bound %} value="{{ comment_form.name.value }} {% endif %}" name="name"> <textarea>{% if comment_form.is_bound %}{{ comment_form.comment.value }} {% endif %} </textarea> </form> -
Permission denied error in django app develop. im using windows 10. how to solve this error?
enter image description here how to solve this error in windows. -
Django how deactive User Account
Let's say I want to deactivate the specific User Account when the user clicks Deactivate Account button. How would I do this? \\views.py def delete_view(request): profile = request.user if request.method == 'POST': form = DeleteUserForm(request.POST, request.FILES, instance=profile) if form.is_valid(): profile.is_active = False return redirect('/') else: form = DeleteUserForm(instance=profile) return render(request, 'delete.html', {'form': form, 'profile': profile}) \\forms.py class DeleteUserForm(forms.Form): delete = forms.CharField( label='', max_length=0).widget = forms.HiddenInput() The code was just an attempt, but does not work because of the instance, so you can think away the instance -
django.db.migrations.exceptions.NodeNotFoundError: Migration order.0001_initial dependencies reference nonexistent parent node
I mistakenly deleted all the migrations folders inside the app and also deleted the db. Also, I ran command python manage.py flush. After all when I am running this python manage.py makemigrations I have this same error occurred. I don't know how to resolve it. Please help me to solve this. I am working on a localhost only. ` dependencies = [ ('product', '0016_productvariants_item_num'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ]` -
Routing for FormView Class
I have django_test project and defapp application in it. I want to access form.html which MyView makes, I am still confused about routing. What I know about is like this, path('', views.index, name='index'), calls def index(request): in views.py However how can I access the MyView class? in django_test/urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include,url urlpatterns = [ url(r'^s3direct/', include('s3direct.urls')), path('admin/', admin.site.urls), ] in defapp/views.py from django.shortcuts import render # Create your views here. from django.views.generic import FormView from .forms import S3DirectUploadForm class MyView(FormView): template_name = 'form.html' form_class = S3DirectUploadForm in defapp/template/form.html <html> <head> <meta charset="utf-8"> <title>s3direct</title> {{ form.media }} </head> <body> <form action="" method="post">{% csrf_token %} {{ form.as_p }} </form> </body> </html> -
Heroku Python Deployment Version Issue
Heroku will not push my Python version for my Django app and I can't figure out why... I upgraded my python from 3.8.7 to 3.10.2 and reflected this within the runtime.txt file, and the changes are clearly added, but this isn't seeming to work. From heroku's Python Support: Supported runtimes python-3.10.2 on all supported stacks``` C:\Users\New User\Downloads\django-modal-ajax-crud-main\django-modal-ajax-crud-main>git push heroku main Enumerating objects: 191, done. Counting objects: 100% (191/191), done. Delta compression using up to 4 threads Compressing objects: 100% (173/173), done. Writing objects: 100% (191/191), 72.21 MiB | 1.24 MiB/s, done. Total 191 (delta 35), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> Using Python version specified in runtime.txt remote: ! Requested runtime ("python-3.10.2") is not available for this stack (heroku-20). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to whispering-oasis-59527. remote: To https://git.heroku.com/whispering-oasis-59527.git ! [remote rejected] main -> main (pre-receive hook declined) error: failed to push some refs … -
Django modeling a supplier DB with different products. Unable to figure out supplier_product relation table
I am having a Django project where I have a supplier and multiple products which are vastly different from each other. The products are called resources. Because they are very different I cannot have a product table and therefore, don't know how to make the supplier_product model through which I can fetch all the products related to supplier. Here are example models: class Company(models.Model): ...... #some common fields class Supplier(Company): # delivery_time = "3 weeks" delivery_time = models.CharField(max_length=255, blank=True, null=True) # minimun order quantity MOQ = models.FloatField(blank=True, null=True) moq_unit = models.CharField(max_length=255, blank=True, null=True) billing_address = models.ForeignKey( .... ) shipping_address = models.ForeignKey( .... ) There are some more fields in the supplier. Here are the resources: class Resource(models.Model): ....... #some common fields class Part(Resource): code = models.CharField(max_length=255, unique=True, blank=True, null=True) supplier = models.ForeignKey( Company, related_name="supplier_part", on_delete=models.SET_NULL, null=True, blank=True, ) country = models.CharField(max_length=255, blank=True, null=True) class Fuel(Resource): code = models.CharField(max_length=255, unique=True, null=True, blank=True) color = models.CharField(max_length=255) supplier = models.ForeignKey( Company, related_name="supplier_fuel", on_delete=models.SET_NULL, null=True, blank=True, ) Now the problem is how can I make a SupplierProduct models with (supplier, product) field. Which I can use to retrieve all products from a supplier. In that case I will remove the supplier from the Fuel … -
What the meaning of ^ for url
It might be too simple question. I have this urlpatterns in urls.py urlpatterns = [ url(r'^s3direct/', include('s3direct.urls')), path('admin/', admin.site.urls), ] localhost/admin works, but localhost/s3direct shows the 404 error. Page not found (404) Request Method: GET Request URL: http://localhost:8099/s3direct Using the URLconf defined in djang_test.urls, Django tried these URL patterns, in this order: ^s3direct/ admin/ The current path, s3direct, didn’t match any of these. (I use runserver at port 8099) -
How to schedule posts for carousel in templates using django?
I'm having a hard time to come up with a solution on how to schedule posts for bootstrap carousel with dynamic data in django. Example: I created a post for Jan. 1 - Jan. 30 if today is Feb. 1 the post should still be visible on the carousel.