Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django authentication with active directory cause 500 internal error
I have Django web app running on production server CentosOs-7. I'm trying to authenticate my user through the corporate Active Directory server. However, I'm encountering 500 internal server error when I visit my web app. So I've looked at httpd log file, I've found that Tue Apr 21 18:15:09.372866 2020] [:error] [pid 32508] [remote 100.120.96.54:21376] mod_wsgi (pid=32508): Exception occurred processing WSGI script '/opt/BsP_v0/kwnProtclBsline_proj/kwnProtclBsline_proj/wsgi.py'. [Tue Apr 21 18:15:09.372884 2020] [:error] [pid 32508] [remote 100.120.96.54:21376] Traceback (most recent call last): [Tue Apr 21 18:15:09.372897 2020] [:error] [pid 32508] [remote 100.120.96.54:21376] File "/opt/BsP_v0/kwnProtclBsline_proj/kwnProtclBsline_proj/wsgi.py", line 16, in <module> [Tue Apr 21 18:15:09.372917 2020] [:error] [pid 32508] [remote 100.120.96.54:21376] application = get_wsgi_application() [Tue Apr 21 18:15:09.372924 2020] [:error] [pid 32508] [remote 100.120.96.54:21376] File "/opt/BsP_v0/kwnProtclBsline_proj/venv/lib/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application [Tue Apr 21 18:15:09.372936 2020] [:error] [pid 32508] [remote 100.120.96.54:21376] django.setup(set_prefix=False) [Tue Apr 21 18:15:09.372942 2020] [:error] [pid 32508] [remote 100.120.96.54:21376] File "/opt/BsP_v0/kwnProtclBsline_proj/venv/lib/python2.7/site-packages/django/__init__.py", line 22, in setup [Tue Apr 21 18:15:09.372950 2020] [:error] [pid 32508] [remote 100.120.96.54:21376] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Tue Apr 21 18:15:09.372955 2020] [:error] [pid 32508] [remote 100.120.96.54:21376] File "/opt/BsP_v0/kwnProtclBsline_proj/venv/lib/python2.7/site-packages/django/conf/__init__.py", line 56, in __getattr__ [Tue Apr 21 18:15:09.372963 2020] [:error] [pid 32508] [remote 100.120.96.54:21376] self._setup(name) [Tue Apr 21 18:15:09.372967 2020] [:error] [pid 32508] [remote 100.120.96.54:21376] File … -
Django-oscar less css
OSCAR_USE_LESS = True DEBUG = True In Oscar Documentation, it says that you can view compiled css via browser after a reload(F5) but my pages show without a CSS effect on them. What am I missing <link rel="stylesheet/less" type="text/css" href="{% static "oscar/less/styles.less" %}" /> <script src="//cdnjs.cloudflare.com/ajax/libs/less.js/3.9.0/less.min.js" ></script> -
Django Jinja - If an object in all objects has attribute run html
I'm needing help figuring out how to write code for this problem (in title). Let's say I have this model: from django.db import models class Section(models.Model): name = models.CharField(max_length=20) display = models.BooleanField(default=True) and I create 2 objects with different names and 2 different display variables: >>> s1.display True >>> s2.display False Here I have some HTML code with Jinja templating for this code to display, if these objects even exist: <!-- In Views, Section.objects.all() is 'sections' --> {% if sections %} <div class="all-sections"> <h2 class="title">Explore</h2> {% for section in sections %} <div class="section"> <p class="section-title">{{ section.name }}</p> </div> {% endfor %} </div> {% endif %} Now I make both of them false: >>> s1.display = False >>> s1.save() Now, if ALL OF THEM HAVE DISPLAY FALSE I don't want the entire section to be there, the same as if there weren't any in that list at all. I've thought about doing a for loop and iterating through each one, but then that would just repeat the all of the HTML code for each one that did have display on. <!-- Wouldn't Work Example --> {% if sections %} {% for section in sections %} {% if section.display %} <div class="all-sections"> … -
Django Update view saving but not updating
I have made a working form to post reviews for restaurants. When user is logged in he can see displayed under his post the edit button. When I use the Updateview however, it doesn't edit, but instead creates a new line in which the new review appears (and that new line doesn't appear then on my webpage). Here is the model: class UserReview(models.Model): # Defining the possible grades Grade_1 = 1 Grade_2 = 2 Grade_3 = 3 Grade_4 = 4 Grade_5 = 5 # All those grades will sit under Review_Grade to appear in choices Review_Grade = ( (1, '1 - Not satisfied'), (2, '2 - Almost satisfied'), (3, '3 - Satisfied'), (4, '4 - Very satisfied'), (5, '5 - Exceptionally satisfied') ) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) user_review_grade = models.IntegerField(default=None, choices=Review_Grade) # default=None pour eviter d'avoir un bouton vide sur ma template user_review_comment = models.CharField(max_length=1500) posted_by = models.ForeignKey(User, on_delete=models.DO_NOTHING) def get_absolute_url(self): return reverse('restaurants:reviews', args=[self.id]) def get_edit_url(self): return reverse('restaurants:edit-review', args=(self.id,)) Here is the update form (similar as review form): class EditReviewForm(forms.ModelForm): class Meta: model = UserReview fields = [ 'restaurant', 'user_review_grade', 'user_review_comment' ] widgets = { 'restaurant': forms.HiddenInput, 'user_review_grade': forms.RadioSelect, 'user_review_comment': forms.Textarea } labels = { 'user_review_grade': 'Chose a satisfaction level:', … -
Use Matplotlib on django site
I am thinking of starting a new django project for plotting stock prices and displaying them onto the site. I know matplotlib pretty well and was wondering if I could plot the chart and somehow push it to the site with the usual matplotlib features like zoom etc. I have seen this done where that images are pushed but I am wondering if I could push the chart with its functionality provided by matplotlib and I can't seem to find an answer anywhere so maybe it isn't possible? -
how to override django admin delete confirmation page?
When i tried to delete an object which has 500 related objects. delete confirmation page talking so long to render related objects. how to override it so that it will not show related objects in the delete confirmation page. but it will delete it in the background. -
Django get values for Max of grouped data
After many trials and errors and checking similar questions, I think it worth asking it with all the details. Here's a simple model. Let's say we have a Book model and a Reserve model that holds reservation data for each Book. class Book(models.Model): title = models.CharField( 'Book Title', max_length=50 ) name = models.CharField( max_length=250 ) class Reserve(models.Model): book = models.ForeignKey( Book, on_delete=models.CASCADE ) reserve_date = models.DateTimeField() status = models.CharField( 'Reservation Status', max_length=5, choices=[ ('R', 'Reserved'), ('F', 'Free') ] ) I added a book and two reservation records to the model: from django.utils import timezone book_inst = Book(title='Book1') book_inst.save() reserve_inst = Reserve(book=book_inst, reserve_date=timezone.now(), status='R') reserve_inst.save() reserve_inst = Reserve(book=book_inst, reserve_date=timezone.now(), status='F') reserve_inst.save() My goal is to get data for the last reservation for each book. Based on other questions, I get it to this point: from django.db.models import F, Q, Max reserve_qs = Reserve.objects.filter( book__title='Book1' ).values( 'book__title' ) reserve_qs now has the last action for each Book, but when I add .value() it ignores the grouping and returns all the records. I also tried filtering with F: Reserve.objects.filter( book__title='Book1' ).values( 'book__title' ).annotate( last_action=Max('reserve_date') ).values( ).filter( reserve_date=F('last_action') ) I'm using Django 3 and SQLite. -
Django form is saying field is required despite providing value
I have a form with a required field customer_phone_number and despite passing a phone number in with the data the form isn't valid.. class OrderForm(forms.ModelForm): class Meta: model = models.Order fields = ( 'date', 'customer_phone_number', ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['customer_phone_number'].required = True self.fields['customer_phone_number'].widget = PhoneNumberPrefixWidget() data = { 'date': '2020-04-20', 'customer_phone_number': '+17168567800', } form = OrderForm(data=data) form.is_valid() print(form.errors) # {'customer_phone_number': ['This field is required.']} The only thing I can think of is that I'm using a custom widget but I have no idea how to correct this error. from phonenumber_field.phonenumber import PhoneNumber from django.forms import Select, TextInput from django.forms.widgets import MultiWidget class PhonePrefixSelect(Select): initial = '+1' def __init__(self, attrs=None): choices = [('+1', '+1')] super().__init__(attrs, choices=sorted(choices, key=lambda item: item[1])) def render(self, name, value, *args, **kwargs): return super().render( name, value or self.initial, *args, **kwargs) class PhoneNumberPrefixWidget(MultiWidget): """ A Widget that splits phone number input into: - a country select box for phone prefix - an input for local phone number """ def __init__(self, attrs=None): widgets = ( PhonePrefixSelect(attrs={ 'class': 'form-control w-25 mr-2', 'tabindex': '-1' }), TextInput(attrs={ 'class': 'form-control w-75' }), ) super().__init__(widgets, attrs) def decompress(self, value): if value: if type(value) == PhoneNumber: if value.country_code and value.national_number: return ["+%d" % … -
Reuse django urls patterns and views
I have a usecase where I would like to reuse a bunch of existing views and url patterns. Current situation is a product with about 20 views for it: urlpatterns = [ # product url(r'^product/(?P<pid>\d+)$', views.view_product, name='view_product'), url(r'^product/(?P<pid>\d+)/something$', views.view_something, name='view_something'), url(r'^product/(?P<pid>\d+)/morethings', views.view_morethings, name='view_morethings'), url(r'^product/(?P<pid>\d+)/deeper/things$', views.view_deeper_things, name='view_deeper_things'), ... etc. So I can browse to the following urls: https://host/product/1 https://host/product/1/something https://host/product/1/morethings https://host/product/1/deeper/things In the new situation I want to add additional ways to browse to the products, i.e. product name or some key valuepair. i.e. https://host/product/name/product1 https://host/product/name/product1/something https://host/product/name/product1/morethings https://host/product/name/product1/deeper/things and https://host/product/meta/property1/value1 https://host/product/meta/property1/value1/something https://host/product/meta/property1/value1/morethings https://host/product/meta/property1/value1/deeper/things where I use a database query in the view to find the product by name, or by the specified property+value. How can I reuse patterns and views to avoid having 20 new views and patterns for each way of identifying a product? I could just list all the (20x3) possible patterns and add 20 more for each new way of identifying products. url(r'^product/(?P<pid>\d+)/something$', views.view_something, name='view_something'), url(r'^product/(?P<pid>\d+)/morethings', views.view_morethings, name='view_morethings'), url(r'^product/(?P<pid>\d+)/deeper/things$', views.view_deeper_things, name='view_deeper_things'), url(r'^product/name/<str:name>/something$', views.view_something_name, name='view_something_name'), url(r'^product/name/<str:name>/morethings', views.view_morethings_name, name='view_morethings_name'), url(r'^product/name/<str:name>/deeper/things$', views.view_deeper_things_name, name='view_deeper_things_name'), url(r'^product/meta/key/<str:name>/<str:name>/something$', views.view_something_meta, name='view_something_meta'), url(r'^product/meta/key/<str:name>/<str:name>/morethings', views.view_morethings_meta, name='view_morethings_meta'), url(r'^product/meta/key/<str:name>/<str:name>/deeper/things$', views.view_deeper_things_meta, name='view_deeper_things_meta'), I know I could do: urlpatterns = [ # product url(r'^product/(?P<pid>\d+)$', views.view_product, name='view_product'), url(r'^product/name/<str:name>$', views.view_product, name='view_product_by_name'), And have default … -
Django Template `With` Operator complex boolean assignment
I am creating a Django template that has columns only visible to admins. Currently I am using a template tag has_group that works well. I have to include some logic for superusers. {% if request.user|has_group:"Admins" or request.user.is_superuser %} <th class="detail_btn_col" scope="col">Detail</th> {% endif %} ... Similar code for the <td> But it's making a query for every row of a table. Not terrible but I would like to just set the value once at the start of the template. I saw that I could assign a variable using with and that would accomplish what I want. {% with has_admin_view=request.user|has_group:"Admins" or request.user.is_superuser %} Does not work. {% with has_admin_view=request.user|has_group:"Admins" %} The above works, but superusers aren't included. Is there a way to do AND/OR operations in Django template's WITH statement? -
Django rest framework serialize model with FK
I'm learning Django and Vuejs. There is something I'm not understanding how it works. I have a model "Nc" wich have some foreign key to other models like Affaire. How can i obtaines in my JSON files the str return for instances instead of the real value... models.py : class Affaires(models.Model): id = models.PositiveSmallIntegerField(primary_key=True) nom = models.CharField(max_length=50) adresse = models.CharField(max_length=100, blank=True, null=True) cp = models.CharField(max_length=5, blank=True, null=True) ville = models.CharField(max_length=50, blank=True, null=True) dessinateur = models.PositiveSmallIntegerField(blank=True, null=True) conducteur = models.PositiveSmallIntegerField(blank=True, null=True) chefdeprojet = models.PositiveSmallIntegerField(blank=True, null=True) cloture = models.IntegerField() class Meta: managed = True db_table = 'affaires' def __str__(self): return '{} - {}'.format(self.id, self.nom) class NC(models.Model): idaffaire = models.ForeignKey(Affaires, models.DO_NOTHING,verbose_name="N° d'affaire", db_column='idAffaire') idof = models.ForeignKey(AffairesOfs, models.DO_NOTHING,verbose_name="N° d'OF", db_column='idOf') idposte = models.ForeignKey(ProductionPostes, models.DO_NOTHING,verbose_name="Poste", db_column="idPoste") idrepere = models.ForeignKey(AffairesReperes, models.DO_NOTHING,verbose_name="Repère", db_column='idRepere') idnc = models.ForeignKey(Nc_type, models.DO_NOTHING,verbose_name="Type de NC", db_column='idNc_type') quantite = models.PositiveIntegerField(verbose_name="Quantité") dateajout = models.DateField(default=timezone.now, verbose_name="Date d'ajout", db_column='dateAjout') class Meta: managed = True db_table = 'qualite_Nc' serialize.py class NcSerializer(serializers.ModelSerializer): class Meta: model = NC fields = '__all__' JSON files : { "id": 1, "quantite": 1, "dateajout": "2020-04-08", "idaffaire": 1145, "idof": 1433, "idposte": 6271, "idrepere": 5361, "idnc": 1 }, { "id": 2, "quantite": 17, "dateajout": "2020-04-09", "idaffaire": 1205, "idof": 1290, "idposte": 5812, "idrepere": 7004, "idnc": 1 }, … -
Null field in database
I have a form with conditionned field my problem is that empty field is registered instead of NULL in database 2 last fields are conditionned on selected value just before (ran_bug) my 2 conditionned fields are required = false (even it should not be necessary ?) in my models, this fields are null=True and blank=True class Randomisation(models.Model): ran_ide = models.AutoField(primary_key=True) pay_ide = models.CharField("Patient's country code", max_length=2, null=True, blank=True) ran_str_num = models.CharField("Logical numerotation", max_length=2, null=True, blank=True) ran_bra = models.CharField("Arm", max_length=1, null=True, blank=True) bra_lib = models.CharField("Arm label", max_length=50, null=True, blank=True) ran_act = models.IntegerField("Activated line", null=True, blank=True) pat = models.CharField("Patient number", max_length=12, unique=True, null=True, blank=True) ran_nai = models.IntegerField("Patient birthdate (year)", blank=True) ran_sex = models.IntegerField("Sex", null=True, blank=True) ran_st1 = models.IntegerField("Stratification variable 1", blank=True) ran_st2 = models.IntegerField("Stratification variable 2", blank=True) ran_bug = models.IntegerField("Use of alternative randomization procedure?", null=True, blank=True) ran_dem_nom = models.CharField("Name of the person asking for randomization", max_length=12, null=True, blank=True) ran_dem_dat = models.DateTimeField("Date of demand", null=True, blank=True) ran_log = models.DateTimeField("User", null=True, blank=True) ran_dat = models.DateTimeField("Date", null=True, auto_now_add=True, blank=True) forms.py class RandomizationEditForm(forms.ModelForm): def __init__(self, request, *args, **kwargs): super(RandomizationEditForm, self).__init__(*args, **kwargs) self.user_country = request.session.get('user_country') self.language = request.session.get('language') self.user_site_type = request.session.get('user_site_type') PAYS = Pays.options_list(self.user_country,self.user_site_type,self.language) SEXE = [(None,''),(1,'Male'),(2,'Female')] STRATE_1 = [(None,''),(1,'strate 1 condition 1'),(2,'strate 1 condition 2')] STRATE_2 … -
Django facebook auth
Does django-social-auth cannot use for facebook auth anymore? As I trying to do a Django web app for fb auth but it just show a error: Authentication process canceled, any other ways for facebook auth in Django? -
How to save a string without explicit escaping?
I am trying to make my Django based API return an HTML snippet as a string. I am retrieving the HTML snippet through a BeautifulSoup bs4 element. To convert it into a string, I am simply using the str() operation as follows: test['key'] = str(bs4_element) When I retrieve this value from an API call, I get the HTML code, however, with backslash characters inserted throughout to escape special characters, somewhat like this: "key": "<div class=\"hackdown\"><style id=\"MathJax_SVG_styles\">... I want to render this retrieved HTML in a browser, however, the introduced backslash characters are not letting me do the same. How do I convert the bs4 element such that the above is prevented? -
Printing logs (of the running website) in VSCode console
hi all I have a web built with django framework and running with apache now. I am trying to print() but nothing is shown on the console, so I turned to logger and no luck still. This is one of my log I tried to print in the view.py, and I was expecting 'helloworld' could be shown on my console... import logging logger = logging.getLogger(__name__) logger.info('helloworld') is there anything i should be setting elsewhere? kindly help, thanks. -
Django conditional for rendering template
I am new to django and am trying to only render text which does not have the word 'After' or 'Before' in it. However this didnt break anything but it didnt actually remove those values? I looked at using a regex but this really isnt recommended for django templates. {% if "After" not in window.name or "Before" not in window.name %} {{window.event_id}}-{{window.name}} {% endif %} The codebase I am working on makes it almost impossible to remove these values in the models before you get to the template... I can only apologise for maintaining and putting up with this! -
Django modify table with jquery and ajax
I have a problem with my code. I'm trying to modify a data table utilizing the ajax code but does not work. I have create the json response in my view and add the script in my html code. When I try to edit my id.element in my shell recevice the following message: "GET /magazzino/?formId=1&formCodice=1&formCategoria=MATERIA+PRIMA&formSottocategoria=ciao HTTP/1.1" 200 16137". I don't know if it will help. This is my html code: {% extends "base/base.html" %} {% load crispy_forms_tags %} {% block content %} <main role="main" class="col-md-9 ml-sm-auto col-lg-10 px-4"> .... <h1>Approvvigionamenti</h1> <div class="row"> <div class="col-md-12 "> <h3>Registra materiale acquistato</h3> <form id="addUser" method="post"> {% csrf_token %} <div class="form-row"> <div class="form-group col-2 0 mb-0"> {{form.codice|as_crispy_field}} </div> <div class="form-group col-5 0 mb-0"> {{form.tipologia|as_crispy_field}} </div> <div class="form-group col-5 0 mb-0"> {{form.sottocategoria|as_crispy_field}} </div> </div> <div class="form-row"> <div class="col-md-2 "> <button class="btn btn-primary form-control" type="submit">Registra nel magazzino</button> </div> </div> </form> </div> <div class="col-md-12"> <br> <h3>Materiale registrato</h3> <table id="userTable" class="table table-striped"> <tr> <th>Codice</th> <th>Tipologia</th> <th>Sottocategoria</th> </tr> {% if materiale %} {% for element in materiale %} <tr id="element-{{element.id}}"> <td class="codice userData" name="codice">{{element.codice}}</td> <td class="categoria userData" name="categoria">{{element.tipologia}}</td> <td class="sottocategoria userData" name="sottocategoria">{{element.sottocategoria}}</td> <td align="center"> <button class="btn btn-success form-control" onClick="editUser({{element.id}})" data-toggle="modal" data-target="#myModal"> Modifica</button> </td> <td align="center"> <button class="btn btn-danger form-control" onClick="deleteUser({{user.id}})">DELETE</button> … -
Django Rest Framework, Why does separate serialization class for Image fields is been required?
When serializing a model that contain image field, separate serialization class was been required. Why can't we serialize the model completely in single class ? Serializer.py class ProfileSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField(read_only=True) avatar = serializers.ImageField(read_only=True) class Meta: model = Profile fields = '__all__' class AvatarSerializer(serializers.ModelSerializer): class Meta: model = Profile fields =('avatar',) models.py class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) bio = models.CharField(max_length=100,blank=True) avatar = models.ImageField(null=True,blank=True) def __str__(self): return self.user.username I am following a tutorial in Udemy GitLink : https://github.com/pymike00/The-Complete-Guide-To-DRF-and-VueJS/tree/master/05-DRF-LEVEL-THREE/profilesapi/profiles/api -
CSS loaded but not takes effect on the display
I always get stuck at CSS. I have a table, which works perfectly fine on large screens, and for mobile devices I want the table to be in a card format. I got an idea of creating another div and made the UI for mobile devices as well. And Using CSS, I tried... resp.css .immobile{ display: none; } .immonitor{ display: block; } @media screen and (max-width: 764px){ .immonitor{ display: none; } .immobile{ display: block; } } List.html <tbody> {% for order in order_list %} <div class="immonitor"> <tr> <td>{{ order.id }}</td> <td>{{order.client_name}}</td> <td>{{order.event_name}}</td> <td>{{order.event_date}}</td> <td>{{order.location}}</td> <td><a href="{% url 'order_detail' order.id %}">View</a></td> </tr> </div> <div class="immobile"> <tr> <td> <div> {{order.client_name}} <br> <h3>{{ order.id }}</h3> </div> <div class="pull-right"> {{order.event_name}}<br> {{order.event_date}}<br> {{order.location}}<br> </div> </td> </tr> </div> {% endfor %} </tbody> Now, the CSS doesn't have any effect on the table, it displays both card and table. And the CSS is perfectly loaded. -
Django getting the option value from a drop down menu
I am creating a Django page and I have two drop down menus. The first drop down menu will select a test. Then based on whatever test they selected, it should populate the second drop down menu with some ManyToMany fields. Here is my drop down menus <form> <select name="test"> {% for test in test %} <option value={{ test.name }}>{{ test.name }}</option> {% endfor %} </select> </form> <form> <select name="event"> {% for applicable_events in test %} <option value={{ applicable_events.name }}>{{ applicable_events.name }}</option> {% endfor %} </select> <input type="submit" value="Submit"> </form> The first form is correctly populating all of my tests. Now when the user selects one of the options in the first drop down, I am trying to get whatever they selected so that I can then populate the second drop down. Here are my two models.. class Event(models.Model): name = models.CharField(max_length=255) #test = models.ManyToManyField(Test) applicable_devices = models.ManyToManyField(Device) applicable_platforms = models.ManyToManyField(Platform) class Meta: verbose_name = 'Event' verbose_name_plural = 'Events' def __str__(self): return self.name class Test(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255, blank=True) applicable_device = models.ManyToManyField(Device) applicable_platform = models.ManyToManyField(Platform) applicable_events = models.ManyToManyField(Event) class Meta: verbose_name = 'Test' verbose_name_plural = 'Tests' def __str__(self): return self.name So you can see that for each … -
NoReverseMatch at /admin/r/1/APT2/ Reverse for 'apartment_create' not found. 'apartment_create' is not a valid view function or pattern name
I am trying to display a template on Django 3.0 and I get NoReverseMatch Error. Obviously, the url.py and views.py fail to show the template. I am on admin page adding a new record, but when I click show on site, I get this error. 1) What is the first part of admin/r/1/APT2 url mean especially the r/1? I believe this should redirect to apartment_create.html, but the view function does not exist or there is no url by that name. But according to me, there is. NoReverseMatch at /admin/r/1/APT2/ Reverse for 'apartment_create' not found. 'apartment_create' is not a valid view function or pattern name. views.py class ApartmentCreate(CreateView): # make a form based on this model form_class=ApartmentForm # if we only want to edit these two fields # fields = ('first_name', 'last_name') fields = '__all__' class Meta: widgets = {'geom': LeafletWidget()} # render this html file, pass a form object to that file template_name = 'rent_app:apartment_create.html' #template_name = 'rent_app/form_template.html' def get_success_url(self): return reverse('rent_app:apartment_create_success') urls.py from django.urls import path from . import views from django.contrib import admin app_name = 'rent_app' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('admin/', admin.site.urls), path('apartment_create/<slug:apt_id>', views.ApartmentCreate.as_view(), name='apartment_create'), path('apartments/<int:pk>/', views.ApartmentUpdate.as_view(), name='apartment_update'), path('apartments/<int:pk>/delete/', views.ApartmentDelete.as_view(), name='apartment_delete'), -
Error during template rendering (NoReverseMatch) in Django
I am trying to submit the form to my view: in trending.html: {% extends 'djangobin/base.html' %} {% load static %} {% load humanize %} {% block title %} Trending {{ lang.name }} Snippets - {{ block.super }} {% endblock %} {% block main %} <h5><i class="fas fa-chart-line"></i> Trending {{ lang.name }} Snippets</h5> <hr> <table class="table"> <thead> <tr> <th>Title</th> <th>Date</th> <th>Hits</th> <th>Language</th> <th>User</th> </tr> </thead> <tbody> {% for snippet in snippets %} <tr> <td><i class="fas fa-globe"></i> <a href="{{ snippet.get_absolute_url }}">{{ snippet.title }}</a> </td> <td title="{{ snippet.created_on }}">{{ snippet.created_on|naturaltime }}</td> <td>{{ snippet.hits }}</td> <td><a href="{% url 'trending_snippets' snippet.language.slug %}">{{ snippet.language }}</a></td> {% if not snippet.user.profile.private %} <td><a href="{{ snippet.user.profile.get_absolute_url }}">{{ snippet.user.username|title }}</a></td> {% else %} <td>-</td> {% endif %} </tr> {% empty %} <tr class="text-center"> <td colspan="4">There are no snippets.</td> </tr> {% endfor %} </tbody> </table> {% endblock %} in views.py: from django.shortcuts import HttpResponse, render, redirect, get_object_or_404, reverse from .forms import SnippetForm from .models import Language, Snippet def trending_snippets(request, language_slug=''): lang = None snippets = Snippet.objects if language_slug: snippets = snippets.filter(language__slug=language_slug) lang = get_object_or_404(Language, slug=language_slug) snippets = snippets.all() return render(request, 'djangobin/trending.html', {'snippets': snippets, 'lang': lang}) in urls.py: from django.conf.urls import url from . import views as views urlpatterns = [ url('^trending/$', … -
Django Sum positive values seperate from negative values
Can you sum positive values seperately from negative values? I have a table that looks like this: class Order(models.Model): date = models.DateField() amount = models.DecimalField() I'm looking to get a queryset that sums the postive amounts seperate from the negative amounts and groups by week: Year Week Sum of positive amounts Sum of negative amounts I'm able to get all positive amounts per week seperately by doing: Order.objects.filter(amount__gt=0).annotate(year_week=Trunc('date', 'week', output_field=DateField())).\ annotate(year=ExtractYear('year_week')).annotate(week=ExtractWeek('year_week')).\ values("year_week", "year", "week").annotate(value=Sum("amount")).order_by("-year_week") I can do this again for the negative value, but then I have two seperate querysets. Can I merge them efficiently without looping manually or is there a way to do both in a single query? -
How to correct TypeError: Unicode-objects must be encoded before hashing? - django - python
Does anyone know how to solve the following error ------activation_key = hashlib.sha1(short_hash+base).encoding.hexdigest() TypeError: Unicode-objects must be encoded before hashing----- all the code regarding the problem is attached below. All help appreaciated! import stripe import random import hashlib from django.conf import settings from django.contrib.auth.signals import user_logged_in from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile, UserStripe, EmailConfirmed stripe.api_key = settings.STRIPE_SECRET_KEY def get_create_stripe(user): new_user_stripe, created = UserStripe.objects.get_or_create(user=user) if created: customer = stripe.Customer.create( email = str(user.email) ) new_user_stripe.stripe_id = customer.id new_user_stripe.save() @receiver(post_save, sender=User) def create_profile(sender, instance, created, *args, **kwargs): user=instance if created: get_create_stripe(user) email_confirmed, email_is_created = EmailConfirmed.objects.get_or_create(user=user) if email_is_created: short_hash = hashlib.sha1(str(random.random()).encode('utf-8')).hexdigest()[:5] base, domain = str(user.email).split("@") activation_key = hashlib.sha1(short_hash+base).encode('utf-8').hexdigest() email_confirmed.activation_key = activation_key email_confirmed.save() emailconfirmed.activate_user_email() -
'NoneType' object has no attribute in the form init
Gives me that error 'NoneType' object has no attribute 'tutor_courses', i am trying to get query set with courses where request.user is in the tutor field. How to fix that? models.py class Course(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=150, null=True, blank=True) description = models.TextField() image = models.ImageField(upload_to='courses/course_images',blank=True,null=True) cover = models.ImageField(upload_to='courses/course_covers',blank=True,null=True) tutor = models.ForeignKey(User,related_name='tutor_courses',on_delete=models.CASCADE) students = models.ForeignKey(User,related_name='course_students',blank=True,on_delete=models.CASCADE,null=True) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) category = models.ForeignKey(CourseCategories,on_delete=models.CASCADE) certificate = models.ImageField(upload_to='courses/course_certificates',blank=True,null=True) languages = LanguageField(blank=True) rank_score = models.FloatField(default=0.0) price = models.FloatField(default=0.0) discount_price = models.FloatField(blank=True, null=True) forms.py class SectionForm(forms.ModelForm): def get_tutor_courses(self): return self.user.tutor_courses course = forms.ModelChoiceField(queryset=Course.objects.all()) def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super(SectionForm, self).__init__(*args, **kwargs) tutor_courses = user.tutor_courses.all() self.fields['course'].queryset = tutor_courses if not tutor_courses: self.fields['course'].help_text = "You need to <b>create</b> a course to create sections in it" class Meta: model = CourseSections fields = ('title','course')