Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get rid of app name in the particular url?
I have this urls.py in my app from django.urls import path, include from rest_framework.routers import DefaultRouter from products import views app_name = 'products' router = DefaultRouter() router.register(r'products', views.ProductViewSet, basename='products') router.register(r'categories', views.ProductCategoryViewSet, basename='categories') router.register(r'brands', views.BrandViewSet, basename='brands') urlpatterns = [ path('', include(router.urls)), ] And this is my project's urls.py from django.contrib.auth import views as auth_views from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LoginView.as_view(template_name='users/logout.html'), name='logout'), path('__debug__/', include('debug_toolbar.urls')), ] urlpatterns += [ ... path('products/', include('products.urls', namespace='products')), ... ] And viewsets: from rest_framework import viewsets, permissions from .models import ( Product, ProductCategory, Brand, ) from .serializers import ProductSerializer, ProductCategorySerializer, BrandSerializer #all other viewsets are the same class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] A router for my app generates urls almost as expected, I can go to 'site/products/categories' for categories 'site/products/brands' for brands BUT for products url is 'site/products/products'. How to make it not to add app name in this case? I want it to be just 'site/products'. -
Date Format in Django views complex sql
I am new in Python Django and love this... but now I need create select to database where I have rows with date in this format 2020-08-21 10:43:26.000000 And I need change this date like as this Month-Day (Jan-02 for example) and after that this column group by... I am try many things what I found here but nothing works... :/ right now my query looks like this... hist_data = Vpnhistory.objects.filter(bytes_sent__gt=0) hist_data = hist_data.filter(end_time__gte=datetime.now()-timedelta(days=14)) hist_data = hist_data.values('end_time', 'bytes_sent') hist_data = hist_data.annotate(summ=Sum('bytes_sent'), end_time_str=DateToChar(F('end_time'), Value('MM-DD'))) and class DateToChar like thisin my model.py class DateToChar(models.Func): arity = 2 function = 'to_char' output_field = models.CharField() Datum still returns with full datetime format .. :/ thank you for help. Stepan -
How to acces a dict with @ in key, in django templates?
i converted a XML file with the follwing line, to a dict, with xmltodict: <drivers> <driver enable="True" guid="{8702bdfa-53b8-4a83-bd01-854293141f11}"> <Name>Intel Net e1d65x64.inf 12.17.8.7</Name> Then i passed the dict to a django template and want to access the guid. In python i can access it with dict["drivers"]["drivers"]["@guid"], since xmltodict, converted the guid key to @guid. However, i cant use {{item.drivers.drivers.@guid}} in django templates. How can i access the guid in templates? -
Django + htmx vs DRF + React
What are Django + htmx limitations compared to DRF + React? I don't know any React and I want to make something by myself. -
How can i compute a result from related models in django
class Function(models.Model): name = models.CharField(max_length=200) def __str__(self): return str(self.name) class Fractions(models.Model): fraction = models.DecimalField( max_digits = 5, decimal_places = 2) def __str__(self): return str(self.fraction) What i am trying to do if Function.name equals = "x" multiply specific Fractions.fraction by 4 and display it in the template -
How to refer or access the custom made permissions in `has_perm()` and `required_permissions`, in Django?
I want to know that how do I refer the custom made permissions in the has_perm() method of User Model and required_permissions attribute of PermissionRequiredMixin Class? Let's say I create the following custom permission: content_type = ContentType.objects.get_for_model(User) Permission.objects.create( codename='custom_permission', name='Custom Permission', content_type=content_type, ) and suppose my django app where I created this custom permission is named as: mycustomapp How will I refer/access this custom permission in has_perm() method and required_permissions attribute? I tried following for has_perm() from django.contrib.auth.models import Permission user = User.objects.all()[0] user.user_permissions.add(Permission.objects.get(name="Custom Permission")) user.save() user.has_perm("mycustomapp.user.custom_permission") But it resulted in False, instead of True, even though running user.user_permissions.all() show the newly added permission and I tried this for required_permissions attribute: class CustomView(PermissionRequiredMixin, View): required_permission = ["mycustomapp_user_custom_permission"] But it does not work and when I go to this View on front-end I get Forbidden 403 error, even though the logged in user has this required permission. Can anyone tell me how do I refer the custom made permission in has_perm() and in required_permissions. Please tell me while considering all the details exactly as I gave above in example. -
How to generate url for the s3 object without expiring?
I have uploaded an object with the client = boto3.client('s3', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY) response = client.put_object( Bucket=BUCKET_NAME, Body=in_mem_file.getvalue(), Key=str(img_name)) and I'm generating the URL by url = client.generate_presigned_url('get_object', Params={ 'Bucket': BUCKET_NAME, 'Key': str(img_name)}, ExpiresIn=518400) I need to generate the URL without expiring in some cases. Is it possible to generate url without expiring in s3 bucket? -
Cannot assign "'T Shirt for mens'": "CartProdVarient.cart_product" must be a "CartProduct" instance
Models class CartProduct(models.Model): cart_product_name = models.CharField(max_length=200) cart_holder = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.cart_product class CartProdVarient(models.Model): cart_product = models.ForeignKey(CartProduct, on_delete=models.CASCADE) cart_prod_varient = models.CharField(max_length=200) def __str__(self): return self.cart_prod_varient Views def add_cart(request): prod = Product.objects.get(id=request.POST.get('product_id')) CartProdVarient(cart_product=prod.product_name).save() return render(request, 'app/service-page.html') Problem i want to assign some value to "cart_product" while its a Foreign key but it giving me error.. i want something like this : CartProdVarient(cart_product="T-Shirt", cart_prod_varient="small size").save() T-Shirt is already in "cart_product_name" -
How to add frontend to my backend project (django - Flutter)
how to add frontend (Flutter) to my back this is my backend the project is my django project and store is my django app backend -
CSRF-token error in django+nginx+gunicorn in docker
I have a problem with CSRF-token error in django+nginx+gunicorn in docker: Origin checking failed - http://185.255.132.54:5000 does not match any trusted origins. Such problem on live production server and this problem with dev local server: Forbidden (403) CSRF verification failed. Request aborted. This error appears only with NGINX port (any POST form, login page too (example.com/admin) (5000 for production and 8001 on dev server), but it's ok on gunicorn port (no static). I read some that I have to add CSRF_TRUSTED_ORIGINS = ['http://185.255.132.54:5000', 'http://185.255.132.54', 'https://185.255.132.54:5000'] to production server, but it didn't help. Here's my code: https://github.com/endlessnights/DjangoDockerNginxSample (all files, included Dockerfile, docker-compose, project files etc are there) What have I to do with such problem? -
Django admin get value of selected date range in filter
I wanted to get value of selected date range (from_date, to_date) in Django admin. Here is sample code. list_filter = (('last_login', filters.MyDateTimeFilter),) class MyDateTimeFilter(DateFieldListFilter): title = 'date filter' parameter_name = 'date_range_filter' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def queryset(self, request, queryset): print(queryset.GET.get('date_range_filter')) return queryset -
TabularInline for through Model not showing on Django 3
First off, I am using Django 3.2.9. Here are my models, pretty straightforward: class AChallenge(models.Model): name = models.CharField(max_length=255, unique=True) class SubAdvanced(models.Model): name: str = models.CharField(max_length=255, unique=True) challenges = models.ManyToManyField( AChallenge, related_name = 'challenge', through='SubAdvancedChallenge') class SubAdvancedChallenge(models.Model): sub_advanced = models.ForeignKey( SubAdvanced, on_delete=models.CASCADE) challenge = models.ForeignKey( AChallenge, on_delete=models.CASCADE) percentage = models.FloatField( validators=[MinValueValidator(0), MaxValueValidator(1)]) Here is my admin : class SubAdvancedChallengeInline(admin.TabularInline): model = SubAdvancedChallenge extra = 1 class SubAdvancedAdmin(BelleEmpreinteAdmin): inlines = (SubAdvancedChallengeInline,) admin.site.register(SubAdvanced, SubAdvancedAdmin) According to every single tutorial I see on the internet, I should be getting a nice inline editor like this: Despite all this, I am only getting this: If I try to force the inclusion of the "challenges" field, like this: class SubAdvancedAdmin(BelleEmpreinteAdmin): fields = ("name", "challenges") inlines = (SubAdvancedChallengeInline,) I will get the following error: (admin.E013) The value of 'fields' cannot include the ManyToManyField 'challenges', because that field manually specifies a relationship model. The fact that my TabularInline simply does not appear definitely seems like a bug, but it seems too crazy that this slipped through the cracks for so long. Anybody else met this issue? -
Model a 6-digit numeric postal code in django
I would like to define a 6-digit numeric postal code in Django models.py. At first, I tried this; postal_code = models.PositiveIntegerField(blank=False) However, postal codes can have leading zeros such as 000157. PositiveIntegerField is not suitable for it. If I use CharField, the field can accept alphabets which are not valid for postal codes. How do I define a 6-digit numeric postal code in django models.py? I am using Django v4. -
pyreadstat expected str, bytes or os.PathLike object, not InMemoryUploadedFile
Trying to make endpoint that can read uploaded .sav (SPSS) file and create model with data from it. For getting data from it I'm using pyreadstat library. But now when I'm trying to run it I have an error expected str, bytes or os.PathLike object, not InMemoryUploadedFile How I can change this code so pyreadstat can correctly read the given file? from rest_framework import generics, status import pandas as pd import pyreadstat from rest_framework.response import Response from .models import Research, Data from .serializers import FileUploadSerializer, SaveFileSerializer class UploadFileView(generics.CreateAPIView): serializer_class = FileUploadSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) file = serializer.validated_data['file'] df, meta = pyreadstat.read_sav(file, user_missing=True) json_df = df.to_json(orient='table') rsch = Research.objects.get(pk=1) Data.objects.create(research=rsch, data={}) -
How to define positive integer field that accepts 6 digits only in Django?
I want to define a database field in models.py that accepts only 6 digits in Django. This is how I define the field in models.py but it can accept any positive integer; six_digit_code = models.PositiveIntegerField(blank=False) I am using Django v4. -
How can i send my template values to database using Jquery, Ajax in django?
1.jquery $(textbox).on('click','.save',function(e){ e.preventDefault(); var x = $('#input_msg').val(); $.ajax({ url:'newpostx/', type: $(this).attr('method'), data: x, headers:{ 'X-CSRFToken':'{{csrf_token}}' } }).done(function(msg) { document.location = "http://127.0.0.1:8000/newpostx/" alert("save data") }).fail(function(err){ alert('no data was saved') }) }); home.html $(container).on('click','.show', function () { //On click of link, textbox will open console.log(count[1]) msg_bubble = 1; $("div.popup").show(); var num = $(this).attr('value'); console.log(num,'num') $(textbox).append('Grid No_ '+ num +'Bot MessagesType any text here Add Message BubbleSelect InputText InputButtonsStar RatingsCalendar & TimeImage/File InputSelect User Input: Name -->Type Input:File UploadTake PhotoFile Upload & Take PhotoButton Add ButtonNumber of stars:345Steps in stars:0.51Type Input:NameFull NameEmailMobilePasswordCustom TextCalendarData Limitation TypeAbsolute DateRelative DateMin DateMax DateTimeAppointment Duration15 minutes30 minutes1 hour2 hourStart Time09:00 AM10:00 AM11:00 AM12:00 AMEnd Time09:00 AM10:00 AM11:00 AM12:00 AMCancelSave') $("#input_msg").val() $("#input_msg"+num).text(window.localStorage.getItem(key+num)) console.log(count[num-1]) for(var i=2; iType any text here'); $(".container_inside").append(structure); $("#add_msg_"+num+i).text(window.localStorage.getItem(num+i)); } }); 3.views.py def post_new(request): if request.method == "POST": new_poll= text() #call model object d= request.POST new_poll.message= d['message'] new_poll.save() print(new_poll) return render(request, "loggedin.html") 4.models.py class text(models.Model): message = models.TextField(max_length=250) time = models.DateTimeField(default=datetime.now) 5.urls.py path('newpostx/',views.post_new,name='post_new'), -
"Error: Couldn't find that app. › › Error ID: not_found." when running heroku commands in console
Heroku sees my app in the list of apps, but I can't access it with any commands. I constantly getting the error "Couldn't find that app". I tried all these: heroku run python manage.py migrate -app my-api heroku run python manage.py migrate heroku run python manage.py createsuperuser -app my-api Although when I try to run commands for 'heroku apps' in my console, says I have one app called my-api. I followed other similar questions and tried the git remote commands beforehand but still failed. Example: heroku apps heroku git:remote -app my-api -
"Failed building wheel for psycopg2==2.8.6" - MacOSX using virtualenv and pip
I need install psycopg2==2.8.6 because when I installed latest version I get UTC error. I solve UTC error with install psycopg2==2.8.6 in my manjaro os but i try install this in my macOS and i got this: ld: warning: directory not found for option '-L/usr/local/opt/openssl/lib/' ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command '/usr/bin/clang' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for psycopg2 -
Django DetailView page - inline formset not saved in SQL
I am trying to implement Django inline formset to my DetailView. According to documentation it is much better to separate Detail and Form views and bring them back together in the third view and this is what I did. My form is visible in my template file but after submission, nothing happens. It is returning correctly to my product detail view but no data is saved to SQL. Can you please let me know what am I doing wrong? models.py class Product(models.Model): title = models.CharField('title', max_length=400, blank=False, null=False, help_text='max 400 characters', default='') class CERequest(models.Model): author = models.CharField(max_length=255, blank=True, null=True) related_component = models.ForeignKey(CostCalculator, on_delete=models.CASCADE, blank=True, null=True, default=1) number_of_units = models.IntegerField(default=0) related_product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True, related_name='related_product_ce_request') created = models.DateTimeField(default=timezone.now) total_price = models.IntegerField(verbose_name='Price (€)', default=0, blank=True, null=True) forms.py class CalculatorFormProduct(forms.ModelForm): author = forms.CharField(widget = forms.HiddenInput(), required = False) number_of_units = forms.IntegerField(help_text='Only numeric values are allowed.', min_value=0) total_price = forms.IntegerField(widget = forms.HiddenInput(), required = False) created = forms.DateTimeField(widget = forms.HiddenInput(), required = False) class Meta: model = CERequest fields = ('author', 'created', 'related_product', 'related_component', 'number_of_units') CalculatorFormsetProduct = inlineformset_factory(Product, CERequest, form=CalculatorFormProduct, fields=('author', 'related_product', 'related_component', 'created', 'number_of_units'), extra=3, can_delete=False) views.py class ProductView(LoginRequiredMixin, DetailView): model = Product template_name = 'hubble/ProductDetailView.html' def get_success_url(self): return reverse('product', kwargs={'slug': … -
how can i py my icons in my webapp in a better position?
i'm working with django-python making a webapp, but i have a problem, i have 4 icon in my first row and two icons under them, the problem is, above the lower icons are attached to the upper icons, this is the home.html file: {% extends 'dashboard/base.html' %} {% load static %} {% block content %} <section class="container text-center"> <h3>Welcome</h3> <hr> <br> <div class="row"> <div class="col-md-3"> <a href="{% url 'notes' %}"> <div class="card"> <img class="card-img-top" src="{% static 'images/notes.jpg' %}" alt="Notes image"> <div class="card-body"> <h5 class="card-title "> Notes </h5> Create Notes to refer them later. They are stored permanently until deleted </div> </div> </a> </div> <div class="col-md-3"> <a href="{% url 'homework' %}"> <div class="card"> <img class="card-img-top" src="{% static 'images/homework.jpg' %}" alt="Notes image"> <div class="card-body"> <h5 class="card-title "> Homework </h5> Add homeworks and assign them deadlines. They will be displayed prioritised by deadlines </div> </div> </a> </div> <div class="col-md-3"> <a href="{% url 'youtube' %}"> <div class="card"> <img class="card-img-top" src="{% static 'images/youtube.jpg' %}" alt="Notes image"> <div class="card-body"> <h5 class="card-title "> Youtube </h5> Search Youtube and select your desired video to play it on youtube </div> </div> </a> </div> <div class="col-md-3"> <a href="{% url 'todo' %}"> <div class="card"> <img class="card-img-top" src="{% static 'images/todo.jpg' %}" alt="Notes … -
How to fix FileNotFoundError: [Errno 2] No such file or directory:? (HEROKU)
I am trying to push my Django + React app to heroku. I have configured the path for my static files at below in settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'app/laundryman_frontend/build/static') ] The build is successful when I push to heroku but when I run heroku run python manage.py collectstatic I get the error FileNotFoundError: [Errno 2] No such file or directory: '/app/laundryman_frontend/build/static' My guess is that, Heroku is not looking does not recognise the path that I have set for the static files. Kindly help me solve this issue -
How to run parallel tasking with celery django?
I am looking to run tasks in parallel with django celery. Let's say the following task: @shared_task(bind=True) def loop_task(self): for i in range(10): time.sleep(1) print(i) return "done" Each time a view is loaded then this task must be executed : def view(request): loop_task.delay() My problem is that I want to run this task multiple times without a queue system in parallel mode. Each time a user goes to a view, there should be no queue to wait for a previous task to finish Here is the celery command I use : celery -A toolbox.celery worker --pool=solo -l info -n my_worker1 -------------- celery@my_worker1 v5.2.7 (dawn-chorus) --- ***** ----- -- ******* ---- Windows-10-10.0.22000-SP0 2022-08-01 10:22:52 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: toolbox:0x1fefe7286a0 - ** ---------- .> transport: redis://127.0.0.1:6379// - ** ---------- .> results: - *** --- * --- .> concurrency: 8 (solo) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery I have already tried the solutions found here but none of them seem to do what I ask StackOverflow : Executing two tasks at the same time with … -
Matching data from two functions in django context?
I'm struggling with matching contexts in my django project. I want to insert a .annotate() queryset, perfectly in just a set variable. I know it sounds weird but it's the best as I can describe it. I tried using .filter(), as it makes sense to me logically, but it doesn't quite work. my views.py from django.shortcuts import render from django.db.models import Count from django.db.models import Sum from .models import Offer_general from .models import Offer_details import datetime # Create your views here. def offer_general_list(request): #queryset = Offer_general.objects.filter(status=1).order_by('-id') context = {} context["data"] = Offer_general.objects.filter(status=1).order_by('-id')#stuff from Offer_general context["test"] = Offer_details.objects.values('fk_offer_general_id').annotate(sum=Sum('fk_offer_general_id')) return render(request, "index_offers.html", context) def offer_general_details(request): context = {} context["data"] = Offer_details.objects.all() return render(request, "offer_detail.html", context) models.py from django.db import models from django.contrib.auth.models import User from django.db.models import Count STATUS = ( (0,"Inactive"), (1,"Active") ) class Offer_type(models.Model): type = models.TextField() class Meta: ordering = ['-type'] def __str__(self): return self.type class Offer_general(models.Model): offer_name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) status = models.IntegerField(choices=STATUS, default=0) type = models.ForeignKey(Offer_type, on_delete= models.PROTECT) class Meta: ordering = ['-id'] def __str__(self): return self.offer_name class Offer_localization(models.Model): localization = models.TextField() class Meta: ordering = ['-localization'] def __str__(self): return self.localization class Offer_details(models.Model): slug = models.SlugField(max_length=200, unique=True) localization = models.ForeignKey(Offer_localization, on_delete= models.PROTECT, default="Opole") … -
Getting TypeError: Form.__init__() missing 1 required positional argument: ‘request’ even though I have passed request in both GET and POST methods
I have a form, which I am initializing its field with some data passing to it from view in its __init__() method to be shown on front end, using HttpRequest object. Even though, I have passed the HttpRequest object named request in both GET and POST methods, I am still getting the following error on POST request: TypeError at /accounts/invite-user/cancel/ InviteUserCancelForm.__init__() missing 1 required positional argument: 'request' Error full details are: Traceback Switch to copy-and-paste view D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\handlers\exception.py, line 55, in inner response = get_response(request) … Local vars D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\handlers\base.py, line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … Local vars D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\views\generic\base.py, line 84, in view return self.dispatch(request, *args, **kwargs) … Local vars D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\contrib\auth\mixins.py, line 73, in dispatch return super().dispatch(request, *args, **kwargs) … Local vars D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\contrib\auth\mixins.py, line 109, in dispatch return super().dispatch(request, *args, **kwargs) … Local vars D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\views\generic\base.py, line 119, in dispatch return handler(request, *args, **kwargs) … Local vars D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\views\generic\edit.py, line 151, in post form = self.get_form() … Local vars D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\views\generic\edit.py, line 39, in get_form return form_class(**self.get_form_kwargs()) … My forms.py is: class InviteUserCancelForm(forms.Form): invitations = forms.ChoiceField( widget=forms.RadioSelect, choices=(('test_invite','test_invite'),) ) def __init__(self, request: HttpRequest, *args, **kwargs): super (InviteUserCancelForm, self).__init__(*args, **kwargs) if "invitations" in args: self.fields['invitations'] = forms.ChoiceField( label="Your Invitations", widget=forms.RadioSelect, choices=request["invitations"] ) … -
Django ValueError when A field is empty
i have a ModelForm which is like this : Forms.py : class send_to_evaluatorForm(forms.ModelForm): class Meta: model = send_to_evaluator exclude = ('Creater_UserID','mozo1_id','mozo2_id','mozo3_id','knowledge') so the problem comes when i leave a field empty and submit to save it... but when everything is filled and nothin left empty the code runs ok. a part of my view : if request.method == "POST": form = send_to_evaluatorForm(request.POST) mozo3=request.POST.get('mozo3') mozo1=request.POST.get('mozo1') mozo2=request.POST.get('mozo2') if form.is_valid: obj = form.save() the error happens because the form doesnt validate and while i was debugging it i noticed that a field is required here is my model if you want to have a look...if i let nazar empty my form doesnt save it models.py: mozo1_id = ForeignKey(topic1,on_delete=models.PROTECT,blank=True, null=True) mozo2_id = ForeignKey(topic2,on_delete=models.PROTECT,blank=True, null=True) mozo3_id = ForeignKey(topic3,on_delete=models.PROTECT,blank=True, null=True) nazar = TextField(verbose_name='point_of_view',max_length=4000) create_date = IntegerField(default=LibAPADateTime.get_persian_date_normalized(), blank=True, null=True) Creater_UserID = ForeignKey(Members,on_delete=models.PROTECT,blank=True, null=True) knowledge = ForeignKey(TblKnowledge,on_delete=models.PROTECT,blank=True, null=True) def __str__(self): return str(self.id)