Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ident between django tag {%%} in vs code
I would like to indent my code between the django tags {%%}. e.g from {% for disease in diseases %} <h3 class="card flex flex--center-all grid__element">{{ disease}}</h3> {% endfor %} to this: {% for disease in diseases %} <h3 class="card flex flex--center-all grid__element">{{ disease}}</h3> {% endfor %} Unfortunately Beautify automaticly unindent, and the default formatter in vs code stick all the blocks on the same line. I tried to change the Vs code settings by creating new tags, or new brackets, or changing the way VS code indent. Nothing work. All helps are welcome. -
Generate XML from List in Python
I want to generate a XML-Scheme/XSD out of Lists. The form of the Paths is a list like so: l1 = ['Customers', 'CustomerType', 'B2B', 'Industry', 'Manufacturing', 'ManufactureOfFurniture'] l2 = ['Customers', 'CustomerType', 'B2B', 'Industry', 'Manufacturing', 'ManufactureOfJewellery'] l3 = ['Customers', 'CustomerType', 'B2C', 'Industry' ...] ... And with a dict that has all the classes to corresponding lists: schema_dict = { "c-customertype-b2b-industry-manufacturingoffurnite" : l1, "c-customertype-b2b-industry-manufacturingofjewellery": l2, ... } And out of that i want to create a XML-Schema like this: <xs:element name="customers"> <xs:complexType> <xs:sequence maxOccurs="unbounded"> <xs:element name="customertype"> <xs:complexType> <xs:sequence maxOccurs="unbounded"> <xs:element name="b2b"> <xs:complexType> <xs:sequence maxOccurs="unbounded"> <xs:element name="industry"/> <xs:complexType> <xs:sequence maxOccurs="unbounded"> <xs:element name="manufacturing" type="c-customertype-b2b-industry-manufacturing" /> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> <xs:element name="b2c"> {...} I already have the simpletypes. The Last value in path should have a typename of the simpletype. simpleTypes look like this: <xs:simpleType name="c-customertype-b2b-industry-manufacturing" final="restriction"> <xs:restriction base="xs:ENTITY"> <xs:enumeration value="cars" /> <xs:enumeration value="knifes" /> </xs:restriction> </xs:simpleType> I'm currently working with xml.etree.ElementTree to make Elements but im open for other suggestions. -
Django InvalidCursorName error when Google or Facebook crawler bots request my home page
I have been receiving InvalidCursorName error for a while in my django website and the HTTP_USER_AGENT shows Facebook or Google bots: for example when i mention my website domain in a comment i received this error immediately. Migrations are all done and i have run the commande python manage.py migrate --run-syncdb but i still receiving this error. -
How to initialize foreign key into a form in Django
I have this two models, one Voucher model is a foreign key to the RegistrationForm model. Anytime someone a search and the in item exist in the voucher model, I want it to be initialized to the Registration form and saved Error Message raise ValueError( ValueError: Cannot assign "'phr201'": "RegistrationForm.voucher" must be a "Voucher" instance. Models class Voucher(models.Model): name = models.CharField(max_length=120, null=True, blank=True) class RegistrationForm(models.Model): voucher = models.OneToOneField(Voucher, on_delete=models.CASCADE) full_Name = models.CharField(max_length=200,) Date_of_birth = models.CharField(max_length=100) View.py class RegistrationProcessing(generic.CreateView): form_class = Registerform template_name = 'RegistrationProcessing.html' def form_valid(self, form): form.instance.voucher = self.request.GET.get('q') return super().form_valid(form) def get_context_data(self, **kwargs): context = super(RegistrationProcessing, self).get_context_data(**kwargs) query = self.request.GET.get('q', default='') print(query.id) context.update({ 'job_listing': Voucher.objects.filter( Q(name__iexact=query) ) }) return context -
Django object.filter(X__contains = 210922143300) gives error
Please help me out def search_venues(request): if request.method == "POST": searched = request.POST['searched'] titles = Information.objects.get(id=210922143300) print(titles) titles = Information.objects.filter(id__contains=21092214330) print (titles) return render(request, 'search_titles.html', {'searched': searched, 'titles': titles}) else: return render(request, 'search_titles.html', {}) the first print statement gives me: <QuerySet [<Information: Wind energy can deliver vital slash to global warming>]>, like i expect the second print statement gives me: enter image description here What should i do, ofc in the future i want to pass my searched variable -
Filtering a table by a <select> clause with Django
I have a table that needs to be filtered on a select HTML clause giving a functionality like an excel filter. How can this filtering can be implemented? I want to filter it by owner Table Example: <table class="table table-hover"> <thead class="table-bordered"> <tr> <th scope="col">NumberID</th> <th scope="col">Title</th> <th scope="col"> Owner <select name="columns" class="form-select" aria-label="Default select example"> <option selected>All</option> <option value='option1' id="filterOwner">1</option> <option value='option2' id="filterOwner">2</option> <option value='option3' id="filterOwner">3</option> <option value='option4' id="filterOwner">4</option> <option value='option5' id="filterOwner">5</option> </select> </th> <th scope="col">Status</th> </tr> </thead> <tbody id='myTable'> {% for data in dataset %} <tr> <td>{{ data.NumberID }}</a></td> <td>{{ data.title }}</a></td> <td>{{ data.owner }}</a></td> <td>{{ data.currentMonthStatus }}</a></td> <td> <a type="button" class="btn btn-outline-success btn-sm" href="/updatecontrol/{{data.NumberID}}">edit utility control</a> </td> </tr> {% endfor %} </tbody> -
How do i serve files uploaded by the user in a locally deployed django project
I deployed my django app using python manage.py runserver 0.0.0.0:8888. And i set debug to False. HOw do i serve files uploaded by the user. The app is an internal app and can only be accessed by staffs of the organization. So they want the media files to be stored locally on the server -
Integrating Model, Serializer and Algorithm in a tree structure coherently
I have a tree-like structure of objects, linked to each-other with foreign keys. Each object's fields are stored in a model. Each object has a serializer. Each object has a few routines, now stored in an algorithm class. There is a serializer that recreates the tree structure into a nested dictionary. How do I merge these 3 facets of each object into a single object? Should I create a child object, which inherits from the three others (scary)? or should I include the model and the serializer inside my algo class as inner objects (seems more modular and independent)? -
matching query does not exist. in django
Hi This is my Project I needed define two get_absolute_url in my project get_absolute_url one models.py def get_absolute_url(self): return reverse("cv:resume_detial", args={self.id, self.slug}) urls.py path('resume-detial/<int:resume_id>/<slug:resume_slug>', views.ResumeDetialView.as_view(), name="resume_detial"), views.py class ResumeDetialView(View): template_name = 'cv/resume-detial.html' def get(self, request, resume_id, resume_slug): resumes = ResumeDetial.objects.get(pk=resume_id, slug=resume_slug) return render(request, self.template_name, {'resumes':resumes}) This is a work But other get_absolute_url is does not work models.py def get_absolute_url(self): return reverse("cv:project_detial", args={self.id, self.project_slug}) urls.py path('project-detial/<int:project_id>/<slug:projects_slug>', views.ProjectDetialView.as_view(), name="project_detial"), views.py class ProjectDetialView(View): template_name = 'cv/project-detial.html' def get(self, request, project_id, projects_slug): projects = ResumeDetial.objects.get(pk=project_id, slug=projects_slug) return render(request, self.template_name, {"projects":projects}) django messages DoesNotExist at /project-detial/1/todo-django ResumeDetial matching query does not exist. I am a beginner and thank you for your help -
when i deploy django application on heroku. My websocket is is disconnect when i tried to connect
heroku Application Logs INFO failing WebSocket opening handshake ('Internal server error') WARNING dropping connection to peer tcp4:10.1.40.17:31231 with abort=False: Internal server error DEBUG WebSocket closed for ['10.1.40.17', 31231] my settings.py import redis CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.pubsub.RedisPubSubChannelLayer", "CONFIG": { "hosts": [("*", 6379)], }, }, } -
ReactJS with graphql CORS Issue
I have running django backend on http://127.0.0.1:8000 and I want to request it with reactjs frontend. As you can see below, I can see the successful response in the Insomnia app. But, When I want a request with reactjs frontend, I get a CORS ERROR. I check the request in the inspect networks and I saw a similar request payload with insomnia. -
Why does django queryset only allow me to search users by foreignkey only ( Number) and not by user name?
Am working on this app where users of the app can make payment to other users, but am currently challenge by the search functionality, since i can only search users on the app by their foreignKey only, but instead i would want to be able to search by users full name and username, when i search user by name i get this exception (Field 'id' expected a number but got 'Hong'. ). why does my query only limit me to search by user number(foreignKey).Here is my view to search user for payment. class RequestSearchUser(LoginRequiredMixin, ListView): model = FriendList form_class = SearchUserForm template_name = 'wallet/request_search_user_form.html' def get_queryset(self): try: username = self.kwargs['search_user'] except: username = '' if username != '': object_list = self.model.objects.filter(user=username) else: object_list = self.model.objects.all() return object_list def get_context_data(self, **kwargs): context = super(RequestSearchUser, self).get_context_data(**kwargs) query = self.request.GET.get("search_user") context['user'] = self.request.user if query: queryset = (Q(user=query)) search_user = FriendList.objects.filter(queryset) if not search_user: messages.error(self.request, 'No user found.') else: search_user = [] context['search_user'] = search_user context['nbar'] = 'request' return context Here is my search form.py class SearchUserForm(forms.ModelForm): class Meta: model = User fields = ('username',) def clean_username(self): username = self.cleaned_data['username'].strip() return username Here is the Html form <div class="blog_details"> <h2>Request Money</h2><hr> <form class="form-contact … -
How can i convert string to int and then sort view by int value?
I want sort view by a value that is string. but before that, i want convert string to int then sort by that. main = models.Main.objects.all().order_by('fore_key__n') In this code fore_key__n is string value like '20' -
Deploying Project from VS to App service: Container ***** didn't respond to HTTP pings on port: 8000, failing site start
I'm trying to deploy Django project to Azure App Service through Visual Studio. Once deployed and if I open the app URL an error is displayed ":( Application Error". Same error occurs if deployed from the GitHub Actions CI/CD through service principles. Logs displaying this error "Container **** didn't respond to HTTP pings on port: 8000, failing site start" Unable to find any solution for this. Any help would be appreciated. -
In @app.route('/') , how route function is invoked from app object. like @object.decorator_function(arg)
In Python flask framework app is object and route is function and decorator can anybody tell me what is the mechanism behind it . I mean @app.route('/') , how route function is invoked from app object. e.g. @object.decorator_function(arg) from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' -
Changing the Django admin site
I wanted to change the "Django administration" text on the default Django admin site. But the docs do not make it that, clear. Is there a way that I can do it once i have collected all the static files? -
Elastic search and Lucene for Django and MongoDB
I'm implementing a search engine in my Django project with MongoDB. But I have some confusion about choosing between Lucene and ElasticSearch. As mentioned, I'm using MongoDB for storing data. Anyone, please give me the technical reason for choosing Lucene over ElasticSearch. Which one is better for indexing and analytics as well. -
Django admin does not show extra fields added in init method of modelform
I found a couple of questions regarding this, but I specifically wonder about how to add a field in the ModelForms __init__() method. This is, because I get the number of fields from a function and need to display them in the admin: class SomeForm(forms.ModelForm): class Meta: model = Product fields = ["name", "price",] def __init__(self, *args, **kwargs): number_of_fields = get_number of fields(kwargs["instance"]) print(number_of_fields) ## e.g. 3, gives output super().__init__(*args, **kwargs) for i in range(number_of_fields): self.fields[i] = forms.CharField("test", required = False) But the fields do not show up in the Template Admin edit page. What did I miss? No error popping up either ... -
django-component - passing string instead of context variable
Having trouble passing context variable to a django-component View: labels = "'January','February','March','April','May','June'" data = "69, 10, 5, 2, 20, 30" colors = "'#3e95cd', '#8e5ea2','#3cba9f','#e8c3b9','#c45850','#a45350'" context = { 'title': title, 'language': langCode, 'clabels':labels, 'cdata':data, 'ccolors':colors} return render(request, "reports/dashboard.html", context) In Template: <div class="col-lg-6">{% component "simplechart" width="980" height="300" chartid="chart1" title="We are testing" clabels='{{ clabels }}' cdata="{{ cdata }}" ccolors="{{ ccolors }}" type="bar" %}</div> Components.py @component.register("simplechart") class SimpleChart(component.Component): # Note that Django will look for templates inside `[your app]/components` dir # To customize which template to use based on context override get_template_name instead template_name = "simplechart/simplechart.html" # This component takes three parameters def get_context_data(self, width, height, chartid, title, clabels,cdata,ccolors, type): print("CHART GET CONTEXT") print(cdata) print(clabels) return { "width": width, "height": height, "chartid": chartid, "title": title, "clabels": clabels, "cdata": cdata, "ccolors": ccolors, "type": type } class Media: css = { 'all': ('css/simplecard.css') } js = 'js/cmx_chart.js' The debug print statements output: CHART GET CONTEXT {{cdata}} {{clabels}} It is passing in the litereal string, not replacing with context variable passed in from the view. Any ideas what I'm doing wrong? -
allauth don't send verification emails django
hi iam useing allauth django but it dont send any email my settings.py : # ALL AUTH SETTINGS ACCOUNT_EMAIL_REQUIRED= True ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_USERNAME_BLACKLIST = ['test'] ACCOUNT_USERNAME_MIN_LENGTH = 4 ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_CONFIRMATION_COOLDOWN =120 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'MY EMAIL' EMAIL_HOST_PASSWORD = 'EMAIL PASSWORD' i have trun on less secure apps on my google account i dont know what to do know -
Drf excel renderer not returning proper values?
class UserExportSerializer(ModelSerializer): class Meta: model = User fields = ["email", "phone", "username"] class UserExportViewSet(XLSXFileMixin, ReadOnlyModelViewSet): queryset = User.objects.all() serializer_class = UserExportSerializer renderer_classes = [XLSXRenderer] I have a value of phone +919999999999 in database but while exporting to excel it returns '+919999999999. But if there is not + at first in phone value then it works fine. I am using drf-renderer-xlsx package to export into excel. -
how to pass in slug url in django template
i want to pass in a slug in my django template so i can be able to add a post as favourite but i do not know the right way to pass in the slug this is what i have done href="{% url 'elements:favourite' elements_slug.slug %} <a href="{% url 'elements:favourite' elements_slug.slug %}" class="btn">Favourite</a> views.py def favourite(request, elements_slug): user = request.user elements = Elements.objects.get(slug=elements_slug) profile = Profile.objects.get(user=user) if profile.favourite.filter(slug=elements_slug).exists(): profile.favourite.remove(elements) else: profile.favourite.add(elements) return HttpResponseRedirect(reverse('elements:vector-details', args=[elements_slug])) -
Django - display "loading bar" after form submit until backend result is returned
I have a online pricing webpage where customer can input some data, then submit the form to get the price returned. How to display a "work-in-progress/loading/calculating"kind of thing temporarily before the final result (e.g. price) is calculated/returned. below is the simplified code from my web: Main html (post_list.html) (Note: I am using htmx to help partially update the page result) <html> <body> <form method="POST" hx-post="{% url 'post_list' %}" hx-target="#num_1" hx-target="#num_2" hx-target="#result"> {% csrf_token %} <div> <label>num_1:</label> <input type="text" name="num_1" value="" placeholder="Enter value" /> </div> <div> <label>num_2:</label> <input type="text" name="num_2" value="" placeholder="Enter value" /> </div> <br /> <div id="num_1">{{ num_1 }}</div> <br /> <div id="num_2">{{ num_2 }}</div> <br /> <div id="result">{{ result }}</div> <br> <button type="submit">Submit</button> </form> <script src="https://unpkg.com/htmx.org@1.6.1"></script> </body> </html> post_list_snippet.html <html> <div> <label>first_number:</label> <span id="num_1"> {{ num_1 }} </span> </div> <div> <label>second_number:</label> <span id="num_2"> {{ num_2 }} </span> </div> <div> <label>calculation_result:</label> <span id="result"> {{ result }} </span> </div> </html> view.py def post_list(request): result = "" num1 = "" num2 = "" if request.method == "POST": num1 = request.POST.get('num_1') num2 = request.POST.get('num_2') result = int(num1) + int(num2) if request.headers.get('Hx-Request') == 'true': # return only the result to be replaced return render(request, 'blog/post_list_snippet.html', {'num_1': num1,'num_2': num2,'result': result}) else: return render(request, 'blog/post_list.html', … -
Django Model ImageField default value
I made a model which has an image field and it is allowed to be blank. How can I have a default image for the model when no image is set for it? class Product(models.Model): picture = models.ImageField(blank=True) -
how to access parent object from admin tabularinline in Django admin
I need to access the parent object of an item to be able to filter the dropdown Fk fields inside the inline object based on it is a parent. here is my code : models.py class Match(models.Model): date_time = models.DateTimeField() home_team = models.ForeignKey('teams.Team',related_name="home_team_team",on_delete=models.PROTECT) away_team = models.ForeignKey('teams.Team',related_name="away_team_team",on_delete=models.PROTECT) league = models.ForeignKey(League,on_delete=models.CASCADE,null=True) class Goal(models.Model): match = models.ForeignKey(Match,on_delete=models.CASCADE) date_time = models.DateTimeField() team = models.ForeignKey("teams.Team",on_delete=models.PROTECT,null=True,blank=True) player = models.ForeignKey('players.PlayerProfile',related_name="goal_maker",on_delete=models.PROTECT,null=True,blank=True) assistant = models.ForeignKey('players.PlayerProfile',related_name="goal_assist",on_delete=models.PROTECT,null=True,blank=True) admin.py #this is my inline class class GoalInline(nested_admin.NestedTabularInline): model = Goal fields = ['date_time','team','player','assistant'] extra = 1 show_change_link = True def formfield_for_foreignkey(self, db_field, request, **kwargs): print(f"data {self.model}") if db_field.name == "team": kwargs["queryset"] = Team.objects.filter() #i need to perform filtering here return super().formfield_for_foreignkey(db_field, request, **kwargs) #my parent class @admin.register(Match) class MatchAdmin(nested_admin.NestedModelAdmin): # form = LeagueForm readonly_fields = ['date_time','home_team','away_team','league'] list_display = ["league","home_team","away_team",] search_fields=["home_team","away_team","league"] list_filter=['league','date_time',"home_team","away_team"] inlines=[GoalInline] def get_inlines(self, request, obj=None): if obj: return [GoalInline] else: return []