Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to call templates outside app folder?
How can I call the header.html? This is my folder structure. I'm having a "TemplateSyntaxError at /". - Project Name - App - Home - Templates //will contain all the views - home.html - views..py - Templates //will contain all the scripts,styles - header.html Here is my code: Home/templates/home.html {% extends '../../templates/header.html' %} {% block content %} <body> </body> {% endblock content %} -
Razorpay payment button connection in django
Hey I'm trying to make donation web app in django I have never work in gateway application. views.py def payment_page(request): form = PaymentForm(request.POST or None) donation = request.POST.get('donation') try: donation = int(donation) * 100 # Note 1 Rs == 100 ps donation = str(donation) except TypeError: donation = 100 # If delete this you will TypeError Razorpay money should be greater than 1 ps return render(request, 'mysite/payment_page.html', {'form':form, 'donation':donation}) What I done in try block? 1 rs is equal to 100ps so I multiple it with 100. If I don't use the try it give me typeError payment_page.html <div class="container"> <div class="jumbotron"> <form method="post">{% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-danger">Donate</button> </form> </div> </div> <form action="/purchase" method="POST"> <!-- Note that the amount is in paise = 50 INR --> <script src="https://checkout.razorpay.com/v1/checkout.js" data-key="rzp_test_VKwzQnRYkTmxEW" data-amount="{{ donation }}" data-buttontext="Pay" data-name="Merchant Name" data-description="Purchase Description" data-image="" data-prefill.email="{{ email }}" data-theme.color="blue" ></script> <input type="hidden" value="Hidden Element" name="hidden"> </form> How it working right now I enter name, donation amount, email in form click donate the amount it save in database and after that I press pay it display the amount, but I want only one button which can do the both work at the same … -
How to test clean_<fieldname> method?
I try to write a test for my clean_ method. Here is the code for my test def test_clean_restraints(self): form = NewTaskForm(dict(restraints="90 20 <>")) form.clean_restraints() At this step I receive an error: Error Traceback (most recent call last): File "/home/user/django_projects/my_webservice/tasks/tests/test_forms.py", line 12, in test_clean_restraints form.clean_restraints() File "/home/user/django_projects/my_webservice/tasks/forms.py", line 22, in clean_restraints if self.cleaned_data.get('restraints') == '': AttributeError: 'NewTaskForm' object has no attribute 'cleaned_data' NewTaskForm looks like this: class NewTaskForm(ModelForm): class Meta: model = Task restraints = forms.CharField() region = forms.CharField() interactions = forms.CharField() def clean_restraints(self): if self.cleaned_data.get('restraints') == '': return self.cleaned_data.get('restraints') data = self.cleaned_data.get('restraints').strip().split('\n') regexp = re.compile(r'^(\d+)[\t ]+(\d+)[ \t]+([><]{2})?$') cleaned_data = [] for i, line in enumerate(data): match = regexp.match(line) if not match: raise forms.ValidationError(f"Error in restraints in line {i + 1}") else: rst_1, rst_2, loop_type = match.groups() rst_1 = int(rst_1) rst_2 = int(rst_2) cleaned_data.append((rst_1, rst_2, loop_type)) return cleaned_data I'm using Django 2.1, python 3.7.1, PyCharm 2018.3.3 Professional I tried to run it under debugger in PyCharm but things goes crazy. I receive different error message. It looks like debugger stopped after full form validation ignoring breakpoints. I have no idea what is going on. -
Django - image does not gets display if object_list == empty
i want to display an image if nothing could be found trough my searchg function. I setup 2 serach functions. one for elasticsearch and the other one for a local search query view, anyways the one for elastic does not seems to work or at least it does not display the "not found" image if the object_list is empty, any idea? elastic_search_function: def globalsearch_elastic(request): qs = request.GET.get('qs') page = request.GET.get('page') if qs: qs = PostDocument.search().query("multi_match", query=qs, fields=["title", "content", "tag"]) qs = qs.to_queryset() else: qs = '' paginator = Paginator(qs, 10) # Show 10 results per page try: qs = paginator.page(page) except PageNotAnInteger: qs = paginator.page(1) except EmptyPage: qs = paginator.page(paginator.num_pages) return render(request, 'myproject/search/search_results_elastic.html', {'object_list':qs}) template.html <body> <h1 class="center">Search results <a class="fa fa-search"></a></h1> <hr class="hr-style"> {% if object_list.count == 0 %} <div class="search_not_found"> <img src={% static "/gfx/sys/not_found.png" %}> <h2>Nothing found here ...</h2> </div> {% else %} {% for post in object_list %} <div class="post"> <h3><u><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></u></h3> <p>{{ post.content|safe|slice:":800"|linebreaksbr}} {% if post.content|length > 300 %} <a href="{% url 'post_detail' pk=post.pk %}">... more</a> {% endif %}</p> <div class="date"> <a>Published by: <a href="{% url 'profile' pk=user.pk %}" >{{ post.author }}</a></a><br> <a>Published at: {{ post.published_date }}</a><br> <a>Category: <a href="{% … -
CodeSnippet display from right to left problem
hello i'm using ckiditor and i use CodeSnippet inside it it display from right to left like this https://dzblog.pythonanywhere.com/media/Images/Screenshot_2019-01-21_jkgjfghfghfghfghfghfghfgh1.png and inside my base.html i set <body class = 'rtl'> <!-- content--> </body> i know but website use 'AR' as default language so can someone help me to make just CodeSnippet show from left to right thank you -
How to store global state in Django application outside database?
I want to implement a neural network model in Django application so that it can communicate via REST API with other application. Django application iteratively (1) collects a batch of training data from the other application, (2) retrains the model on so far aggregated data and (3) gives predictions on demand from that other application. Time is crucial factor here. How and where can I store an instance of the trained model between those steps? -
How to attach the downloaded csv from another url and attach it as a file inside django mail?
How to attach the downloaded CSV file from another url and attach it as a file to send mail using Django ? -
Reference a field from a model specified in Foreign Key
Say I have a car model that looks like this: class Car(models.Model): car_model = models.CharField(max_length=100) car_number = models.IntegerField() and I also have a wheel model that now looks like this: class Wheel(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE) I want to specify a wheel's model so it has to be the same like its car's model. something like that: class Wheel(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE) wheel_model = car.car_model How can I achieve this? So If my car_model is BMW, I want also to have wheel_model BMW set automatically -
How do I construct an order_by for a specific record in a ManyToOne field?
I'm trying to sort (order) by statistical data stored in a ManyToOne relationship. Suppose I have the following code: class Product(models.Model): info = ... data = models.IntegerField(default=0.0) class Customer(models.Model): info = ... purchases = models.ManyToManyField(Product, related_name='customers', blank=True) class ProductStats(models.Model): ALL = 0 YOUNG = 1 OLD = 2 TYPE = ((ALL, 'All'), (YOUNG, 'Young'), (OLD, 'Old'),) stats_type = models.SmallIntegerField(choices=TYPE) product = models.ForeignKey(Product, related_name='stats', on_delete=models.CASCADE) data = models.FloatField(default=0.0) Then I would like to sort the products by their stats for the ALL demographic (assume every product has a stats connected to it for ALL). This might look something like the following: products = Product.objects.all().order_by('stats__data for stats__stats_type=0') Currently the only solution I can think of is either to create a new stats class just for all and use a OneToOneField for Product. Or, add a OneToOneField for Product pointing to the ALL stats in ProductStats. Thank you for your help. -
React w/ Django Rest Framework response (200) is <unavailable>
I'm trying to use React to consume a Django Rest Framework-based API, but am having some major problems with what should be super simple. Given this simple API method: from rest_framework.decorators import api_view, detail_route, list_route, permission_classes @api_view(['GET']) @permission_classes((AllowAny,)) def dummy(request, per_page=40): import json print("Returning the dummy") return Response({"Yeah":"Booo!"}) And this function in React using Axios to consume it: import React, { Component } from "react"; import PropTypes from "prop-types"; import axios from 'axios'; class Dashboard extends Component{ constructor(props){ super(props); this.state = { username: props.username, }; axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; } componentDidMount(){ axios.get('/api/dummy/').then((response) => console.log(response)); } render(){ return( <div id="dashboardWrapper"></div> ) } } export default Dashboard Using Python's requests library and curl, the method returns a JSON object. In the browser, loading this page will run the GET function, and also load the JSON object in the Network tab. This leads me to believe that the problem isn't on Django's end. When I look in the console, the Axios GET function will not capture the response sent up from Django. It gets a status code 200, but nothing else. No response.data at all. With console.log(response) all I see is , for both errors (have tested on non-existant endpoints) and … -
Django admin. Edit user and leave password unchanged
I have my custom user model: class RemoteUser(AbstractUser): class Meta: verbose_name= 'MyUser' verbose_name_plural = 'MyUsers' # Custom fields here... How do I set up my user admin form to edit user details hiding the password? class RemoteUserForm(UserCreationForm): # What do I put here? Even if I exclude password from fields it keeps giving me KeyError 'password1'. -
Deleting nullable field is deleting related objects
I have a Tournament model with related Standings: class Tournament(models.Model): standings = models.ForeignKey('Standings', blank=True, null=True) I just did the following: standings = Standings.objects.get(pk=pk) standings.delete() And it deleted the related tournament as well. This should not have happened, since standings is a nullable field. Why did it happen and what can I do to prevent this from happening again? -
Django: Update form for inline_formset is not working
These are my forms: class MultijournaltotalForm(forms.ModelForm): class Meta: model = Multijournaltotal fields = ('Date', 'Total_Debit', 'Total_Credit') widgets = { 'Date': DateInput(), } def __init__(self, *args, **kwargs): self.user = kwargs.pop('User', None) self.company = kwargs.pop('Company', None) super(MultijournaltotalForm, self).__init__(*args, **kwargs) self.fields['Date'].widget.attrs = {'class': 'form-control',} self.fields['Total_Debit'].widget.attrs = {'class': 'form-control',} self.fields['Total_Credit'].widget.attrs = {'class': 'form-control',} class MultijournalForm(forms.ModelForm): class Meta: model = Multijournal fields = ('By','To','Debit','Credit','narration') def __init__(self, *args, **kwargs): self.User = kwargs.pop('User', None) self.Company = kwargs.pop('Company', None) super(MultijournalForm, self).__init__(*args, **kwargs) self.fields['Debit'].widget.attrs = {'class': 'form-control',} self.fields['Credit'].widget.attrs = {'class': 'form-control',} self.fields['To'].widget.attrs = {'class': 'form-control select2',} self.fields['By'].widget.attrs = {'class': 'form-control select2',} self.fields['narration'].widget.attrs = {'class': 'form-control',} Multijournal_formSet = inlineformset_factory(Multijournaltotal, Multijournal, form=MultijournalForm, extra=6) I am facing a problem in updating my inline formset from quite a long time. The create view works perfectly fine but when I try to update the instances of Multijournal in Multijournaltotal then the objects are not shown in the formset... I tried this previously: class Multijournal_updateview(LoginRequiredMixin,UpdateView): model = Multijournaltotal form_class = MultijournaltotalForm template_name = 'Multijournal/multi_journal_form.html' def get_success_url(self,**kwargs): company_details = get_object_or_404(Company, pk=self.kwargs['pk']) multijournal_details = get_object_or_404(Multijournaltotal, pk=pk2) selectdatefield_details = get_object_or_404(Selectdatefield, pk=self.kwargs['pk3']) return reverse('accounting_double_entry:multijournaldetail', kwargs={'pk1':company_details.pk, 'pk2':multijournal_details.pk,'pk3':selectdatefield_details.pk}) def get_context_data(self, **kwargs): context = super(Multijournal_updateview, self).get_context_data(**kwargs) company_details = get_object_or_404(Company, pk=self.kwargs['pk']) context['company_details'] = company_details selectdatefield_details = get_object_or_404(Selectdatefield, pk=self.kwargs['pk3']) context['selectdatefield_details'] = selectdatefield_details multijournal_details = … -
Form Datefield passing None to post data form in django
I used boostrap datepicker for the datefield that capture date of birth, the problem i have is the datefield returning None which result to an error (1048, "Column 'st_dob' cannot be null"). model.py st_dob = models.DateField() forms.py st_dob = forms.DateField(label='Date Of Birth', widget=forms.DateInput(attrs={'class': 'dob_datepicker'})) view.py if request.method == 'POST': if student_form.is_valid(): print(request.POST.get('st_dob')) My part of boostrap date picker look like this $('.dob_datepicker').datepicker({ endDate: new Date(), autoclose: true, // close after insert format: 'yyyy-mm-dd', }); So it works on getting other post data but for this datefield it return none -
Django: how to repopulate and validate ModelForm with data from .csv file?
I need to hardcode a simple django app, which will allow me to validate ModelForm fields according to row data from .csv file. User is expected to select the correct value for each form field.(.csv file may contain also unnecessary columns, so I need to select only the values I need from a dropdown) If all fields are valid (after clicking a submit button) - > serialize this row data instance as JSON, else - ignore current row data, refresh the form page with new prepopulated fields from next row. The question is how to customize ArticleForm and ArticleTranclationForm to Make user be able to select corresponding value from dropdown for each field? models.py from django.db import models class Article(models.Model): identifier = models.CharField(unique=True, max_length=255) number = models.CharField(max_length=255) preview_image = models.CharField(max_length=255) tile_image = models.CharField(max_length=255) width = models.FloatField(blank=True, null=True) length = models.FloatField(blank=True, null=True) vendor_code = models.CharField(max_length=255, blank=True, null=True) verified = models.IntegerField() class Meta: abstract = True class ArticleTranslation(models.Model): name = models.CharField(max_length=255, blank=True, null=True) description = models.TextField(blank=True, null=True) rapport = models.CharField(max_length=255, blank=True, null=True) rapport_shift = models.CharField(max_length=255, blank=True, null=True) main_color = models.CharField(max_length=255, blank=True, null=True) country = models.CharField(max_length=255, blank=True, null=True) texture = models.CharField(max_length=255, blank=True, null=True) coating_type = models.CharField(max_length=255, blank=True, null=True) basis = models.CharField(max_length=255, blank=True, null=True) … -
Django ORM - find objects that a variable fits inbetween a range of model fields?
I am trying to find all django objects using an integer variable, where this variable is inbetween two django model fields. I understand using __range() is normally for finding if a model field is inbetween two variables, but I need it the other way around. models: class Location(models.Model): location_start = models.IntegerField() location_end = models.IntegerField() sample_id = models.ForeignKey(Sample, on_delete=models.CASCADE, db_column='sample_id') views ( doesnt work) : location_query = 1276112 loc_obj = Location.objects.filter( sample_id=sample_obj, location_query__range(location_start, location_end) ) Raw SQL: SELECT * FROM location WHERE sample_id=12 AND 1276112 BETWEEN location_start AND location_end Is there an easier way to do this without looping through the objects? -
How can I ensure uniqueness on a django model depending on the value?
The title may be slightly misleading, I essentially want to know how to ensure uniqueness on 1 type of attribute, but not on others. If I have a model 'MyModel' that has a related model called 'Settings', which sets certain attributes for MyModel, how do I ensure that there is only one default settings object? What is the best way to make sure that only one settings object is the default? I can put that 'default' and 'related_model' are unique_together, but this only allows for one non-default settings object as well. I'd like to get to the point where I can only have one default settings object, but no limit on non-default ones. MyModel attribute1 = x ... Settings related_model = MyModel default = boolean -
Rendering a Django HTML Template to a PDF file via Render_to_PDF displays unicodes caracters (like nepali caracters ) like a black squares
I want to render html template to a pdf . I followed the tutorial (https://www.youtube.com/watch?v=B7EIK9yVtGY) to render html template to a pdf. It was working perfectly when I used the html template with english words only , but when I used the nepali words in html template , it returns 'latin-1' codec can't encode characters in position 1058-1062: ordinal not in range(256) error . After changing utils.py , it render html template to pdf but displays nepali words like a black squares. utils.py import StringIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("utf-8")), result, encoding='UTF-8') if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None views.py class GeneratePDF(LoginRequiredMixin, View): def get(self, request,regid, *args, **kwargs): template = get_template('PrintPreview.html') context = {} context['municipality'] = config.Municipality context['registrationid'] = regid reg = NewRegistration.objects.get(id=regid) context['registration'] = reg context['application_status'] = reg.applicationstatus_set.all() context['application'] = get_related_object_or_none(reg.application_set) context['houseowner'] = reg.houseownerinfo_set.all() houseowner_names = ", ".join(reg.getAllHouseownerNpNameAsList()) if houseowner_names == "": context['houseowner_name'] = u"{} ({})".format(reg.houseowner_name_np, reg.houseowner_name_en) else: context['houseowner_name'] = houseowner_names context['landowner'] = reg.landowner_set.all() context['applicant'] = get_related_object_or_none(reg.applicant_set) context['landinformation'] = get_related_object_or_none(reg.landinformation_set) charkillas = reg.charkilla_set.all() for ch in charkillas: if ch.ch_direction == "n": context['charkilla_n'] = ch elif ch.ch_direction … -
Django: using a different view for GET and POST?
Using Django Class Based Views, I already have a ListView for Order objects, and I created a FormView to perform advanced searches on these orderers. However, I'm not sure how to pass the filtered queryset of the FormView to the ListView. Here is the code, with commented sections to explain the issue: class OrdersListView(PermissionRequiredCanHandleOrders, SelectRelatedMixin, PrefetchRelatedMixin, ModelInContextMixin, SubSectionLastOrders, RestaurantOrdersOnly, ListView): model = Order paginator_class = DiggPaginator paginate_by = 15 select_related = ('convive__user',) prefetch_related = ('orderoperation_set',) # will use the template named order_list.html class OrdersAdvancedSearchView(PermissionRequiredCanHandleOrders, ModelInContextMixin, SubSectionLastOrders, RestaurantOrdersOnly, RestaurantMixin, FormView): model = Order template_name = "orders/order_advanced_search.html" form_class = OrderAdvancedSearchForm def form_valid(self, form): data = form.cleaned_data queryset = Order.objects.all() # Here, I'm using the form content to filter the queryset # queryset = queryset.filter(some_attribute__in=data['stuff']) # MY PAIN POINT IS HERE: what I'm supposed to do here ? # my queryset is filtered, and I need to call OrderListView # with it. return super().form_valid(form) -
The difference between if item == "If" and if 'If' in item?
my code is here for index, item in enumerate(actdiagram, start=1): print(item+"&") # if item == "If": if 'If' in item: os.write(fd, ("if").encode('ascii')) indexOfIf = index elif index == (indexOfIf+1): os.write(fd, ("\"" + item + "\" then \n").encode('ascii')) else: os.write(fd, ("-->" + item + "\n").encode('ascii')) My Question is my code does not go through if item == "If"but it works fine for if 'If' in item: I wanted to know why it happen like this. -
How to show error message while save data from admin side.? i using models.model for create models
class Setting(models.Model): id=models.AutoField(primary_key=True, unique=True) ldap_server = models.CharField(max_length=100, default='ldap://yourDomain.in') ldap_server_username = models.CharField(max_length=100, null=True) ldap_server_password = models.CharField(max_length=100, null=True) def save(self, *args, **kwargs): ldap_server=self.ldap_server ldap_server_username = self.ldap_server_username ldap_server_password = self.ldap_server_password try: l = ldap.initialize(ldap_server) l.protocol_version = ldap.VERSION3 l.set_option(ldap.OPT_REFERRALS, 0) l.simple_bind_s(ldap_server_username, ldap_server_password) super(Setting, self).save(*args, **kwargs) except: messages.error(request, "You have logged in..!") here i faced the error in messages.error(request, "You have logged in..!").... i can't use messages.error(request, "You have logged in..!"). anybody know alternative way to show error message. Thaks in advance. -
how to configure static files when deploy apps in real hosting server (production)
hello im just moving from development to production stage of my django apps, now i just paid for a hosting service from my country that support for python setup app its currently using cpanel, its deployed greatly but i just realize i need to change the DEBUG = True, to DEBUG = FALSE but after alter it to DEBUG = False, the apps style start to broken, because the css (static files) didnt loaded, can someone give me a pointer of how to do the static files configuring in production? im using cpanel and the provider didnt let me edit any of the server configuration -
Extend inherited from Parent Class variable value(s) in Child class, and pass the value(s) to a Django template
I have the following code: Class Parent(TemplateView): css_class = None # can be also an empty list or a list with strings Class Child(Parent): css_class = ['site'] I have a variable css_class that can exist or not on the Parent Class(es), can be None, and empty list [], or a list of strings ['site', 'global'] On the Child class I want to check if that variable exist: If exist and is a non-empty list, check the Parent list, and expand the list with the variables in the child variable, only if there are no duplicates. Example; Parent - > css_class = ['site', global'] Child -> css_class = ['site', 'listing'] Child Result -> css_class = ['site', 'global','listing'] If is none or empty list, remains the one declared on the Child class In a Django Template add on the body the classes, something like: <body {% if css_class %}class="{{ css_class }}"{% endif %}> The code above works only for a classes. For multiple I will add a for loop, but I need to add space between classes if they are more. -
I downloaded an excel or csv file in Firefox Browser but the suffix disappeared
When I try to download excel or csv file in Firefox Browser, what I get is a file with the right filename but no suffix, what happened? def download(request, id): apply_info = TextDataApplyLogs.objects.filter(id=id).first() filename = apply_info.download_file_name file_type = filename.split('.')[1] with open(os.getcwd() + '/static/files/text_data_open/' + filename, 'rb') as f: data = f.read() res_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' if file_type == 'xlsx' else 'text/csv' response = HttpResponse(data, content_type=res_type) response['Content-Disposition'] = 'attachment; filename={}'.format(filename) return response -
Update / edit django object after selecting it from a dropdown list
I want to update / edit a product from a page by clicking a form button (UPDATE) after selecting product from a dropdown list. List.html page works fine while clicking on UPDATE button update.html page cannot parse the POST data. Manually I could access update.html with pk suffix (/update/1/), it is working fine too. How can I pass pk's value alone to url? views.py class ProductUpdateView(UpdateView): template_name = 'update.html' model = Product fields = ['name', 'description', 'image', 'file',] success_url = '/list/' class ProductsView(ListView,): template_name = 'list.html' model = Product urls.py urlpatterns = [ url(r'^list/$', ProductsView.as_view(), name='list'), url(r'^update/(?P<pk>[0-9]+)/$', ProductUpdateView.as_view(), name='update'), ] list.html <body> <form method='POST' action='/update/'> {% csrf_token %} <select name='pk'> {% for obj in object_list %} <option value='{{ obj.id }}'>{{ obj.name }}</option> {% endfor %} </select> <input type="submit" value='UPDATE'> </form> </body>