Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
MultiValueDictKeyError varies in localhost and Heroku host
I'm currently learning django and I've created a simple TODO project which has an otp authentication feature. While running the project in localserver otp was generated and stored in the model which is then matched by using if (t.otp == int(request.POST['otp'])): where t is a model object. This works perfectly fine. While I deployed the same in heroku server with DEBUG = True for testing purpose, it is throwing MultiValueDictKeyError in line if (t.otp == int(request.POST['otp'])):. Initially t.opt is set to the value generated and it is reinitialized to 0 once the user enters the correct OTP and registers. Kindly notice the comments in the code that explains the issue a bit more. My views.py goes as (I've removed some elif part that are not required to reduce the number of lines), def regsub(request): if(request.method=="POST"): uname = request.POST['username'] fname = request.POST['fname'] lname = request.POST['lname'] email = str(request.POST['email']) pass1 = request.POST['pass1'] try: **#this tries to get the values pass1 and pass 2 whereas except gets the value otp** if(request.POST['pass1']==request.POST['pass2']): dictpass = { 'username':uname, 'fname':fname, 'lname':lname, 'email':email, 'password':pass1, } the_otp = r.randint(100000,999999) try: t=temp.objects.create(name=uname,otp=the_otp) t.save() except(IntegrityError): return render(request,'register.html',{'flag':True,'msg':"Username already exits! Please try again."}) sub = "OTP for registration" msg = "Some Message … -
How to use a test bucket for MinIO?
I'm writing a Django app, and I use Minio as my object storage. I use this python package.enter link description here I want to create a test bucket for my unit tests. What should I do? In my models.py file, I add a default bucket to save objects; I don't know what I should do for the test request. It is my model: class PrivateAttachment(models.Model): file = models.FileField(verbose_name="Object Upload", storage=MinioBackend(bucket_name='django-backend-dev-private'), upload_to=iso_date_prefix) I really appreciate any help you can provide. -
Failed to build cryptography greenlet ERROR: Could not build wheels for cryptography which use PEP 517 and cannot be installed directly
A client sent to me an app-web in python-django, I am trying to run app on my local windows 10 Installed docker desktop for w10. Then run docker-compose -f local.yml build And I got an error while building: #8 83.78 Failed to build cryptography greenlet #8 83.78 ERROR: Could not build wheels for cryptography which use PEP 517 and cannot be installed directly The weird thing its that I dont have cryptography in my requirements files: base.txt pytz==2018.5 # https://github.com/stub42/pytz python-slugify==1.2.5 # https://github.com/un33k/python-slugify Pillow==5.2.0 # https://github.com/python-pillow/Pillow argon2-cffi==18.3.0 # https://github.com/hynek/argon2_cffi whitenoise==4.0 # https://github.com/evansd/whitenoise redis>=2.10.5 # https://github.com/antirez/redis django-background-tasks==1.2.0 # https://github.com/arteria/django-background-tasks # Django # ------------------------------------------------------------------------------ django~=2.1.0 # https://www.djangoproject.com/ django-environ==0.4.5 # https://github.com/joke2k/django-environ django-model-utils==3.1.2 # https://github.com/jazzband/django-model-utils django-allauth==0.37.1 # https://github.com/pennersr/django-allauth django-crispy-forms==1.7.2 # https://github.com/django-crispy-forms/django-crispy-forms django-redis==4.9.0 # https://github.com/niwinz/django-redis # Django REST Framework djangorestframework~=3.9.0 # https://github.com/encode/django-rest-framework coreapi==2.3.3 # https://github.com/core-api/python-client django-filter djangorestframework-filters==1.0.0.dev0 drf-flex-fields~=0.3.5 # Channels channels~=2.1.5 # https://github.com/django/channels channels_redis~=2.3.1 # https://github.com/django/channels_redis local.txt -r ./base.txt Werkzeug==0.14.1 # https://github.com/pallets/werkzeug ipdb==0.11 # https://github.com/gotcha/ipdb Sphinx==1.7.7 # https://github.com/sphinx-doc/sphinx psycopg2==2.7.4 --no-binary psycopg2 # https://github.com/psycopg/psycopg2 bpython~=0.17 # Testing # ------------------------------------------------------------------------------ pytest==3.7.3 # https://github.com/pytest-dev/pytest pytest-sugar~=0.9.1 # https://github.com/Frozenball/pytest-sugar # Code quality # ------------------------------------------------------------------------------ flake8==3.5.0 # https://github.com/PyCQA/flake8 coverage==4.5.1 # https://github.com/nedbat/coveragepy # Django # ------------------------------------------------------------------------------ factory-boy==2.11.1 # https://github.com/FactoryBoy/factory_boy django-debug-toolbar==1.9.1 # https://github.com/jazzband/django-debug-toolbar django-extensions==2.1.2 # https://github.com/django-extensions/django-extensions django-coverage-plugin==1.5.0 # https://github.com/nedbat/django_coverage_plugin pytest-django==3.4.2 # https://github.com/pytest-dev/pytest-django django-cors-headers … -
Filter objects manyTomany with users manyTomany
I want to filter the model Foo by its manyTomany field bar with users bar. Models class User(models.Model): bar = models.ManyToManyField("Bar", verbose_name=_("Bar"), blank=True) class Foo(models.Model): bar = models.ManyToManyField("Bar", verbose_name=_("Bar"), blank=True) class Bar(models.Model): fubar = models.CharField() with this user = User.objects.get(id=user_id) I want to gett all Foo's that have the same Bar's that the User has. I would like this to work: bar = Foo.objects.filter(foo=user.foo) but it doesn't work. -
Custom queries in django serializers
I have the following view that allows me to determine defined prices for the logged in user and captures the information of the provider model requested by the user: class ProductStoDists(mixins.ListModelMixin, generics.GenericAPIView): permission_classes = (permissions.IsAuthenticated,IsSavedRole) queryset = SellProduct.objects.select_related("provider", "product", "coupon_percentage", "coupon_quality").filter(~Q(stock = None), Q(disabled_sale=False)) serializer_class = SellProductSerializer parser_classes = (MultiPartParser,) filter_backends = [DjangoFilterBackend, filters.SearchFilter] filterset_fields = ["product", "provider", "provider__state_prin_venue", "product__sectors", "product__categories", "provider__type_provider"] pagination_class = Pagination def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) #@method_decorator(cache_page(60*60)) #@method_decorator(vary_on_cookie) def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) entity = Provider.objects.filter(administrator=request.user) data_price = [] if page is not None: serializer = self.get_serializer(page, many=True) object_dataset = DataSetIds() if request.user.role != "lab": prices = [] for sell_product_cost in serializer.data: provider = Provider.objects.filter(id_provider=sell_product_cost["provider"]).select_related("country_prin_venue", "state_prin_venue", "city_prin_venue", "administrator") price_object = CustomPrices(entity, request.user.id, provider) if provider[0].type_provider == "dist": if request.user.role == "dist" or request.user.role == "sto": sell_product_cost["distributors"] = price_object.get_sell_distributors(sell_product_cost["id_sell"]) else: sell_product_cost["distributors"] = None else: if request.user.role == "sto": sell_product_cost["storage"] = price_object.get_sell_storage(sell_product_cost["id_sell"]) else: sell_product_cost["storage"] = None return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) How could I make the "storage" or distributors field be done from the serializardor and not from the view?, since I consider that this can slow down the response of the customer service. -
Accessing attributes on different types of profiles
I've got two different type of user profile defined in my project: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) full_name = models.CharField(max_length=128) address = models.CharField(max_length=256) class Meta: abstract = True class ProfileA(Profile): # Special fields related to ProfileA class ProfileB(Profile): # Special fields related to ProfileB While I need to access the attributes on user's profile I use hasattr to detect profile type, something like: if hasattr(request.user, profilea): print(request.user.profilea.address) else: print(request.user.profileb.address) Or in templates: {% if user.profilea %} {{ user.profilea.address }} {% else %} {{ user.profileb.address }} {% endif %} To make it simpler I wrote a middleware to set profile attribute on request.user: if hasattr(request.user, "profilea"): request.user.profile = request.user.profilea request.user.is_a = True else request.user.profile = request.user.profileb request.user.is_a = False So now I can use something like {{ user.profile.address }} in my templates and request.user.profile.address in my Views. However my problem raise where I have to deal with a set of Users with different type of profile. Now I have to constantly use conditions every where I need to access attributes on User's profiles. I can also write a template tag: @register.filter def is_a(obj): if hasattr(obj, 'profilea'): return True return False And use it like: {% if user|is_a %} {{ user.profilea.address … -
How to customize the text in change_form template of Admin dashboard in Django?
I want to remove the word 'Another' from change_form template as shown in the image. Other Details is a StackedInline model. I tried overriding the template to remove the text but could not find a way. Please give a suggestion or a solution to this. Thanks in advance -
Invalid block tag 'else'. Did you forget to register or load this tag?
Why I got this error? I have this error on django, while it's working correctly on flask. 1 {% if user.is_authenticated %} 2 {% extends "home.html" %} 3 {% else %} 4 {% extends "index_not_auth.html" %} 5 {% endif %} TemplateSyntaxError at / Invalid block tag on line 3: 'else'. Did you forget to register or load this tag? Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.2 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 3: 'else'. Did you forget to register or load this tag? Exception Location: D:\GitHub Repositories\Django-WebApp\venv\lib\site-packages\django\template\base.py, line 534, in invalid_block_tag Python Executable: D:\GitHub Repositories\Django-WebApp\venv\Scripts\python.exe Python Version: 3.6.1 -
Through relationship using polymorphic model
I'm trying to use a through relationship between a polymorphic and a non-polymorphic table with the the RankedAthlete model: class ChoiceBlank(PolymorphicModel): pass class ChoiceAthlete(ChoiceBlank): choice = models.ForeignKey('SomeModel', on_delete=models.CASCADE) class BetMultiple(models.Model): answer = models.ManyToManyField('ChoiceBlank', blank=True, through='RankedAthlete') class RankedAthlete(models.Model): choiceAthlete = models.ForeignKey('ChoiceBlank', on_delete=models.CASCADE) bet = models.ForeignKey('BetMultiple', on_delete=models.CASCADE) rank = models.IntegerField() This doesn't work because RankedAthlete expects a ChoiceBlank and a ValueError is raised when I create one. Conversely, I can't migrate my db if I replace choice with a ChoiceAthlete. Django-polymorphic doc doesn't mention my use case, is it unsupported? Is there a way to make this work? -
Best practices for long running tasks in django
I am developing web app on django. One of the problem that I encounter, is long running tasks, that can execute during weeks or more. I am talking about Campaign entity. User creates one, launch and can wait and see intermidiate results. What is the best practise to implement such tasks in django. One of the options that I could find is celery and rabbitmq. -
Django: display many to many relationship through a model in themplate
I have this ManyToMany relationship through an intermediary model: class Group(models.Model): members = models.ManyToManyField(Student, through='NamedMembershipClub') class Membership(models.Model): year = models.IntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) I'm trying to display members with the year they joined in my template. I read on this post that I should use members_set.all {% for member in object.members_set.all %} <p>{{member.user.first_name}} {{member.year}}</p> {% endfor %} But it doesn't produce any output, the loop is just not entered because the set is empty. I also tried : {% for member in object.members.all %} <p>{{member.first_name}}</p> {% endfor %} Which gives some satisfaction because I can display the user but not the associated data in the Membership model. Is there any way to get the set directly in the template ? Thanks! I'm running Django 3.0. -
How can i filter by date min and date max with rows?
how can i get a filter by date min and date max without model, i connect to a external database and get a consultation but cant filter Add code here: views.py def BootstrapFilterView(request): cursor.execute("[Prueba].[dbo].[Pr_Ne] '10/04/2021 4:00:00', '28/05/2021 23:59:59'") qs = cursor.fetchall() prog_data_ini = request.GET.get('prog_data_ini') date_min = request.GET.get('date_min', None) date_max = request.GET.get('date_max', None) fecha = datetime.now() format_min = fecha.strftime('%Y-%m-%d') date_max = fecha + timedelta(days=1) format_max = date_max.strftime('%Y-%m-%d') if is_valid_queryparam(date_min): qs = qs.filter(prog_data_ini__gte=date_min) if is_valid_queryparam(date_max): qs = qs.filter(prog_data_ini__lt=date_max) html <div class="input-group date"> <b class="b-form">DESDE:</b><input type="date" class="form-control" id="publishDateMin" name="date_min" value="{{format_min}}"> <span class="input-group-addon"> <i class="glyphicon glyphicon-th"></i> </span> </div> <div class="input-group date"> <b class="b-form">HASTA: </b> <input type="date" class="form-control" id="publishDateMax" name="date_max" value="{{format_max}}"> <span class="input-group-addon"> <i class="glyphicon glyphicon-th"></i> </span> </div> -
Django: Show media files to authenticated users only
I'm on Django 3.2 not using django's default server and I want to restrict certain media[mostly pdf files] inside the media directory to logged in users only. Is there any way to do that? Thanks. PS:I'm aware of a question similar to this,but it is on django v1.x and Nginx -
how to send nested functions data to another function in python
I want to display the value of a variable in world function. def base(): print("Hello World") def child(): a = 10 return a def world(): num = base.child() # error ------- print(num) world()``` -
Run custom command from admin panel
Instead of connecting to the server and running the custom command from the terminal, I'd like to make it easy for someone to log into the admin panel and run it on a button click. The current idea is to extend the admin index template to include a button that links to a particular view and then have the command be triggered in the view function. However, that sounds like a hacky solution. Is there a more elegant way? -
CreateView not receiving Kwargs from urls.py
I've been using arguments provided in the path(...) in urls.py for my view, which is a TemplateView. Now, I've been trying to do the same with a similar template, but using a CreateView. After some debugging, I've realized that for some reason a CreateView doesn't seem to receive the kwargs defined in the urls.py path. For instance: urls.py path('product/<int:pk>/', views.SomeViewClass.as_view(), {"foo": "bar"}, name='detail_product', ), views.py class SomeViewClass(TemplateView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) section = kwargs["foo"] The above works. However, this doesn't: urls.py path('create/', views.OtherClassView.as_view(), {"foo": "bar"}, name='create'), views.py class OtherClassView(CreateView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) section = kwargs["foo"] Any obvious workaround? Other than fishing out this parameter through a completely different pipeline? -
How to store Unique=True in database in django
My app keeps book records for different schools I have a Klass model that enables each school to key in the classes in the school. I also have an import-export resource for importing books details in bulk. I however get an error because already there are two schools each having form 1 form 2 and form 3. It return MultipleObjectsReturned error get() returned more than one Klass -- it returned 2! How can I help my situation??? class ImportStudentsResource(resources.ModelResource): school = fields.Field(attribute = 'school',column_name='school', widget=ForeignKeyWidget(School, 'name')) klass = fields.Field(attribute = 'klass',column_name='class', widget=ForeignKeyWidget(Klass, 'name')) stream = fields.Field(attribute = 'stream',column_name='stream', widget=ForeignKeyWidget(Stream, 'name')) class Meta: model = Student fields = ('school','student_id','name','year','klass','stream') import_id_fields = ('student_id',) import_order = ('school','student_id','name','year','klass','stream') class uploadStudents(LoginRequiredMixin,View): context = {} def get(self,request): form = UploadStudentsForm() self.context['form'] = form return render(request,'libman/upload_student.html',self.context) def post(self, request): form = UploadStudentsForm(request.POST , request.FILES) data_set = Dataset() if form.is_valid(): file = request.FILES['file'] extension = file.name.split(".")[-1].lower() resource = ImportStudentsResource() if extension == 'csv': data = data_set.load(file.read().decode('utf-8'), format=extension) else: data = data_set.load(file.read(), format=extension) result = resource.import_data(data_set, dry_run=True, collect_failed_rows=True, raise_errors=True) if result.has_validation_errors() or result.has_errors(): messages.success(request,f'Errors experienced during import.') print("error", result.invalid_rows) self.context['result'] = result return redirect('upload_students') else: result = resource.import_data(data_set, dry_run=False, raise_errors=False) self.context['result'] = None messages.success(request,f'Students uploaded successfully.') else: self.context['form'] = … -
I have created my piechart for my database(postgresql) value in python using django ..But i couldn't display on my server
Main url urlpatterns = [ path('',include('health.urls')), path('admin/', admin.site.urls), path('users/',include('users.urls')), path('Dashboard/',include('Dashboard.urls')) ] Dashboard.urls from django.urls import path from . import views urlpatterns = [ path("pe", views.piechart, name="piechart"), path("data", views.piechartdata, name="piechartdata") ] dashboard view.py..Here I have two functions but am able to return only one ..How to add both at my main html page from django.http import JsonResponse from django.shortcuts import render from Dashboard.models import userdashboard from django.core import serializers def piechart(request): return render(request, "piechart.html", {}) def piechartdata(request): dataset = userdashboard.objects.all() data = serializers.serialize('json', dataset) return JsonResponse(data, safe=False) In my html page i could return only one function,but I need both..can anyone help me?? <li><a href="Dashboard/pe">Dashboard</a></li> model: from django.db import models class userdashboard(models.Model): Month = models.CharField(max_length=30) Values = models.IntegerField() -
Django not accepting parsed csv date input even though it follows the YYYY-MM-DD format. What is the problem?
I'm trying to populate my existing Django model with values from a csv file. I've tried to use datetime.strptime() but it also has not worked. This is the code I'm trying to run from the Django python manage.py shell loadcsv.py import csv from dashboard.models import Checkin with open('foo.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: new_checkin = Checkin(date=row[0],project_id=row[1],manager_id=row[2],user_id=row[3],hours=row[4]) new_checkin.save() # # row[0] = date; # # row[1] = project # # row[2] = manager # # row[3] = user # # row[4] = hours models.py (dashboard.models) from django.db import models # Create your models here. class Checkin(models.Model): date = models.DateField(blank=False) project_id = models.IntegerField(blank=False) manager_id = models.IntegerField(blank=False) user_id = models.IntegerField(blank=False) hours = models.DecimalField(max_digits=5, decimal_places=2) foo.csv sample entry date,project_id,manager_id,user_id,hours 2019-09-11,134,1,1,3 2019-09-11,201,1,1,5 2019-12-23,14,8,2,0.46 2019-12-23,14,8,2,0.46 The error I'm getting django.core.exceptions.ValidationError: ['“date” value has an invalid date format. It must be in YYYY-MM-DD format.'] I can save to the database when I manually create a single object in the shell like so: from dashboard.models import Checkin new_checkin = Checkin(date="2012-01-01", manager_id="5", project_id="5",user_id="3", hours="0.75") new_checkin.save() -
Cookies in Django/JavaScript for a cart in webstore
I'm just starting to add cookie to my webstore and I need to use cookies in order for the cart to update the added products. Any tips? Is django good to use for storing cashe and using them in the shopping cart - or is it simpler to only use JavaScript? Don't have a lot of code to show as I've just stared doing the cookies, any tips would be helpful! :) -
I want to login with both and phone number in this DRF
I'm currently using a custom user model and can log in with my phone number. But now I want to log in with both phone and email. Please check the given code and let me know in the comments if any more details are needed. Thanks in advance. class LoginSerializer(serializers.Serializer): phone = serializers.CharField() password = serializers .CharField() def validate(self, data): email = data. get ('email') phone = data.get('phone') password = data.get('password') reg = False print(phone, ",", password) obj = CustomUser.objects.get(phone=phone) if phone and password: user = authenticate(username=obj.username, password=password) if user: data['user'] = user print(user.id) else: msg = 'login failed' raise exceptions.ValidationError(msg) else: msg = 'provide credientials' raise exceptions.ValidationError(msg) return data -
Django custom URL mapping: date pattern not matched in template
I am using Django 3.2 I have created a custom Date URL pattern matcher as follows: helpers.py from datetime import datetime class DateConverter: regex = '\d{4}\d{2}\d{2}' def to_python(self, value): return datetime.strptime(value, '%Y%m%d') def to_url(self, value): return value urls.py from django.urls import path, register_converter from . import views from myproj.helpers import DateConverter app_name = 'event' register_converter(DateConverter, 'yyyymmdd') urlpatterns = [ path('', views.index, name='index'), path('detail/<int:event_id>/<slug:event_slug>', views.detail, name='detail'), path('archive/<yyyymmdd:start_date>/<yyyymmdd:end_date>', views.archive, name='archive'), ] index.html (relevant section) <div class="row"> <a href="{% url 'event:archive' '2020101' '2020201' %}">Previous Events</a> </div> I get the following error: reverse for 'archive' with arguments '('2020101', '2020201')' not found. 1 pattern(s) tried: ['media/events/archive/(?P<start_date>\d{4}\d{2}\d{2})/(?P<end_date>\d{4}\d{2}\d{2})$'] How do I fix this? -
django superuser created through docker-compose file doesn't work
I have a simple django-mongo application. I have a dockerfile for my django application. I have a docker-compose.yml which contains django and mongo images. I am able to build and run the django-mongo application using docker-compose commands. the problem I am facing is I am unable to log into the django admin-panel using superuser credentials. Below is my dockerfile RUN mkdir /cursor_infotech WORKDIR /cursor_infotech ADD . /cursor_infotech/ RUN pip install -r requirements.txt``` docker-compose.yml ```version: "3" services: cursor-infotech: container_name: cursor image: cursor restart: always build: . #environment: # - MONGO_URI=$MONGO_URI # - PORT=$PORT # - NODE_ENV=$NODE_ENV ports: - "7000:7000" networks: - cursor-backend depends_on: - mongo command: > sh -c "python manage.py makemigrations && python manage.py migrate && python manage.py createsuperuser --noinput --username admin --email admin@test.com && gunicorn -b 0.0.0.0:7000 cursor_infotech.wsgi" mongo: container_name: mongo image: mongo environment: - MONGO_INITDB_DATABASE=cursor-pcbuild - MONGO_INITDB_ROOT_USERNAME=root - MONGO_INITDB_ROOT_PASSWORD=password volumes: - ./init-mongo.js:/docker-entrypoint-initdb.d/init-mongo-js:ro - ./data:/usr/share/db/data ports: - '27017:27017' networks: - cursor-backend networks: cursor-backend: driver: bridge``` I ran this command in my project folder ```docker-compose up --build``` The django & mongo images are build and deployed - working fine. When I try to log-into admin account in my django admin-panel, I get below error. [enter image description here][1] [1]: https://i.stack.imgur.com/WiMOV.png … -
image annotation tools with Django
I need to create an online 2D annotation tool using DJANGO. I would like to know how I can implement an already existing image annotation tool like for example (CVAT / VGG VIA / LabelMe ...) in django, Thank you. -
Reverse list in descending order to get the last objects in django template
I've searched a lot and couldn't find anything to reverse the list in descending order so that I can get the last two objects in the template. Here is my model: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') commented_by = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.CharField(max_length=128) views.py: posts = Post.objects.all().order_by("date_posted").reverse() return render(request, "cs50gram/explore.html", {"posts": posts}) template.html: {% for post in posts %} {% for comment in post.comments.all|slice:":2" reversed %} <div style="color: gray"> <b> {{ comment.commented_by }} </b> {{ comment.comment }} </div> {% endfor %} {% endfor %} The problem here is that it slices first and then reverse.. What have I tried? How to reverse a for loop in a Django template and then slice the result Using the solution presented in the answer, it didn't work for some reason. This is exactly how I tried it in my code. {% for post in posts %} {% for comment in post.comments.all.reverse|slice:":2"%} <div style="color: gray"> <b> {{ comment.commented_by }} </b> {{ comment.comment }} </div> {% endfor %} {% endfor %} The output is that it only slice it without reversing. Any help in reversing the list in descending order and getting the last n (2) objects is appreciated.