Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is Django serializer escaping characters to protect from xss attack?
I use a serializer to process the data comming from the frontend. The data is basically a username, email and password. The data will be saved in a database and the username will be displayed in the frontend later on. I am wondering if the serializer is already escaping " and < characters to protect from xss-attacks. If it isn't, is there a simple way to configure the serializer to do so? My serializer looks like that: # Register Serializer class RegisterSerializer(serializers.ModelSerializer): profile = ProfileSerializer(required=True) class Meta: model = User fields = ('id', 'username', 'email', 'password', 'profile') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user( username=validated_data['username'], email=validated_data['email'], password=validated_data['password'] ) profile_data = validated_data.pop('profile') user.profile.company_name = profile_data['company_name'] user.is_active = False user.save() return user -
django-filebrowser-no-grappelli - problem with AzureStorage
I installed django-filebrowser-no-grappelli and added AzureBlobStorageMixin from django-filebrowser-no-grappelli2, link here. The problem is that I cannot create any folder and upload any image through admin panel. I get this error: This backend doesn't support absolute paths. When I try to create new folder I get: 'AzureMediaStorage' object has no attribute 'service' Below is the code with class AzureBlobStorageMixin(StorageMixin): storage_type = 'azure' def sys_file(self): return 'dir.azr' def isdir(self, name): """ Returns true if name exists and is a directory. """ if name.endswith('/'): return True result = self.listdir(name) # if name contains dirs (result[0]) or files (result[1]) its a directory return len(result[0]) > 0 or len(result[1]) > 0 def isfile(self, name): """ Returns true if name exists and is a regular file. """ return self.exists(name) def listdir(self, path=''): files = [] dirs = [] path_parts = path.split('/') # remove blank parts of path if path_parts[-1] == '': path_parts = path_parts[:-1] for name in self.list_all(path): name_parts = name.split('/') # check dir level of files if len(name_parts) == len(path_parts) + 1: files.append(name_parts[-1]) # check dir level of dirs elif len(name_parts) == len(path_parts) + 2: if name_parts[-2] not in dirs: dirs.append(name_parts[-2]) else: pass return dirs, files def path(self, name): """ Azure storage doesn't support Python's … -
How to NOT "double-encode" UTF-8 strings in a custom Django lookup (rhs)
Suppose the following custom Django lookup: from django.db import models class WebSearch(models.Lookup): lookup_name = 'websearch' def as_postgresql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = lhs_params + rhs_params return """to_tsvector('french', (%s)) @@ websearch_to_tsquery('french', (%s))""" % (lhs, rhs), params Now, querying a model TextField like so: MyModel.objects.filter(sometextfield__websearch='sautée') results in the following SQL: SELECT * FROM mymodel WHERE to_tsvector('french', ("sometextfield")) @@ websearch_to_tsquery('french', ('"saut\\u00e9e"')) which added double quotes around rhs, changing the semantics of websearch_to_tsquery encoded the UTF-8 character in a weird way while Postgres CLI (psql) seems to support just straight up querying like so: SELECT * FROM mymodel WHERE to_tsvector('french', "sometextfield") @@ websearch_to_tsquery('french', 'sautée'); How would one disable all that string encoding business, so that "sautée" would just come out as "sautée"? -
How to display property method as a message in class based view?
I have a property method defined inside my django model which represents an id. status_choice = [("Pending","Pending"), ("In progress", "In progress") ,("Fixed","Fixed"),("Not Fixed","Not Fixed")] class Bug(models.Model): name = models.CharField(max_length=200, blank= False, null= False) info = models.TextField() status = models.CharField(max_length=25, choices=status_choice, default="Pending") assigned_to = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.CASCADE, related_name='assigned', null = True, blank=True) phn_number = PhoneNumberField() uploaded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.CASCADE, related_name='user_name') created_at = models.DateTimeField(auto_now_add= True) updated_at = models.DateTimeField(blank= True, null = True) updated_by = models.CharField(max_length=20, blank= True) screeenshot = models.ImageField(upload_to='pics') @property def bug_id(self): bugid = "BUG{:03d}".format(self.id) return bugid What I wanted is I need to show this id as a message after an object is created. corresponding views.py file. class BugUpload(LoginRequiredMixin, generic.CreateView): login_url = 'Login' model = Bug form_class = UploadForm template_name = 'upload.html' success_url = reverse_lazy('index') def form_valid(self, form): form.instance.uploaded_by = self.request.user return super().form_valid(form) -
How to get list of users by passing permissions and roles string in Django
I searched many links over here. I don't know how to write the above functionality using Django. I wanted to list all the user by permissions or roles in Django. Read many blogs and we have option to get the list of permission or roles assigned to the user and not vice versa. Let me know the other options to get the same. -
drf_yasg: How to add square backets in TYPE_ARRAY parameters when request from swagger ui
I have custom field in request body: receipt_details_schema = openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'bonus_restrict': openapi.Schema( title='bonus_restrict', type=openapi.TYPE_INTEGER ), 'prod_cat': openapi.Schema( title='prod_cat', type=openapi.TYPE_INTEGER ), 'prod_code': openapi.Schema( title='prod_code', type=openapi.TYPE_INTEGER ), 'prod_name': openapi.Schema( title='prod_name', type=openapi.TYPE_STRING ), 'prod_price': openapi.Schema( title='prod_price', type=openapi.TYPE_INTEGER ), 'prod_amount': openapi.Schema( title='prod_amount', type=openapi.TYPE_INTEGER ), 'prod_sum': openapi.Schema( title='prod_sum', type=openapi.TYPE_INTEGER ), 'position': openapi.Schema( title='position', type=openapi.TYPE_INTEGER ), }, required=['prod_code', 'prod_price', 'prod_amount', 'prod_sum', 'position'], ) receipt_details_field = openapi.Parameter( name='receipt_details', in_=openapi.IN_FORM, description="receipt_details field", type=openapi.TYPE_ARRAY, items=receipt_details_schema # schema=receipt_details_schema, ) @swagger_auto_schema(manual_parameters=[receipt_details_field]) def post(self, request, **kwargs): and when trying request from swagger ui with header(x-www-urlencoded), i get data field whithout square backet. How i can add it with objects when requesting? enter image description here enter image description here I check drf_yasg documentation and not find answer for my quetion. I'm beginner in drf, dont scold me. -
Why is it not redirected when the payment is successful? using django and braintree dropin-ui
I use this sandbox for the payment section of the store site. I want to redirect the user to page Done after successful payment, but the current page is loaded again! pealse help view of payment_process: def payment_process(request): order_id = request.session.get('order_id') order = get_object_or_404(Order, id=order_id) total_cost = order.get_total_cost() if request.method == 'POST': nonce = request.POST.get('paymentMethodNonce', None) result = gateway.transaction.sale({ 'amount': f'{total_cost:.2f}', 'payment_method_nonce': nonce, 'options': { 'submit_for_settlement': True } }) if result.is_success: order.paid = True order.braintree_id = result.transaction.id order.save() return redirect('payment:done') else: return redirect('payment:canceled') else: client_token = gateway.client_token.generate() return render(request, 'payment/process.html', {'order': order, 'client_token': client_token}) page of Done.html: {% extends "shop/base.html" %} {% block title %} Pay by credit card {% endblock %} {% block sidenavigation %} {% endblock %} {% block content %} <h1>Pay by credit card</h1> <!-- includes the Braintree JS client SDK --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script src="https://js.braintreegateway.com/web/dropin/1.14.1/js/dropin.min.js"></script> <form method="post" autocomplete="off"> {% if braintree_error %} <div class="alert alert-danger fade in"> <button class="close" data-dismiss="alert">&times;</button> {{ braintree_error|safe }} </div> {% endif %} <div class="braintree-notifications"></div> <div id="braintree-dropin"></div> <input style="background-color: #0783ca" id="submit-button" class="btn btn-success btn-lg btn-block" type="button" value="Pay now!"/> </form> <script> var braintree_client_token = "{{ client_token}}"; var button = document.querySelector('#submit-button'); braintree.dropin.create({ authorization: "{{client_token}}", container: '#braintree-dropin', card: { cardholderName: { required: false } } … -
django project : An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block
Slut everyone, in this django project I'm trying to save or update my database with data from an API.Here is the structure of my models models.py def A(models.Model): number=models.CharField(max_length=50,blank=True,null=True,unique=True) sayfa=CharField(max_length=100,blank=True,null=True) def B(models.Model): link=models.ForeignKey(A, on_delete=models.CASCADE) adress=models.CharField(max_length=255,blank=True,null=True) in this specific case, each element of A can contain several rows of B. And as the data comes from an API, I would like to save it at my database level and if the element exists it updates it views.py def test(request): url='http://myapi/data' x=requests.get(url) contenu=x.json() all_data=content['data'] for my_data in all_data: bv, _ = B.objects.update_or_create(adress=my_data['adress']) bv.save() mala=B.objects.all() context={'data':mala} return render(request,'account/list.html',context) when executing i get the error (An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.) Here each row of A can have several rows at table B. -
Accessing Mailman 3 list members via Python/Django management console
I am trying to access members of an existing Mailman 3 mailing list directly from Django Management console on a Debian Bullseye where Mailman is installed from deb packages (mailman3-full). I can connect to the Django admin console like this (all 3 variants seem to work fine): $ /usr/share/mailman3-web/manage.py shell $ mailman-web shell $ mailman-web shell --settings /etc/mailman3/mailman-web.py Python 3.9.2 (default, Feb 28 2021, 17:03:44) >>> But inside the Django admin console, some mailman components seem to be missing. I try to access the list manager as described here: Docs > Models > The mailing list manager: >>> from mailman.interfaces.listmanager import IListManager >>> from zope.component import getUtility >>> list_manager = getUtility(IListManager) Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/lib/python3/dist-packages/zope/component/_api.py", line 169, in getUtility raise ComponentLookupError(interface, name) zope.interface.interfaces.ComponentLookupError: (<InterfaceClass mailman.interfaces.listmanager.IListManager>, '') Can't figure out why this ComponentLookupError happens. Also tried to acccess a list with the ListManager implementation: >>> from mailman.config import config >>> from mailman.model.listmanager import ListManager >>> list_manager = ListManager() >>> list_manager.get('mynews@example.com') Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/lib/python3/dist-packages/mailman/database/transaction.py", line 85, in wrapper return function(args[0], config.db.store, *args[1:], **kws) AttributeError: 'NoneType' object has no attribute 'store' >>> list_manager.get_by_list_id('mynews.example.com') Traceback … -
How i can fix Cannot resolve keyword 'pub-date' into field. Choices are: choice, id, pub_date, question_text
Python django when I starting local sever, I met only Cannot resolve keyword 'pub-date' into field. Choices are: choice, id, pub_date, question_text how can i fix? window error at first the problem was about direcotry, so read and search about django slash document. and then i ment a new problem rn.. -
Django orm "annotate" not working with "only"
I want to select only one column with "only" and rename it. The code I want in SQLServer is as follows: SELECT [table].[col1] AS [new_col1] FROM [table] in django orm: model.objects.annotate(new_col1=F('col1').only('col1')).all() When i change it to sql query it is like this: SELECT [table].[col1], [table].[col1] AS [new_col1] FROM [table] and below orm code not working: model.objects.annotate(new_col1=F('col1').only('new_col1')).all() I don't want to use "vales" or "values_list". Please help me how I can do it. -
Moving tables data from sqlite3 to postgressql
What is the simplest way to move data from sqlite3 tables to posgressql in Django project -
Print web application pages in pdf django
I am new in this field and currently learning Django and have pseudo project... I want to print in pdf my app pages which are represented as a group of tabs (5 tabs in total) with its own views/urls. Tab 2, 3, 4, 5 contents are related models of tab 1. I have looked to several tutorials about ReportLab also doing print() button set-up directly from browser side and I am able to print my 1st tab content successfully. I am wondering if there is any example to combine printing all related model tabs i.e. 2, 3, 4, 5 when I am printing 1st tab content? Similar like placing button on listview to print all data together from there? thanks in advance. -
Django - display an error message when form is invalid with "CreateView"
Here is my simplified "ProjectCreate" ClassBasedView : class ProjectForm(forms.ModelForm): class Meta: model = Project fields = ['name', 'creation_date', 'price'] class ProjectCreate(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = Project form_class = ProjectForm success_message = "Project successfully created" success_url = "project-list" def get_form(self, form_class=None): form = super(ProjectCreate, self).get_form(form_class) form.fields.pop('creation_date') return form def form_valid(self, form): if form.instance.name == "not_valid_name": return super().form_invalid(form) form.instance.last_editor = self.request.user form.instance.last_modification_date = datetime.datetime.now() return super().form_valid(form) I want to create the project only if the name isn't "not_valid_name" If the name is "not_valid_name", i want to display an error message (saying that the name isn't valid), and bring back the user to the 'project create' page If you need any additional informations to understand my problem, don't hesitate to ask me. Thanks :) -
error: dictionary changed size during iteration
I am trying to convert a model instance to a dictionary with the function "model_to_dict" from django.forms.models but im getting the error: dictionary changed size during iteration. obj_list = [] object_qs = Model.objects.all() for obj in object_qs: obj_list.append(model_to_dict(obj)) I don’t understand what’s happening and how do i achieve the desired result? -
django.db.utils.IntegrityError: (1062, "Duplicate entry '8d4d1c76950748619f93ee2bfffc7de5' for key 'request_id'")
I don't understand what kind of error is ? sometimes this code works and after 1-2 times submitting form then trying to submit form again with different details then i got this error, django.db.utils.IntegrityError: (1062, "Duplicate entry '8d4d1c76950748619f93ee2bfffc7de5' for key 'request_id'") Here this is my views.py code @api_view(['POST', 'GET']) def add_info_view(request): if request.method == 'POST': form = GitInfoForm(request.POST) if form.is_valid(): form.save() try: git_Id = form.cleaned_data['git_Id'] s = Gitinformation.objects.filter(git_Id=git_Id).values('request_id') print('Value of S :', s[0]['request_id']) s = s[0]['request_id'] approve_url = f"http://127.0.0.1:8000/Approve/?request_id={str(s)}" print("Url : ", approve_url) try: send_mail( 'KSA Test Activation', approve_url, 'Noreplygcontrol@airlinq.com', ['sorav.parmar@airlinq.com'], fail_silently=False, ) request.session['approve_url'] = approve_url print('Approve Url sent : ', approve_url) except Exception as e: pass except Exception as e: pass form = GitInfoForm() form = GitInfoForm() return render(request, 'requestApp/addInfo.html', {'form': form}) How to getrid of this error, please help me. -
How to renderer reacj jsx file in django render without using api
I want to find a way to render react jsx instead of rendered plain html without using api or using indirect html method in django -
What fieldtype of Django model should I choose to store encrypted data?
I am working on a project the requirement is to store some encrypted data in the database. What is the preferred fieldtype of Django model for storing encrypted data? I am currently using CharField, however, I am not sure if this is the best approach. Also, should BinaryField be an option? -
Get product color in color filter by Category wise
I am trying to get a specific category products by category slug.I have Color model,Product model and product variation model in shop app. class Colour(models.Model): title = models.CharField(max_length=100) color_code = models.CharField(max_length=50,null=True) class Product(models.Model): product_name = models.CharField(max_length=100,unique=True) slug = models.SlugField(max_length=100,unique=True) content = RichTextUploadingField() price = models.IntegerField() images = models.ImageField(upload_to='photos/products') is_available = models.BooleanField(default=True) category = models.ForeignKey(Category, on_delete=models.CASCADE,related_name="procat") created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) is_featured = models.BooleanField() class ProductVaraiant(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE) color = models.ForeignKey(Colour,on_delete=models.CASCADE,blank=True, null=True) size = models.ForeignKey(Size, on_delete=models.CASCADE,blank=True, null=True) brand = models.ForeignKey(Brand,on_delete=models.CASCADE,blank=True, null=True) amount_in_stock = models.IntegerField() class Meta: constraints = [ models.UniqueConstraint( fields=['product', 'color', 'size','brand'], name='unique_prod_color_size_combo' In my views.py, def shop(request,category_slug=None): categories = None products = None if category_slug != None: categories = get_object_or_404(Category,slug = category_slug) products = Product.objects.filter(category=categories,is_available=True).order_by('id') variation = ProductVaraiant.objects.filter(product__category = categories) print(variation) # color = color.objects.all() products_count = products.count() else: products = Product.objects.all().filter(is_available=True).order_by('id') products_count = products.count() variation = ProductVaraiant.objects.all() print(variation) context = { 'products' : products, 'products_count' : products_count, 'variation' : variation } return render(request,'shop/shop.html',context) my category model, class Category(MPTTModel): parent = TreeForeignKey('self',blank=True,null=True,related_name='children',on_delete=models.CASCADE) category_name = models.CharField(max_length=200,unique=True) category_img = models.ImageField(upload_to='photos/categories',blank=True) slug = models.SlugField(max_length=100,unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def img_preview(self): return mark_safe('<img src = "{url}" width = "50" height = "50"/>'.format( url = self.category_img.url )) def __str__(self): return … -
The scheduler seems to be running under uWSGI, but threads have disabled.You must run uWSGI with the --enable-threads option for the scheduler to work
I'm deploying django app to pythonanywhere where i used APScheduler for automatically send expire mail whenever subscription end date exceed. I don't know how to enable threads, so that my web app runs perfectly on pythonanywhere. -
Comparing Django project structure to ruby on rails
After some years developing web apps using ruby on rails, I decided to give Django a try, however it seems that I'm missing something, which is how to structure large project, or any project in general. For example, in rails we have a models folder which contains model classes, each in a separate ruby file, a controllers folder which contains controller classes, again each in a separate ruby file. However, in Django it split the project into independent apps, which can be installed independently in other Django project, each app has a models.py file which contains all the models classes, a views.py file which contain all the views functions. But then how to group functions in views like rails? That is one controller per each model. In general how to structure my project when it contains one large app that can't be separated into multiple independent apps? I want for example to have a view index function for each model, but how to do this if all functions are in one file? If my project is about selling cars for example. I should have index function that maps to /cars, another index function to map to /users, etc... I searched … -
Import models from different apps to admin Django
I'm trying to create an admin page for my project including app1 and app2 myproject settings.py urls.py admin.py app1 app2 In myproject/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('app1/', include('app1.urls')), path('app2/', include('app2.urls')), ] In myproject/admin.py from django.contrib import admin from app1.models import User from app2.models import Manager, Employee, Task, Template admin.site.register(User) admin.site.register(Manager) admin.site.register(Employee) admin.site.register(Task) admin.site.register(Template) Why doesn't my admin page import any models at all? Thanks! -
Cache Auto Generated Django Admin Routes
I want to cache the sql queries result in Redis DB in the django admin.AdminSite autogenerated for registered admin.ModelAdmin's I am able to cache a custom url using cache_page and add it to CustomAdminSite I have installed Django debug toolbar to view cache requests. The custom url is getting cached. I am unable to cache other auto generated admin routes. Would it be possible to cache auto generated admin routes too? -
convert python/django built-in class "calendar" to local calendar (Persian)
I created a html calendar using built-in calendar class in Django , now I have to convert it to local calendar "Persian", I tried using django-jalali-date package but couldn't get success result . and another issue is prevmonth and next month buttons which redirect user to not found page. please advice how to handle those issues in utils.py: class Calendar(HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(time_start__day=day) d = '' for event in events_per_day: d += f'<li> {event.title} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, events) return f'<tr> {week} </tr>' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): events = tb_order.objects.filter(time_start__year=self.year, time_start__month=self.month) cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n' cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' cal += f'{self.formatweekheader()}\n' for week in self.monthdays2calendar(self.year, self.month): cal += f'{self.formatweek(week, events)}\n' return cal in Urls: path('testcal/',views.CalendarView.as_view(),name="cal"), in views.py : class CalendarView(generic.ListView): model = tb_order template_name … -
Why parentheses are not used with function in html template when model method is called in django?
I would like to know while in html templating process why model method does not use parentheses like normally we use it in views and it is being called direcly like varible e.g. class Main(models.Model): value=models.BigIntegerField(null=True, blank=True) #Model field variable = 505 # model variable def fun(self): return True # model function (method) The html template {% extends 'base.html' %} {% block content %} {{user.main.value}} it's value <br> {{user.main.fun}} it's function (why no parentheses here like user.main.fun()) <br> {{user.main.variable}} it's variable <br> {% endblock %} If this question is not good then tell me to delete but please do not down vote.Thank You.