Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create multiple objects in one form Django
I am trying to create a form in Django that can create one Student object with two Contact objects in the same form. The second Contact object must be optional to fill in (not required). Schematic view of the objects created in the single form: Contact 1 Student < Contact 2 (not required) I have the following models in models.py: class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Student(models.Model): ACCOUNT_STATUS_CHOICES = ( ('A', 'Active'), ('S', 'Suspended'), ('D', 'Deactivated'), ) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) year = models.ForeignKey(Year, on_delete=models.SET_NULL, null=True) school = models.ForeignKey(School, on_delete=models.SET_NULL, null=True) student_email = models.EmailField() # named student_email because email conflicts with user email account_status = models.CharField(max_length=1, choices=ACCOUNT_STATUS_CHOICES) phone_number = models.CharField(max_length=50) homework_coach = models.ForeignKey(Teacher, on_delete=models.SET_NULL, null=True, blank=True, default='') user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) plannings = models.ForeignKey(Planning, on_delete=models.SET_NULL, null=True) def __str__(self): return f"{self.first_name} {self.last_name}" class Contact(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) contact_first_name = models.CharField(max_length=50) contact_last_name = models.CharField(max_length=50) contact_phone_number = models.CharField(max_length=50) contact_email = models.EmailField() contact_street = models.CharField(max_length=100) contact_street_number = models.CharField(max_length=10) contact_zipcode = models.CharField(max_length=30) contact_city = models.CharField(max_length=100) def __str__(self): return f"{self.contact_first_name} {self.contact_last_name}" In forms.py, I have created two forms to register students and contacts. A student is also connected to a User object for login and authentication, but this is … -
AssertionError when reloading page
I am writing a human detection live streaming with Django + YOLOv5, firstly i import the video source form rtsp, then detect with run() function, then yield frame by frame. To stream, i use StreamingHttpResponse with streaming_content=run(). It seems to work fine, but when i reload the streaming page, maybe the run() is called again, if i reload too much, the fps decreases then the stream stops, with an AssertionError: cannot open rtsp... I have try some solution, use iframe on front-end,... but every time front-end show the stream, it calls StreamingHttpRespone and run() again, do you have any solution for it? def video_feed(request): return StreamingHttpResponse(streaming_content=run(), content_type='multipart/x-mixed-replace; boundary=frame') -
Encapsulating the pythonping function in DJango framework
I have been building a web app using the Django framework to allow me to ping certain IPs periodically to see if they are online. The setup of the app requires different IPs in different groups. When I have added the python ping function into my model it says that the IPs are not reachable. Below is my models.py for the project. As you can see I have included the pythonping ping function to try and ping the IPs in question, but it does not seem to work. from cgitb import text from ipaddress import ip_address from django.db import models from pythonping import ping #import macaddress # Create your models here. class WS_Building_location(models.Model): Building = models.CharField(max_length=200) #date_added = models.DateTimeField(auto_now_add =True) class Meta: verbose_name_plural = 'Buildings' def __str__(self): return self.Building class WS_address(models.Model): """Wyrestorm address""" building = models.ForeignKey(WS_Building_location, on_delete=models.CASCADE) ws_ip = models.GenericIPAddressField() #mac_address = models.macaddress() date_added = models.DateTimeField(auto_now_add=True) ipstr = str(ws_ip) ip_ping = models.TextField(ping('ipstr', verbose = False)) class Meta: verbose_name_plural = 'addresses' def __str__(self): return self.ws_ip I have read that the pythonping module needs to have root access in order to create the raw packets it uses as a ping and it is not recommended that django be root for security concerns. … -
django.template.exceptions.TemplateSyntaxError: Invalid block tag. Did you forget to register or load this tag?
I have a view that has context data and it extends base.html but as I want the context data to be displayed in all templates that extend from base.html and not only the view with the context data I am doing custom template tags with the context inside but I get an error. view with and without context data: class HomeView(ListView): model = Product context_object_name='products' template_name = 'main/home.html' paginate_by = 25 class HomeView(ListView): model = Product context_object_name='products' template_name = 'main/home.html' paginate_by = 25 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) categories = Category.objects.all() news = News.objects.all() context.update({ 'categories' : categories, 'news' : news, }) return context base.html with and without the custom tag {% news %} {% for new in news %} <p>{{ new.title }}</p> {% endfor %} The custom tag file templatetags/news.py from django import template from support.models import News register = template.Library() @register.inclusion_tag('news.html', takes_context=True) def news(context): return { 'news': News.objects.order_by("-date_posted")[0:25], } The custom tag file templatetags/news.html {% for new in news %} <p>{{ new.title }}</p> {% endfor %} -
Django class based signup view form not show up in bootstrap modal
I try to look up my signup view as a bootstrap modal but when click form doesn't show [my views.py[modal form look[index.htmlmy signup.html](https://i.stack.imgur.com/qv1BD.png)](https://i.stack.imgur.com/b7ChP.png)](https://i.stack.imgur.com/BMlaq.png) Can I figure it out without using Ajax or something else or do I have to change my signup view from class based views to something else -
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.