Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send email via SendGrid instead of a file-based EmailBackend in Django
I'm using a file-based EmailBackend in Django. I don't want to store emails in a folder, instead, I want to use SendGrid. I'm following this tutorial here: https://learndjango.com/tutorials/django-password-reset-tutorial?msclkid=0c678f63ac0211ec9f8ff2047d0a934e Here's the concerned part of settings.py: EMAIL_BACKEND = "django.core.mail.backends.filebased.EmailBackend" EMAIL_FILE_PATH = BASE_DIR + "/sent_emails" All emails are stored in this folder /sent_emails. I don't want to do this. The tutorial linked above mentions MailGun and SendGrid, but it doesn't detail how to use that there. This is the Python code required to send an email via SendGrid, but because I'm using Django's built-in reset password facility (which I'm trying to do here), I do not think this is going to be of much help alone, not added to some sort of event that Django provides: message = Mail( from_email='jeff@example.com', to_emails='bob@example.com', subject='Greetings in different languages', html_content=" <ul> <li>Spanish: Hola!</li> <li>French: Salut!</li> <li>Japanese: こんにちは!</li> <li>German: Hallo!</li> <li>Italian: Ciao!</li> </ul> ") try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e.message) The email data above is only an example, and in the app I do not intend to use it (BTW I'm polylingual). Do you know how to do this? -
Django Circular Import Issue
I am having a Circular Import Error, even thought I do not have imports going both ways between apps. Here are the 2 apps models I have, please tell me what am I doing wrong? Also, I was working on some views and suddenly this error appeared, before that I was working just fine with no issues. App 1: from django.db import models from django.contrib.auth.models import AbstractUser from django.urls import reverse from django.template.defaultfilters import slugify from .utils import * from .constants import * class City(models.Model): title = models.CharField(max_length=45) posted = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: verbose_name = "Ville" verbose_name_plural = "Villes" def __str__(self): return self.title class Account(AbstractUser): phone = models.CharField(max_length=15, null=True, blank=True) phone_verified = models.BooleanField(default=False) email_verified = models.BooleanField(default=False) address = models.TextField(null=True, blank=True) dobd = models.CharField(max_length=2, choices=DAYS, null=True, blank=True) dobm = models.CharField(max_length=9, choices=MONTHS, null=True, blank=True) doby = models.CharField(max_length=4, null=True, blank=True) city = models.ForeignKey(City, on_delete=models.DO_NOTHING, null=True, blank=True) gender = models.CharField(max_length=5, choices=GENDERS, null=True, blank=True) profilepic = models.FileField(upload_to="profile_pics/", null=True, blank=True) points = models.IntegerField(default=0) lat = models.CharField(max_length=50, null=True, blank=True) lon = models.CharField(max_length=50, null=True, blank=True) captcha_score = models.FloatField(default=0.0) updated = models.DateTimeField(auto_now=True) receive_sms = models.BooleanField(default=True) receive_email = models.BooleanField(default=True) new = models.BooleanField(default=True, editable=False) class Meta: verbose_name = "Compte" verbose_name_plural = "Comptes" def __str__(self): return self.username class UserModel(Account): … -
Django heroku push gives could not build wheels for backports.zoneinfo error
I am trying to push a django project to heroku. heroku create worked fine but when trying to push to heroku main I get the following error. ''' Enumerating objects: 5317, done. Counting objects: 100% (5317/5317), done. Delta compression using up to 2 threads Compressing objects: 100% (1852/1852), done. Writing objects: 100% (5317/5317), 72.93 MiB | 134.00 KiB/s, done. Total 5317 (delta 4004), reused 4506 (delta 3415) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> No Python version was specified. Using the buildpack default: python-3.10.4 remote: To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.10.4 remote: -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting asgiref==3.4.1 remote: Downloading asgiref-3.4.1-py3-none-any.whl (25 kB) remote: Collecting backports.zoneinfo==0.2.1 remote: Downloading backports.zoneinfo-0.2.1.tar.gz (74 kB) remote: Installing build dependencies: started remote: Installing build dependencies: finished with status 'done' remote: Getting requirements to build wheel: started remote: Getting requirements to build wheel: finished with status 'done' remote: Preparing metadata (pyproject.toml): started remote: Preparing metadata (pyproject.toml): finished with status … -
Django: Reverse for 'add_review' with arguments '('',)' not found. 1 pattern(s) tried: ['movies/addreview/(?P<id>[0-9]+)/\\Z']
I want to add review function in movie_detail.html, but I don't know how to query comments and map to movie_detail.It returns Reverse for 'add_review' with arguments '('',)' not found error. My url.py: urlpatterns = [ path('', MovieList.as_view(), name='movie_list'), path('<int:pk>', MovieDetail.as_view(), name='movie_detail'), path('search/', MovieSearch.as_view(), name='movie_search'), path('addreview/<int:id>/', views.add_review, name='add_review'), ] My model.py: class Movie(models.Model): title = models.CharField(max_length=200) actors = models.CharField(max_length=500, null=True) poster_url = models.CharField(max_length=200) director = models.CharField(max_length=200, default='') score = models.FloatField() genres = models.CharField(max_length=200) language = models.CharField(max_length=200, default='English') durations = models.IntegerField(default=0) regions = models.CharField(max_length=200, default='') release_date = models.DateField(default=timezone.now) description = models.TextField(max_length=1000, default='') year = models.IntegerField(default=2000) views_count = models.IntegerField(default=0) created = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def genres_as_list(self): genre_list = self.genres.split('/') return genre_list def actors_as_list(self): return self.actors.split('/') class Review(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) comments = models.TextField(max_length=1000) rating = models.FloatField(default=0) data_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username my view.py: class MovieDetail(DetailView): model = Movie template_name = "main/movie_detail.html" def get_object(self): object = super().get_object() object.views_count += 1 object.save() return object def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['links'] = MovieLinks.objects.filter(movie=self.get_object()) context['related_movies'] = Movie.objects.filter(genres__in=self.get_object().genres_as_list()).order_by( 'created')[0:6] # context['reviews'] = Review.objects.filter(id=self.kwargs['pk']) return context class MovieSearch(ListView): model = Movie paginate_by = 20 template_name = "main/movie_list.html" def get_queryset(self): query = self.request.GET.get('query') if query: object_list = self.model.objects.filter(title__icontains=query) else: object_list … -
How to send Crypto payments in Python to user?
I have a Django website that can be categorized under gambling. So the users will be able to deposit and withdraw money/crypto. I have created the deposit part where the user is able to deposit money to the website. Now I am stuck with the withdrawal part. Every tutorial and post I have read are about the user to website payment part. I can't find anything that would help me with the website to user process. For deposit I have used PayPal and Coinbase APIs. Also, I am quite new, so please forgive me for any discrepancies. Could someone please help me with the solution or guide me in the right direction? -
Django pass context into another view from dispatch
I want to redirect users to either a ListView or DetailView based on their role through the SiteDispatchView. If DetailView, I want to pass the request.user.site into the DetailView, but I encounter: AttributeError: Generic detail view SiteDetailView must be called with either an object pk or a slug in the URLconf. My URL for the DetailView is path('<int:pk>/', SiteDetailView.as_view(), name='detail-site'), (Note that site is a OnetoOneField with the Site and User models.) # views.py class SiteDispatchView(LoginRequiredMixin, View): def dispatch(self, request, *args, **kwargs): if request.user.role >= 2: return SiteDetailView.as_view()(request, self.request.user.site) else: return SiteListView.as_view()(request) class SiteDetailView(LoginRequiredMixin, generic.DetailView): template_name = "project_site/site_detail.html" context_object_name = "project_sites" model = Site def get_success_url(self): return reverse("project_site:detail-site") -
How Can I save custom form in django admin?
I created custom form in django user admin, I can't save value, when I want to change it. Sorry,I'm bigginer in django. forms.py class Oplata(forms.ModelForm): oplata = forms.CharField(label='Oplata:',initial='0') admin.py admin.site.unregister(User) class MyUserAdmin(admin.ModelAdmin): form = Oplata add_fieldsets = ( (None, { 'classes':('wide',), "fields": ( 'oplata'), }), ) def save(self,*args ,**kwargs): return super(MyUserAdmin,self).save(*args,**kwargs) # list_display = ('qiwibalance') # Register your models here. admin.site.register(User,MyUserAdmin) -
Django - Display list of products with specifications from a foreign key
I have a Product model, and a ProductCustomField model which holds all of the specifications for each product. It has a foreign key back to Product. I just want to be able to list each product along with the specifications for that product. As the code is right now, for each product, it displays the specifications for all products. model class Product(models.Model): name = models.CharField(max_length=255, unique=True) def __str__(self): return self.name[:50] class ProductCustomField(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) key = models.CharField(max_length=255) value = models.CharField(max_length=255) def __str__(self): return self.key[:50] view def product_lines_view(request): context = { 'product_list': Product.objects.all(), 'spec_list': ProductCustomField.objects.all(), } return render(request, 'product_lines/product_list.html', context) template {% for product in product_list %} <h2>{{ product.name }}</h2> <ul> {% for spec in spec_list %} <li>{{ spec.key }}</li> <li>{{ spec.value }}</li> </ul> {% endfor %} {% endfor %} -
Django admin: filter_horizontal with custom search/filter results
I have a simple model with ManyToManyField. class Meeting(models.Model): place = models.CharField() date = models.DateField() persons = models.ManyToManyField(Person) Person model contains basic information about person. class Person(models.Model): login = models.CharField(unique=True) first_name = models.CharField() last_name = models.CharField() def __str__(self): return self.login In my MeetingAdmin(ModelAdmin) class I have filter_horizontal('persons',) that is used for adding multiple people when creating new Meeting object. This works perfectly fine. In the left menu it's showing the list of all persons(filtering by login). As you may know, filter_horizontal contains search box on the top of the left menu. Examples I would also like to be able to filter persons here by their first name and last name. For example, if there is a person with fields (login='mylogin', first_name='John', last_name='Smith') and I type 'Jo' or 'Smi' in search box, this person is displayed as a search result, etc. 'mylogin' since login field is representation of Person model. -
TemplateSyntaxError at /blogapp/author/1/ Could not parse the remainder: '==user.username' from 'request.user==user.username'
what can we use inside {% %} ? Template error: In template C:\Users\SHAFQUET NAGHMI\blog\blogapp\templates\blogapp\authorview.html, error at line 7 Could not parse the remainder: '==user.username' from 'request.user==user.username' 1 : {% include 'blogapp/home.html' %} 2 : {% load static %} 3 : {% block content %} 4 : <link rel="stylesheet" href="{% static 'blogapp/authorview.css' %}"> 5 : <!-- Latest compiled and minified CSS --> 6 : <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> 7 : {% if request.user==user.username %} 8 : {{user.username}} 9 : {% endif %} 10 : <h1>{{user.username}}</h1> 11 : <!-- <h1>{{request.user}}</h1>--> 12 : {% for post in a %} 13 : <div > 14 : <div class="container"> 15 : <h2 class="display-1">{{post.title}} </h2> 16 : <p class="display-2">{{post.summary}}</p><br> 17 : <p class="display-2">{{post.Newpost}}</p> -
Make permission methods in Django admin more DRY
I have two ModelAdmins in my admin.py. Each have the exact same permission methods (has_view_permission, has_add_permission, has_change_permission, has_delete_permission, has_module_permission). Is there a way I could make this more DRY? admin.py: class FirstAdmin(admin.ModelAdmin): list_display = ( 'id', 'title', 'author' ) def has_view_permission(self, request, obj=None): if request.user.is_admin: return True def has_add_permission(self, request): if request.user.is_admin: return True def has_change_permission(self, request, obj=None): if request.user.is_admin: return True def has_delete_permission(self, request, obj=None): if request.user.is_admin: return True def has_module_permission(self, request): if request.user.is_admin: return True class SecondAdmin(admin.ModelAdmin): list_display = ( 'id', 'category', ) def has_view_permission(self, request, obj=None): if request.user.is_admin: return True def has_add_permission(self, request): if request.user.is_admin: return True def has_change_permission(self, request, obj=None): if request.user.is_admin: return True def has_delete_permission(self, request, obj=None): if request.user.is_admin: return True def has_module_permission(self,request): if request.user.is_admin: return True -
HELLO GUYS, PLEASE I WANT GET RATE, TERMS AND TITLE PATTERNING TO EACH GIFTCARD TO MY TEMPLATE
#GIFTCARD MODEL class Giftcard(models.Model): name = models.CharField(max_length=100, blank=False) card_image = models.ImageField(upload_to='Giftcard', blank=False) date = models.DateTimeField(auto_now_add=True) publish = models.BooleanField(default=False) #CARD CATIGORY MODEL class CardCategory(models.Model): title = models.CharField(max_length=150, blank=False) rate = models.IntegerField(blank=True) term = models.TextField(blank=False) cardName = models.ForeignKey(Giftcard, on_delete=models.CASCADE) #GIFTCARD VIEW. @login_required(login_url='/Authentication/login') def giftcard(request, cardName): giftcards = Giftcard.objects.all().filter(publish=True) card_category = CardCategory.objects.filter(cardName=cardName) print(card_category) context = { 'giftcards': giftcards, 'card_category': card_category, } return render(request, 'dashboard/giftcard.html', context) #HERE IS MY TEMPLATE <div class="container-fluid bg-light gift__card-modal shadow-lg"> <div class="pop p-5"> <div class="row d-flex align-items-center justify-content-between"> <div class="col-lg-5 col-12 p-0 m-0"> <img class="img-fluid" src="{{ giftcard.card_image.url }}"> <p class="text-muted">Select the card category and the amount.</p> </div> <div class="col-lg-6 col-sm-12 card-details"> <form class="card-form"> <div class="form-group py-2"> <label for="card-category">Card category</label> <input list="category" class="form-control" name="category" id="card_category" placeholder="Select card category"> <datalist id="category"> {% for card_category in card_category %} <option value="{{ card_category.title }}">{{ card_category.title }} </option> {% endfor %} </datalist> </div> <div class="form-group py-2"> <label for="Amount">Amount</label> <div class="d-flex align-items-center amount"> <input type="text" class="form-control" id="amount" placeholder="Please enter amount"> <span class="">#100,000</span> </div> </div> <div class="form-group py-3"> <label for="rate">Current rate - 250</label> </div> <div class="border-none pt-2 pl-3 d-flex justify-content-end"> <button type="button" class="btn process-card-btn">Proceed</button> </div> </form> </div> </div> </div> </div> -
Django (Python) User Permission
I have a moderate knowledge about the django and python. I need a guide to know how to create user permission with GUI control as shown in the attached image. May Thanks Dear, I have a moderate knowledge about the django and python. I need a guide to know how to create user permission with GUI control as shown in the attached image. May Thanks -
Django create singleton class by using the follwing code of field validation
i created a prectice project of school management system. in witch i have three entity student and teacher and principal. i created individual form for taking the informtion all all theis entity. now i am appling field validation on it. so i want to create a singleton class of validation by this i can use one object of this class for validation of all three entity. how i can create this class @login_required(login_url='/') def add_student(request): course = Course.objects.all() session_year = Session_Year.objects.all() if request.method == "POST": profile_pic = request.FILES.get('profile_pic') first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') email = request.POST.get('email') username = request.POST.get('username') password = request.POST.get('password') address = request.POST.get('address') gender = request.POST.get('gender') course_id = request.POST.get('course_id') session_year_id = request.POST.get('session_year_id') #validation for empty first_name num = 0 if not first_name: messages.warning(request,'please enter first name') #return redirect('add_student') num = num+1 # validation for correct enter first_name if not first_name.isalpha() and first_name!="": messages.warning(request,'please correct enter first name') #return redirect('add_student') num = num+1 #validation for empty last_name if not last_name: messages.warning(request,'please enter last name') #return redirect('add_student') num = num+1 # validation for correct enter last_name if not last_name.isalpha(): messages.warning(request,'please correct enter last name') #return redirect('add_student') num = num+1 # validation for unique email if Customuser.objects.filter(email=email).exists(): messages.warning(request,'Email Is Already … -
html multiple form submit with javascript on keypress
I have a django app, which consists of a surface that generically adds text areas and their respective submit buttons (jinja 2 templates). I am trying to submit the text area content with keypress now instead of the button. The issue is as following: submitting the textarea (when filled with user input) by clicking on the button posts form data, namely the content of the text area and a value that is assigned to the submit button, namely an id for the respective text. In Django's views, I am accessing the data through request.POST. Now, I managed to submit the text area content on button press, but logically the id of the key is not accessible since the button is not pressed (and its value not submitted). How would I send the id now? Can I modify the request object with javascript, adding the key-value pair for the id? Or can I submit the value of a hidden submit button with JS when submitting the text area on key press? What is best for security reasons and cross-browser compatibility? Here is my (reduced) code: template for text area <form action="{% url 'myapp:txtarea' %}" method="post"> <textarea name="inputtext" onkeypress="submitTextAreaOnKeyPress('{{idn}}')" class="xyz" cols="30" rows="1" … -
Scrap each product by filtering comments
I am trying to scrape each product page from aliexpress website. I have written this code to get number of comments, number of photos published by the custumer and also the custumer country and put it to a dataframe. But I want to get only the comments published by certain custumer in other words to apply a filter on comments by custumer country , for example get the comments published by the custum whom country is 'US', but really I don't know how to establish that filter : from selenium import webdriver from selenium.webdriver.common.by import By from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import pandas as pd url = 'https://www.aliexpress.com/item/1005003801507855.html?spm=a2g0o.productlist.0.0.1e951bc72xISfE&algo_pvid=6d3ed61e-f378-43d0-a429-5f6cddf3d6ad&algo_exp_id=6d3ed61e-f378-43d0-a429-5f6cddf3d6ad-8&pdp_ext_f=%7B%22sku_id%22%3A%2212000027213624098%22%7D&pdp_pi=-1%3B40.81%3B-1%3B-1%40salePrice%3BMAD%3Bsearch-mainSearch' driver = webdriver.Chrome(ChromeDriverManager().install()) driver.get(url) wait = WebDriverWait(driver, 10) driver.execute_script("arguments[0].scrollIntoView();", wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '.tab-content')))) driver.get(wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '#product-evaluation'))).get_attribute('src')) data=[] number_feedbacks = driver.find_element(By.XPATH, '//*[@id="transction-feedback"]/div[1]') number_images = driver.find_element(By.XPATH, '//*[@id="transction-feedback"]//label[1]/em') print(f'number_feedbacks = {number_feedbacks}\nnumber_images = {number_images}') while True: for e in driver.find_elements(By.CSS_SELECTOR, 'div.feedback-item'): try: country = e.find_element(By.CSS_SELECTOR, '.user-country > b').text except: country = None data.append({ 'country':country, }) try: wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '#complex-pager a.ui-pagination-next'))).click() except: break pd.DataFrame(data).to_csv('filename.csv',index=False) Any help would be great. Thank you ! -
im getting "variable has been referenced before intialization" error at the last line in django framework
def result(request): check = None try: check = user_answers.objects.get(username=request.session["username"]) except: check = None if check: results,a1,a2,a3,a4,a5 = getPredictions(check) username = request.session["username"] ans = clusterNum.objects.create(username_id=request.session["username"],clusNo = results[0],extroversion=a1,neurotic=a2,agreeable=a3,conscientious=a4,openness=a5) ans.save() # results = getPredictions() return render(request,'result.html',{'name':username,'a1':a1,'a2':a2,'a3':a3,'a4':a4,'a5':a5}) i tried converting them to global but the result is not as expected,it show no values in the webpage -
Select multiple items in Django Admin
Right now filter can be done for all or none i want to make to multiple item selection. In which way I can do that. filter=(2,5,6) -
TypeError at / save() missing 1 required positional argument: 'self'
I cannot update the balance amount, when I try to save the value, it raises that error. models.py, class balance_data(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) total_amount = models.FloatField(max_length=15) def __str__(self): return str(self.user) Views.py, def cash_in(request, amount): new_amount = request.user.balance_data.total_amount + amount balance_data.total_amount = new_amount balance_data.save(update_fields=['total_amount']) return HttpResponse(request.user.balance_data.total_amount) How can I solve this? I am expecting to update the amount. -
recognized command (autofile) does not work when I create a file
Hello friends I work through the VScode platform And also works with django, And I have a problem when I create a templates folder and within it I want to create an HTML file And when I type the html command it does not complete it for me automatically as if it does not recognize the file. But if I create a file in another folder in the project he recognizes it very nicely. Here are some pictures to illustrate. Here you can see the path when I create an html file I have the autocomplete. And here when I create a file inside a template folder it does not know to recognize. -
How to send Crypto payments in Django/Python?
I have a website that basically would categorize under gambling. So the users will be able to deposit and withdraw money/crypto. I have created the deposit part where the user is able to deposit money to the website. Now I am stuck with withdraw part. Every tutorial and post I read are about the user to website payment part. I can't find anything that would help me with the website to user process. For deposit I used PayPal and Coinbase APIs. Also I am quite new to this so sorry if my question is ridiculous or badly worded. Could someone please help me with the solution or at least lead me to the right direction? -
Using Django, send a Python Dictionary to a HTML Page and convert it to Javascript arrays in Javascript Script
I have been trying to send a Python Dictionary to a HTML Page and use that dictionary in Javascript to add a Graph on my website, using Django The form takes a Image Upload, and the code is as follows, <div class=" mx-5 font-weight-bold"> Uplaod Image </div> <input class=" " type="file" name="filePath"> <input type="submit" class="btn btn-success" value="Submit"> This image is then sent to views.py where it is processed and a resultant image, as well as a dictionary is generated from that image. And then again, a HTML page is rendered where the dictionary as well as the resultant image is sent in context variable. The code is as follows, def predictImage(request): fileObj = request.FILES['filePath'] fs = FileSystemStorage() filePathName = fs.save(fileObj.name, fileObj) filePathName = fs.url(filePathName) testimage = '.'+filePathName img_result, resultant_array, total_objects = detect_image(testimage) cv2.imwrite("media/results/" + fileObj.name, img=img_result) context = {'filePathName':"media/results/"+fileObj.name, 'predictedLabel': dict(resultant_array), 'total_objects': total_objects} #context = {} return render(request, 'index.html', context) Now, I want to convert the Dictionary items and keys into two different Javascript arrays, which are then to be used to plot a Graph on the HTML page. The template code of the Javascript is as follows, <script> // const value = JSON.parse(document.getElementById('data_values').textContent); // alert(value); var xArray = []; … -
Why running curl command using parallel needs to timeout?
I have set up daphne server with my django application and I wanted to use curl command to send parallel requests to the API that I have created. This is the command that I am using in terminal. seq 10 | parallel -j 5 --joblog pandu.log curl --connect-timeout 2 -v -F "FILE=@PATH_TO_FILE" http://127.0.0.1:8000/<wxy>/<xyz> So, I started the daphne server in one terminal and ran the curl command in another terminal. This is the view that I have created for handling API requests. @csrf_exempt def inputView(request): file = request.FILES['FILE'] call_print_primers(file) return HttpResponse("well I have recieved the file.") This is the output I am getting when I ran the curl command. Trying 127.0.0.1:8000... % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* Connected to 127.0.0.1 (127.0.0.1) port 8000 (#0) > POST /<wxy>/<xyz> HTTP/1.1 > Host: 127.0.0.1:8000 > User-Agent: curl/7.82.0 > Accept: */* > Content-Length: 2828 > Content-Type: multipart/form-data; boundary=------------------------4e8f33ef7353b32d > } [2828 bytes data] * We are completely uploaded and fine * Mark bundle as not supporting multiuse < HTTP/1.1 200 OK < Content-Type: text/html; charset=utf-8 < X-Frame-Options: DENY < Content-Length: … -
Category and subcategory for django-filter
I want to build a filter for category and subcategory. The filter works enough good, but I don't know how to build left space for children (subcategory). Also I don't know how to build by link. For example, I click a category "Nature" and this category contains different subcategory. In short, I have two question: How to build space for children (subcategory)? how to present categories and subcategories by link? I will be happy of any answer. My code which I tried to use Django-MPTT. But I have error when I use "tree info" and "recursetree" - "'BoundWidget' object has no attribute '_mptt_meta'" template.html <form method="get" class="d-flex flex-column"> {% for su,structure in filter.form.subject|tree_info %} {% if structure.new_level %}<ul> <li>{% else %}</li> <li>{% endif %} {{ su }} {% for level in structure.closed_levels %}</li> </ul>{% endfor %} {% endfor %} OR {% recursetree filter.form.subject %} <li> {{ node }} {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} <button class="btn-primary mt-2" type="submit">Search</button> </form> models.py class Book(models.Model): title = models.CharField(max_length=255, db_index=True) author = models.ForeignKey( "users.CustomUser", on_delete=models.SET_NULL, null=True, db_index=True ) subject = TreeManyToManyField("Subject") class Subject(MPTTModel): name = models.CharField( max_length=100, unique=True, verbose_name=_("category name"), help_text=_("format: required, … -
Manage multiple accounts in different companies with django
I'm learning and working with django less than a year ago. Now I have to develop a site managing multiple users separated by many different companies. I've recently found django-organizations package which seems suitable for this application, I have read the complete documentation in readthedocs, but I can't find simple working example apps to start trying, and the activity on communities like stackoverflow on this subject seems to have decayed two years ago. Please can anybody tell me if django-organizations is an updated package, compatible with last python and django versions, and provide a source of simple “Hello World”-like examples. Or, by the other hand, please suggest me the best way/library to manage signup, login, permissions, etc,in a multiple users – multiple company Django web application. Thanks in advance.