Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not able to redirect to another page after clicking on submit button django
So, I have implemented a bit of post, get and update in the following code. After submitting the values into the database. The return redirect is not changing the page to UserProfile.html which in urls.py is user_profile Code urls.py path('user_profile', views.user_profile, name="user_profile"), views.py def edit_profile(request): try: # checking if the user exist in UserProfile through the logged in email id user_data = UserProfile.objects.get(emailID = request.user.email) # if request.method == "POST" and request.FILES: if request.POST.get('action') == 'post': name = UserProfile.objects.all() response_data = {} # user_img = request.FILES['user_img'] name = request.user.username emailID = request.user.email phone = request.POST.get('phone') college_name = request.POST.get('college_name') branch = request.POST.get('branch') # response_data['user_img'] = user_img response_data['name'] = name response_data['emailID'] = emailID response_data['phone'] = phone response_data['college_name'] = college_name response_data['branch'] = branch # updating the current logged in user values user_data = UserProfile.objects.get(emailID = request.user.email) if(user_data.emailID == request.user.email): UserProfile.objects.filter(emailID = request.user.email).update( name = name, emailID = emailID, phone = phone, college_name = college_name, branch = branch ) return redirect('/user_profile') except UserProfile.DoesNotExist: name = UserProfile.objects.all() response_data = {} # creating new user if request.POST.get('action') == 'post': # user_img = request.FILES['user_img'] name = request.user.username emailID = request.user.email phone = request.POST.get('phone') college_name = request.POST.get('college_name') branch = request.POST.get('branch') # response_data['user_img'] = user_img response_data['name'] = name response_data['emailID'] … -
How to access the instance of the ClusterableModel parent object from a child orderable before the orderable has been saved?
When creating orderables as children of a clusterablemodel, is there any way to access properties of the parent before that parent instance has been saved? The ParentalKey is None until the orderable instance has been saved. Maybe it's possible to pass variables to the orderable when the orderable instance is created? I want to filter the choices offered on the orderable based on the parent properties but can't find any way to do this, only one-filter-for-all. Abbreviated code from a Wagtail test project: @register_snippet class ParentSnippet(TranslatableMixin, ClusterableModel): code = models.CharField(blank=False, null=True, max_length=10) title = models.CharField(blank=False, null=True, max_length=50) .... class ChoiceListIterator(object): def __iter__(self): dropdown_list = list(ChoiceListClass.objects.values_list('code','title')) return dropdown_list.__iter__() class ChildOrderable p_key= ParentalKey( "ParentSnippet", related_name="child_items", ) choice_list=ChoiceListIterator() submenu_selector=Select() submenu_selector.choices = choice_list dropdown_test = models.CharField( blank=False, null=True, max_length=10, choices=choice_list ) panels = [ FieldPanel("dropdown_test"), ] This is fine for showing everything from the ChoiceListClass (just something to return items for this example), the dropdownlist is populated dynamically. Ideally, I want to be able to pass either the parent snippet or properties based on the parent snippet into the ChoiceListIterator constructor and then use this to filter the dropdown_list. eg choice_list=ChoiceListIterator(parent_snippet_instance) But how to access the instance of the parent object creating the orderable … -
Implement Google Indexing Api Django
I am working on a Django project where I need to implement Google Indexing Api . I want to instantly crawl and index all the api's on our site. -
Hide certain fields Django Filter Forms
I have been searching around a bit but I can't find the answer. search.html <form action="" method="get"> {{ filter.form|crispy }} <input type="submit" class="btn btn-primary" /> </form> filters.py class GameFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains') popularity = django_filters.RangeFilter() class Meta: model = Game fields = ['gamemodes'] together = ['name', 'releases__date'] I still want to be able to search on those fields, but I dont want to show certain fields in the filter.form. Example, I want to be able to search on popularity, but I dont want its field generated in the filter.form. Currently all fields are being shown How do I do that? -
Django page not found (404) in my core/urls.py file. Only works when the urls are rearranged
I am relatively new to Django. I've set up my URLs in my core/urls.py file this way and I do get a 404 error when I opened localhost:8000/posts/ on the browser. Code is shown here urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<slug:slug>/', views.SingleView.as_view(), name='single'), path('posts/', views.PostsView.as_view(), name='posts'), ] However, everything works fine when I reverse the slug and posts/ to make the posts come before the slug. Like this: urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('posts/', views.PostsView.as_view(), name='posts'), path('<slug:slug>/', views.SingleView.as_view(), name='single'), ] Please help me figure it out. -
How do I obtain references to other data being submitted in the Django admin?
I have a multiple-choice test app in Django 3.0. It has two models, Question and Choices # models.py class Questions(models.Model): question = models.CharField( help_text='Text of question' ) class Choices(models.Model): def clean(self): choicesSet = Choices.objects.filter(q=self.q) if ( choicesSet.count() != 4 ): raise ValidationError( "Four Choices must be provided." ) q = models.ForeignKey( Questions, on_delete=models.CASCADE ) option = models.CharField( help_text='Text of choice' ) The Admin page for Questions includes inputs for four Choices. When Choices are input, I want to make sure that a complete set of four are input at the same time. I attempted to do this with the Choices.clean() function shown, but it fails. When I enter four choices and attempt to save, each Choice returns the error "Four Choices must be provided". I think what's happening is that since the record is not successfully saved, choicesSet = Choices.objects.filter(q=self.q) returns zero because no Choices are foreign-keyed to the Question q=self.q yet. How can I obtain references to the other three Choices in the clean() function of one Choice during validation? I've read the documentation for Model validation and Form and field validation, but it's more confusing than helpful. -
custom EditProfile in Django forms, submit button not working
I created EditProfile FORMs, in my forms.py file: from django.contrib.auth.forms import UserChangeForm from korisnici.models import CustomKorisnici from django import forms class EditProfile(UserChangeForm): email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'})) first_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) last_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) phone_number = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) bio = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) phone_number = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model = CustomKorisnici fields = ('username', 'first_name', 'last_name', 'email','bio','phone_number','profile_image') def __init__(self, *args, **kwargs): super(EditProfile, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['phone_number'].required = False self.fields['profile_image'].required = False self.fields['bio'].required = False After I run a default Django form in my HTML file(edit_profile.html): <div class="form-group"> <div class="container"> <div class="form"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button id="btn" class="btn" type="submit">Edit Profile</button> </form> </div> </div> </div> When I click on submit button, it is working fine, my profile page was edit and data is change in base. But when I customize my form in bootstrap, the submission button is not doing anything. Here is my bootstrap form: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label >Username</label> <input type="text" class="form-control" name="username"> </div> <div class="form-group"> <label >First name</label> <input type="text" class="form-control" name="first_name"> </div> <div class="form-group"> <label >Last name</label> <input type="text" class="form-control" name="last_name"> </div> <div class="form-group"> <label >Email </label> <input type="email" class="form-control" … -
OSError sending email django
i create a website using python and django. i have a contact me form in it , but when i click the submit button i face with an error: OSError at / [Errno 101] Network is unreachable this is my settings.py: # Email Settings EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_HOST_USER = 'alime1@gmail.com' EMAIL_HOST_PASSWORD = '******' EMAIL_USE_TLS = True EMAIL_USE_SSL = False and this is my views.py: from django.shortcuts import render from django.http import HttpResponse from django.core.mail import send_mail from .models import Page def index(request): if request.method == "POST": name = request.POST['name'] email = request.POST['email'] message = request.POST['message'] # send an email send_mail( 'project website' + name, # subject message, # message 'alime1@gmail.com', # from email [email], # to email ) return render(request,'pages/index.html',{'name':name}) else: pages = Page.objects.all() context = { 'pages': pages } return render(request,'pages/index.html', context) and this is my form : <form action="{% url 'index' %}" class="waypoint" data-animation="pop-in" data-delay=".5s" method="post"> {% csrf_token %} <input placeholder="Name" type="text" name="name" required /> <input placeholder="Enter email" type="email" name="email" required /> <textarea placeholder="Your Message" type="text" name="message" ></textarea> <div id="success"> <div> Your message was sent successfully. Thanks!<span id="close" class="mdi mdi-close" ></span> </div> </div> <button type="submit" class="button"> Send </button> <!-- <input class="button" type="submit" id="submit" value="SUBMIT" /> … -
How do iI convert md files to HTML and render them in Django
I have some md files in an 'entries' folder in my django app folder and i wanna get them, covert them to HTML then render them. This is my util.py def get_entry(title): """ Retrieves an encyclopedia entry by its title. If no such entry exists, the function returns None. """ try: f = default_storage.open(f"entries/{title}.md") return f.read().decode("utf-8") except FileNotFoundError: return None def convert_md(filename): """ Converts given md file to html """ #file= f"{filename}.md" file= default_storage.open(f"{filename}.md") md= file.read() html= md.markdown(md) return html This is my views.py def wiki(request, topic): if util.get_entry(topic) != None: html= util.convert_md(topic) return render(request, "encyclopedia/pages.html", { "title": topic, "body": html }) else: return render(request, "encyclopedia/pages.html", { "title": "ERROR", "body": "THIS PAGE IS NOT AVALIABLE." }) I also have... path("wiki/<str:topic>", views.wiki) in my urls.py but I'm still getting a FileNotFoundError at /wiki/Python error -
I get an Error 404 in my Django App in app engine
I have deployed successfully my Django app in App Engine (standard environment) but I get this message: Not Found The requested resource was not found on this server. In the dashboard there are no Application and server errors but there are two clients errors whose URI are: /favicon.ico and /myapp/ In the Logs Explorer I can find a 404 error before the app starts working and it ends with a 301. -
'GenericApiView' object has no attribute 'update' in my views.py file
The .update function is not suppporting to this genericApiView in my view.py file it gives me an error message 'GenericApiView' object has no attribute 'update' . class GenericApiView(generics.GenericAPIView,mixins.ListModelMixin, mixins.CreateModelMixin,mixins.RetrieveModelMixin,mixins.DestroyModelMixin): serializer_class=ArticleSerializer queryset=Article.objects.all() lookup_field='id' authentication_classes=[SessionAuthentication,BaseAuthentication] permission_classes=[IsAuthenticated] def get(self,request, id=None): if id: return self.retrieve(request) else: return self.list(request) def post(self,request,id): return self.create(request,id) # Error in this function def put(self,request,id): return self.update(request,id) def delete(self,request,id=None): return self.destroy(request,id) -
How to define optional query parameters in Django?
here i got one endpoint to receive multiple query parameters namely first_name, last_name. location and i need the endpoint to be able to handle following scenarios all the 3 param's 1 param 2 param's And i found this but still i got 404 when provide one query parameter, only works when all the parameters are given. urls.py re_path(r'^project_config/(?P<product>\w+|)/(?P<project_id>\w+|)/(?P<project_name>\w+|)/$', views.results, name='config') And view def results(request, product, project_id, project_name): response = "You're looking at the results of question %s." print(product) print(project_name) return HttpResponse(response % project_id) How can allow url to accept optional query parameters ? -
What is the optimal batch size in django
I'm wondering that the optimal batch size while making bulk create in Django. I don't know the exact number of data. It might be millions or thousands. How can I decide the optimal batch size? -
Django get field from m2m and foreign key
I am adding functionality to my django application to add models(Lot) linked to another(Job) with an M2M field. The problem: I am using Django autocomplete light to add this model(Lot) in the form and i want this field to also be filtered by the input and another autocomplete field(Contract), this field is an object called contract that is in the reverse of the M2M field: Relations: {Lot}--reverse on the M2M--{Job}--Foreign Key--{Contract} I am trying to filter lot in the autocomplete to only those where the contract key on the order matches a field in the form, i have looked through documentation and im unsure if there is anyway to do this, below is my latest attempt along with relevant code. models.py(only fields for the relationship) class Contract(Parent_model): contract_id = models.IntegerField(null=False, default=0000) class Job(Job_parent): contract = models.ForeignKey(Contract, on_delete=models.CASCADE) class Lot(Job_parent): CO = models.ManyToManyField(Job, related_name='Lot') autocomplete class based view(views.py) class lot_auto_complete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Lot.objects.all() contract_in = self.forwarded.get('contract', None) if contract: query_set = qs.filter(CO_set.first().contract=contract_in) if self.q: query_set = qs.filter(lot_number__icontains=self.q) return query_set -
installing GEOS on ubuntu
hi i am trying to install GEOS on ubuntu with wget https://download.osgeo.org/geos/geos-X.Y.Z.tar.bz2 but it gives --2021-03-10 10:48:18-- https://download.osgeo.org/geos/geos-X.Y.Z.tar.bz2 Resolving download.osgeo.org (download.osgeo.org)... 140.211.15.30 Connecting to download.osgeo.org (download.osgeo.org)|140.211.15.30|:443... connected. HTTP request sent, awaiting response... 404 Not Found 2021-03-10 10:48:19 ERROR 404: Not Found. judging from the HTTP reponse i dont think it actually downloaded so is there another way to download GEOS? -
How to convert factory boy instance as json
I have a model that relates to some others and I want to make an instance of model factory with factory boy package and send it as json to rest API in django rest framework. When I use: factory.build(dict, FACTORY_CLASS=UserFactory) it returns: {'first_name': "Agent 001", 'username': 'john_doe', 'language': <Language: Catalan>} where language is another model factory but I need it as json to post or patch test. How would I get something like this? {'first_name': "Agent 001", 'username': 'john_doe', 'language': [{'name': 'English'}, {'name': 'French'}]} -
Filefield is not displayed on foreign key popup fiel in django admin
File field from this model is not displayed on the popup form on a foreign key field in django admin. My model is: class NationalId(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,null=True) not_registered_user = models.OneToOneField(NotRegisteredUser, on_delete=models.CASCADE, null=True) national_id = models.CharField(max_length=9, blank=False) document_type = models.CharField(max_length=10, blank=False) is_verified = models.BooleanField(blank=False, default=False) date_verified = models.DateField(null=True, blank=True) date_expired = models.DateField(null=True, blank=True) image_file = models.FileField(null=True, blank=True, verbose_name=_(u'scanned image')) def __str__(self): return self.national_id And the popup shown is -
How to Embed Power BI dashboard into Web portal using Django?
Is it possible to embed dashboards/reports from Power BI and embed it into Web portal using Django framework? I just tried using 'Flask' and it was working fine. But I really wanted to do the same using Django. I'm new to this field and really confused about the code and all. -
Unresolved attribute reference 'objects' for class 'GeneralSettings'
Django 3.1.7 Python 3.8.5 class Branch(models.Model): def get_external_dir(self) -> str: """ Get the path to where all external files for this branch must be put. """ general_settings = generals_models.GeneralSettings.objects.get(key="general_settings") class GeneralSettings(models.Model): key = models.CharField(max_length=16, null=False, default="general_settings") ... Problem Pycharm shows me a warning: Unresolved attribute reference 'objects' for class 'GeneralSettings' I'm struggling for a stylish code. I don't want this warning as it irritates me. Could you tell me: Why is such a warning appear and how to cope with it? Should I just ignore it like this? -
AttributeError: 'ApplicantEducation' object has no attribute '_state'
This is how i constructed my model: Model.py class ApplicantEducation(models.Model): applicant_info = models.ForeignKey(ProfileInfo, on_delete=models.CASCADE) degree_details = models.ForeignKey(DegreeDetails, on_delete= models.CASCADE) marks_percentage = models.FloatField(max_length=5, default=0.0) institute_name = models.CharField(max_length=100) affilation_with = models.CharField(max_length= 50) date_completion = models.DateField(auto_now_add=False, blank=True) def __str__(self): return str(self.applicant_info) def __init__(self, applicant_info = None, degree_details = None): applicant_info = ProfileInfo.info_id degree_details = DegreeDetails.id Anybody, who can figure this out?? -
Making complex query with django models
I created a view in my database model with 6 joins and 10 columns, and at the moment it shows around 86.000 rows. I try to query all the rows by objects.all() and then filter according to user interaction (form data sent by POST and then choosing appropriate .filter(*args) querying) After that I tried to get the length of the queryset by using count() since this method doesnt evaluate the query. But since views don't have indexes on the columns, the count() method takes to long. I searched for the solution of materializing the view but that isn't possible in mysql. Then I searched for a solution that might be able to replace the initial .all() by just using the 6 joins and filtering arguments in django rather than creating a view, so the indexes would still be available. But I couldn't find a solution to that problem. Or maybe combining every row from the view with another table so I can use the index of the other table for faster querying?: SELECT * FROM View LEFT JOIN Table ON (View.id = Table.id) I appreciate every answer -
py.test completely ignores configured loggers. How to fix it?
I have a weird py.test behavior. If a logger is configured in settings.LOGGING then py.test won't show those logger messages captures on a failed test, won't show when running with -s nor having log_cli=true in conf file. Here is how my logging configuration looks like: LOGGING = { "version": 1, "handlers": { "stream": { "class": "logging.StreamHandler", } }, "loggers": { "app": {"handlers": ["stream"], "level": "WARNING", "propagate": False,}, }, } If I comment out the "app": line then logs appear. -
Is there anyone who can assist me to integrate domain registar in my dajngo project
I would like to add a domain registrar to my project like whmcs. I am able to build a project which works like WHMCS billing software but unable to add the domain registrar. I want when the user searches the domain it should give the result that whether it is available or not. if available it should reserve for that user. it is like whmcs domain registar -
display menu of each restaurant for different hotel in web app django?
if we have a web page that displays names of multiple restaurant .Then how do we display menu of each restaurant in Django(backend). I can't figure it out please help. -
How to create user friendly cronitor expression generator using Javascript?
User need to easily create a cronitor expression from UI. Example for the cron expression generator : https://www.freeformatter.com/cron-expression-generator-quartz.html