Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django with angular on elastic beanstalk
I have been using Django and I am used to serving HTML pages using its templates. Using the same to host it on elastic beanstalk has been straight forward. Now if I have to use Django only for its admin and rest APIs while using angular as a frontend framework, what are changes to be made within Django to accommodate angular and how to deploy it on elastic beanstalk with ci/cd preferably through bitbucket. -
Add through field of user to serializer
I'm having the following models class User(AbstractUser): email = models.EmailField(_('email address'), unique=True) display_name = models.Charfield() class Team(models.Model): display_name = models.Charfield() users = models.ManyToManyField(User, through='TeamUser') class TeamUser(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) role = models.IntegerField(_('role'), choices=[(g.id, g.name) for g in TeamRoles.all()], default=0) color = models.CharField(_('color'), max_length=10) class Meta: unique_together = ('team_id', 'user_id',) I want to add role and color to Serializers (using request.user) How can I make TeamSerializer for that? -
how to make shopping cart using django
I'm making a shopping cart with two class models, one user can order multiple products I used the many-to-many relationships. but I'm facing some issues like if two users has order same product then the last user's selected qty will show in both user's order. and many times it shows all orders in the user's cart by default. please tell the correct way to write these models. So each users cart can't affect others class OrderItem(models.Model): id = models.AutoField(primary_key=True) product = models.OneToOneField(Product, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) date_added = models.DateTimeField(auto_now=True) qty = models.IntegerField(default=1) def __str__(self): return self.product.Productname class Cart(models.Model): owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) is_ordered = models.BooleanField(default=False) items = models.ManyToManyField(OrderItem, default=None, blank=True) -
Django test runner not running with non-standard project structure
I've got a Django project with a slightly non-standard structure (shown below) and the Django test runner isn't working. root_dir ├ src | ├ myapp_dir (apps.py, etc.) | ├ project_files_dir (settings.py, wsgi.py, etc.) | ├ utils_dir, etc. | └ manage.py ├ tests | ├ test_settings.py | └ myapp_tests_dir (tests1.py, tests2.py, etc.) ├ setup.py └ runtests.py apps.py contains: from django.apps import AppConfig class MyAppConfig(AppConfig): name = 'myapp' settings.py includes INSTALLED_APPS = [..., myapp] test_settings.py includes INSTALLED_APPS = [..., myapp, tests] runtests.py contains: import os import sys import django from django.conf import settings from django.test.utils import get_runner if __name__ == "__main__": os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings' django.setup() TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests(["tests"]) sys.exit(bool(failures)) When I to run the tests with python runtests.py I get ModuleNotFoundError: No module named 'myapp' If try to change test_settings.py to include INSTALLED_APPS = [..., src.myapp, tests] I then get django.core.exceptions.ImproperlyConfigured: Cannot import 'myapp'. Check that 'src.myapp.apps.MyAppConfig.name' is correct. It's probably also worth mentioning that runserver runs fine from the working directory root_dir when calling it like this: > python src/manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). April 22, 2020 - 16:06:19 Django version 3.0.5, … -
Why aren't my image files uploading properly, I keep receiving 404 in console?
I am trying to have React upload an image via React DropZone. However, when I go to my blog manager page, the console promptly logs 404 Failed to load resource: the server responded with a status of 404 (Not Found). I am using Django Rest Framework for the backend, and in the terminal it states "GET /media/Upload%20image HTTP/1.1". The frontend, react, is able to get the image file on the page, but it will not upload. Here is the settings.py in backend DRF: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'p%s-9w1l268@!b$p#92dj26q)pv7!&ln^3m(1j5#!k8pkc9@(u' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # 'allauth', # 'allauth.account', # 'allauth.socialaccount', 'corsheaders', # 'rest_auth', # 'rest_auth.registration', 'rest_framework', # 'rest_framework.authtoken', 'menus', 'phlogfeeder', 'login' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'chefsBackEnd.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ … -
Why won't my plotly figures render correctly in Django templates?
I have a basic python module that I'm using to output the div necessary to embed the plotly plot directly into my Django template. I just want to display a basic plot in my website for proof of concept to someone I'm developing with. the plot renders but I can only see visual feedback if my cursor goes over a datapoint and shows the coordinates on screen. Otherwise, the lines, points, axes, and all other rendered components are invisible. The code I'm running is below. Plotter.py import plotly.graph_objects as go from plotly.offline import plot import pandas as pd def get_plot_div(): x = [0,1,2,3,4,5] y = [6,5,4,3,4,5] zipped_list = list(zip(x,y)) df = pd.DataFrame(zipped_list,columns = ['x1','x2']) fig = go.Figure() fig.add_trace(go.Scatter( x = df['x1'], y = df['x2'], mode = 'lines')) fig.update_layout(height=600, width=800, title_text="Simple Plot") plot_div = plot(fig, output_type = 'div',auto_open = False) return plot_div Views.py from . import Plotter.py as plotter from django.shortcuts import render def Profile(request): plt_div_returned = plotter.get_plot_div() context = {'fig':plt_div_returned} return render(request,'django_proj/profile.html',context) Then in the profile.html template I have <h1> Test Plot </h1> {% if context.fig %} {{%context.fig | safe%}} {% endif %} This renders the plot in my template, but again I can only see anything if I move … -
i want to send otp after clicking send otp and then verify it by clicking verify in django template how can i do this?
I want to send OTP from Django template, how I can get receiver's phone I below code and send OTP and verify import requests import JSON import random import math URL = 'https://www.sms4india.com/api/v1/sendCampaign' # get request def sendGetRequest(reqUrl, apiKey, secretKey, useType, phoneNo, senderId, textMessage): req_params = { 'apikey':apiKey, 'secret':secretKey, 'usetype':useType, 'phone': phoneNo, 'message':textMessage, 'senderid':senderId } return requests.get(reqUrl, req_params) data ="0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ" leng = len(data) otp ="" for i in range(6): otp += data[math.floor(random.random()*leng)] # get response response = sendGetRequest(URL, 'authkey', 'api key', 'stage', 'phoneNO', 'user', 'Your digit OTP is '+str(otp) ) """ Note:- you must provide apikey, secretkey, usetype, mobile, senderid and message values and then requst to api """ # print response if you want print(response.text) this code generate OTP for me but how to get user-entered OTP and compare in Django -
django-autocomplete-light. How to implement a global navigation autocomplete using django-autocomplete-light
I've been making an Yelp clone and i encounted frustration creating autocomplete. I have one searching form with 2 fields. Search field should traversy through 2 models (Business, Service). Searching should looks like on Yelp. But for Business model it should have one look(it must have and be wrapped into tag). For Service model it looks like a plain text. Also search field must be chained to city field(Look up of businesses should happens only in the city from city field, like 'china restaurants' in 'London' ). I have no problems with city autocomplete(for cities i use cities-light and geodjango). How to implement global navigation autocomplete(like on Facebook or Yelp). *forms.py* class SearchForm(forms.Form): search = forms.ChoiceField(widget=autocomplete.ListSelect2(url='searchquery-autocomplete')) city = forms.ChoiceField(widget=autocomplete.ListSelect2(url='city-autocomplete')) For example i use 2 models: Business with name, service fields and related model Service with name field. -
Django form and CBV CreateView not able to assign request.user to user field
I have a form and a CBV CreateView. I need to assign the request.user to the user field (Foreign Key to CustomUser model), which in the form is a hidden field (user). However, I have tried in the form init method by "self.fields['user'] = self.request.user.id" and I get the error: 'NoneType' object has no attribute 'user'. What is the most clean way of achieving this? I have tried many different ways of doing it with no luck. ): This is my form: class PhoneForm(forms.ModelForm): class Meta: model = Phone fields = 'user', 'phone_name', 'country', 'phone_number', 'phone_type', 'primary' widgets = {'user': forms.HiddenInput()} def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(PhoneForm, self).__init__(*args, **kwargs) self.fields['user'].widget.attrs['readonly'] = True self.fields['user'] = self.request.user.id self.fields['primary'].help_text = _('<strong>Check:</strong> If this is your main contact phone number.') def clean(self): cleaned_data = super(PhoneForm, self).clean() user = cleaned_data.get('user') phone_name = cleaned_data.get('phone_name') country = cleaned_data.get('country') phone_number = cleaned_data.get('phone_number') phone_type = cleaned_data.get('phone_type') primary = cleaned_data.get('primary') print('user: ',user) print('phone_name: ',phone_name) print('country: ',country) print('phone_number: ',phone_number) print('phoe_type: ',phone_type) print('primary: ',primary) if "action_add" in self.request.POST: try: phonenum = Phone.objects.filter(user=user, country=country, phone_number=phone_number).first() if phonenum: raise forms.ValidationError(_('This Phone is registered already.')) except Phone.DoesNotExist: pass try: phone = Phone.objects.filter(user=user, primary=True).first() if phone and primary: raise forms.ValidationError(_('There is another "Primary" … -
Mail don't send mail from smtp server(django)
As far as I understand the problem is that the email is perceived as spam. I wrote to mail on the recommendation, but I don't know when they will respond, so I decided to write, maybe someone has already faced a similar problem Error: 2020-04-21T17:11:44.703528+03:00 srv20-s-st postfix/cleanup[31293]: AB6FC3782386: message-id=<20200421141144.AB6FC3782386@smtp-out7.jino.ru> 2020-04-21T17:11:44.749351+03:00 srv20-s-st postfix/bounce[16478]: 60F7137822E8: sender non-delivery notification: AB6FC3782386 2020-04-21T17:11:44.749756+03:00 srv20-s-st postfix/qmgr[29563]: AB6FC3782386: from=<>, size=2939, nrcpt=1 (queue active) 2020-04-21T17:11:45.286651+03:00 srv20-s-st postfix/smtp[3053]: AB6FC3782386: to=<marsel.abdullin.00@mail.ru>, relay=mxs.mail.ru[94.100.180.31]:25, delay=0.53, delays=0.05/0/0.04/0.45, dsn=5.0.0, status=bounced (host mxs.mail.ru[94.100.180.31] said: 550 spam message rejected. Please visit http://help.mail.ru/notspam-support/id?c=P6S_FpNxB6v7cN6t9-D6dIPfAZm8McBDVirhhk5aBttn62fvJQEllSMAAACyigAAEsgALQ~~ or report details to abuse@corp.mail.ru. Error code: 16BFA43FAB077193ADDE70FB74FAE0F79901DF8343C031BC86E12A56DB065A4EEF67EB6795250125. ID: 0000002300008AB22D00C812. (in reply to end of DATA command)) 2020-04-21T17:11:45.291554+03:00 srv20-s-st postfix/qmgr[29563]: AB6FC3782386: removed -
How to co-exist STATICFILES_FINDERS and STATIC_URL
I would use django on apache with this setting. STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") in apache setting Alias /static/ /var/www/html/jrtweet/current/static/ However I installed django-compressor, so adding,this setting. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # other finders.. 'compressor.finders.CompressorFinder', ) However after adding this, browser can't access /static/ directory. I need to do some setting for co-exist STATICFILES_FINDERS and STATIC_URL setting?? -
Can anyone tell about how can I fix this error in django , AttributeError: module 'BRMapp.models' has no attribute 'objects'
BRMapp is project name. please see the code in below image : https://i.stack.imgur.com/v0gG0.jpg In cmd , showing error: books = models.objects.all() AttributeError: module 'BRMapp.models' has no attribute 'objects' Myrest of the code is absolutely correct.Please tell how can I correct this AttributeError.. -
Can I programmatically change in django crispy forms the StrictButton part of the helper?
I see this documentation: https://django-crispy-forms.readthedocs.io/en/latest/crispy_tag_forms.html?highlight=change%20helper%20in%20view#manipulating-a-helper-in-a-view and https://django-crispy-forms.readthedocs.io/en/latest/dynamic_layouts.html I'd like to change the button description in the view: form.py class GenericButtonForm(forms.Form): def __init__(self, *args, **kwargs): super(GenericButtonForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' #self.helper.form_action = 'catalog:ave-properties' self.helper.form_class = 'form-inline' self.helper.field_template = 'bootstrap4/layout/inline_field.html' self.helper.layout = Layout( StrictButton('I'd like to change this', type='submit', id='button-down-spinner', css_class='btn-info'), ) views.py @login_required def CheckAveView(request): template_name='catalog/check_AVE.html' if request.method == 'POST': GenericButtonForm_inst = GenericButtonForm() GenericButtonForm_inst.helper.form_action = reverse('catalog:ave-properties') # Can I change the butto descriprion? 'I'd like to change this' ave_props = check_AVE_query_json(sess) else: ave_props = '' GenericButtonForm_inst = GenericButtonForm() context = { 'GenericButtonForm_inst': GenericButtonForm_inst, 'ave_props': ave_props, } return render(request, template_name, context=context) Can I manipulate in the view the button description?: self.helper.layout = Layout( StrictButton('I'd like to change this', type='submit', id='button-down-spinner', css_class='btn-info'), Thanks, Luca -
Trouble in accessing the field value of Foreign Key in Django
class State(models.Model): name = models.CharField(max_length=30) slug = models.SlugField(allow_unicode=True, unique=True, editable=False) def __str__(self): return str(self.name) def save(self, *args, **kwargs): self.slug = slugify(self.name) super().save(*args, **kwargs) class Location(models.Model): place_name = models.CharField(max_length=256, primary_key=True) latitude = models.DecimalField(max_digits=19, decimal_places=16) longitude = models.DecimalField(max_digits=19, decimal_places=16) state = models.ForeignKey(State, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return str(self.place_name) class Case(models.Model): user = models.ForeignKey(User, related_name = 'Case', on_delete=models.CASCADE, null=True, blank=True) address = models.ForeignKey(Location, null = True, blank=True, on_delete=models.CASCADE, related_name='Case_Place') case_type = models.BooleanField(default=False) # True is Positive or False is Negative. def __str__(self): if self.case_type == True: return str(self.address) + "- Positive" else: return str(self.address) + "- Suspect" def get_absolute_url(self): return reverse('case:all') class Meta: ordering = ['-case_type'] I want to make get state, total(case_type), case_type group by state from Case. And when user clicks any state the following address, total(case_type), case_type group by address from Case is displayed. -
django apache integration missing module
I'm trying to setup my first Django project and I have some issues with the Apache integration. Here my file tree venv-django aci_project/ |_manage.py |_aci_project/ | |_ init.py | |settings.py | | urls.py | |_ asgi.py | |_ wsgi.py | |_aci_api/ |_ init.py |_aci_script |_admin.py |_apps.py |migrations/ | | init.py |_static --> css |_templates --> template html |_tests.py |_urls.py |_views.py Basically, the flow is the following: Browser --> aci_project --> urls.py --> aci_api --> views.py --> call scripts in aci_script If I run the command "python manage.py runserver" it's working fine. Now I'm trying to integrate my Django project with Apache but it's not working. This is my vhost file in Apache: <VirtualHost *:8000> ErrorLog /var/log/httpd/error_log CustomLog /var/log/httpd/access_log combine <Directory /var/opt/aci_project/aci_project/> <Files wsgi.py> Require all granted </Files> </Directory> WSGIApplicationGroup aciweb01t.stluc.ucl.ac.be WSGIDaemonProcess aciweb01t.stluc.ucl.ac.be group=www-data python-path=/var/opt/aci_project WSGIProcessGroup aciweb01t.stluc.ucl.ac.be WSGIApplicationGroup %{GLOBAL} WSGIScriptAlias / /var/opt/aci_project/aci_project/wsgi.py </VirtualHost> here my wsgi.py file in aci_project --> manage.py --> _aci_project import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'aci_project.settings') application = get_wsgi_application() And this is the error I have in the apache logs: [Wed Apr 22 16:49:12.468252 2020] [wsgi:error] [pid 7818:tid 140205314995968] [remote 10.195.113.74:28031] mod_wsgi (pid=7818): Failed to exec Python script file '/var/opt/aci_project/aci_project/wsgi.py'. [Wed Apr 22 16:49:12.468453 2020] [wsgi:error] … -
Vue.js and django rest framework for implements a cascading dropdown list
I would need help building a request to my backend API. I currently have a form with a drop down list. The data in this list comes from this.$Http.get('/ quality/api/affaires/') Below this drop-down list, I have another list. This list, I would like it to be empty until the 1st is not selected, then it is implemented with data according to the selection above. Backend side (Django) I have 2 models which are "Affaires" and "AffairesOfs". I used Serialize and I can therefore request each of these models via api/affaires and api/affairesofs In the "AffairesOfs" model I have a foreignekey (idaffaire) on the id of the "Affaires" model. Finally, I would like my second list to be made up of all the “affairesofs” linked to the “Affaires” selected. For now, I have my 2 drop-down lists but I can't find a way to link the second to the first. I tried different methods found on the internet (with the use of v-model, ...) but could not achieve a result. I can't even get the value selected from the first list to display it in the console, or in a . i think I need a change event on the first … -
Unable to used Django-Filter in python 3.6 returns ImportError: cannot import name 'six'
I am new to Django framework and I am encountering an issue when I'm using Django-filter and enter it in INSTALLED_APPS it returns the following error: File "Programs\Python\Python36\lib\site-packages\django_filters\__init__.py", line 7, in <module> from .filterset import FilterSet File "Programs\Python\Python36\lib\site-packages\django_filters\filterset.py", line 10, in <module> from django.utils import six ImportError: cannot import name 'six' I am currently trying to solve the issue but still to no avail . Any help will be greatly appreciated. Thank you -
Form for updating model info is blank
I am trying to provide a form to update user info such as employment, location, birthday, interests. The form I tried to make will not show any of this info however, it just shows a submit button. user_info = models.UserInfo.objects.get(user=request.user) if request.method == 'POST': form = UserChangeForm(data=request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('login:login_view') else: form = UserChangeForm(instance=request.user) context = { 'user_info' : user_info, 'form ' : form } return render(request, 'account.djhtml',context) I'm pretty sure I need to use user_info but Im not to sure how to do that. If anyone can point me in the right direction i'd greatly appreciate it. Thanks <form method="post"action="{% url 'social:account_view' %}"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> The djhtml I tried -
How to import pickled python object into Django view.py file
This file runs perfectly well on its own: import pickle with open('model.obj', 'rb') as f: model = pickle.load(f) print(len(model)) But what I really want to do is to use model, which is a very large stored python dictionary, in my Django views.py file, like so: from django.shortcuts import render from modeler.load_model import model def page(request): return render(request, 'page.html', {'model':model}) However, when I try this, I get the error below: File "C:\Users\mmm\PycharmProjects\MyProject\modeler\load_model.py", line 3, in <module> with open('model.obj', 'rb') as f: FileNotFoundError: [Errno 2] No such file or directory: 'model.obj' I don't understand why, because if I run the first file directly it works fine - the only extra step here is importing it into views.py (I tried including the entire load_model.py code within views.py at first, but got this error, so then tried it in this separate file and it worked on its own, so obviously the issue is that I don't know how to correctly load/import my python model objects or files within Django. -
How to dynamically route to a URL with ID of an element fetched using JQuery on Django
I am populating data(Customer order in my case) from database into a table using Django template tags. I have assigned the unique ID( order.id) to the id of "a" tag. On click of this "a" tag, I have written a function which fetches the id of the clicked button and then opens a modal dialog. Now I need the modal body to show the order.name dynamically and then give the user two options - 1. 'No', which closes the modal 2. 'Yes', which should route to views along with the id fetched. I am stuck here. html <div class = 'col-md-7'> <h4>ORDERS</h4> <hr> <div class = 'card card-body'> <a class = 'btn btn-primary text-white' href = "{% url 'createOrder' %}">Create Order</a> <table class = 'table table-sm'> <tr> <th>Product</th> <th>Date Ordered</th> <th>Status</th> <th>Update</th> <th>Remove</th> </tr> {% for order in orders %} <tr> <td>{{order.Product.name}}</td> <td>{{order.created_on}}</td> <td>{{order.status}}</td> <td><a href = "{% url 'updateOrder' order.id %}" style = "color: #005ce6;"><i class="fas fa-pen" style = "padding-left: 5mm;"></i></a></td> <td><a href = "#" class = 'delete' id = '{{order.id}}' style = "color: #b30000;"><i class="fas fa-times" style = "padding-left: 6mm;"></i></a></td> </tr> {% endfor %} </table> </div> </div> <script> $(".delete").click(function() { var id = this.id; $('#modelId').modal('show'); }); </script> <!-- … -
Automatically changing value in Django
Good evening! I am creating an app using Django to manage car rental service. I have a model Car, User and Order, which has a ForeignKey inheriting from Car. I created a form for allowing user creating an order. I want to automatically change the car status as 'Rented' (in Car model it is CharField with 3 choices). Can somebody help me to solve this problem? class Car(models.Model): STATUS = ( ('Dostępny', 'Dostępny'), ('Wypożyczony', 'Wypożyczony'), ('Inne', 'Inne'), ) marka = models.CharField(max_length=100) model = models.CharField(max_length=100) production_year = models.CharField(max_length=100) color = models.CharField(max_length=100) id_plate = models.CharField(max_length=100) status = models.CharField(max_length=100, choices=STATUS) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.marka + ' ' + self.model + ' (' + self.color + ')' class Order(models.Model): client = models.ForeignKey(Klient, on_delete=models.CASCADE) car = models.ForeignKey(Car, on_delete=models.CASCADE) date_ordered = models.DateField(default=datetime.now) date_return = models.DateField() date_added = models.DateTimeField(auto_now_add=True) That is my form: class OrderForm(ModelForm): class Meta: model = Order fields = ['client', 'car', 'date_ordered', 'date_return'] That's views.py: def createOrder(request): form = OrderForm() if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): form.save() return redirect('home') context = {'form': form} return render(request, 'namiejscu/order_form.html', context) -
Pagination in filtered detailview in Django?
def get_context_data(self, **kwargs): context = super(ProductCategoryView, self).get_context_data(**kwargs) #dropdown menu context['subs'] = ProductSubCategory.objects.filter(category=self.object) #sidebar menu sub_id = self.request.GET.get('sub_id') if sub_id: context['products'] = Product.objects.filter(category=sub_id) else: context['products'] = Product.objects.filter(category__in=context['subs']) return context I have this detailview. First two lines linked eachother and product items filtered by them too. I want to paginate the products only but not the dropdown and sidebar. Limit items with simple paginate_by * is possible? Or create listview with the same function? -
Django: how to edit 4 records at the same time in a table presentation?
I have a new Django project with specific constraints for displaying data to be edited? Until now, I had edit and update forms that 'works' for a specific record. I have a index.html form that display data of my model. Records are group by four records. What is expected, is: to display the same table in a edit/update form but with fields that can be modified have four records to edit prefilled with data of the four last line of the table Bras (based on date) When I valid modification, 4 new records are stored I do not really know how to do... models.py class Bras(SafeDeleteModel): """ A class to create a country site instance. """ _safedelete_policy = SOFT_DELETE_CASCADE bra_ide = models.AutoField(primary_key = True) pay_ide = models.ForeignKey(Pays, on_delete = models.CASCADE) # related country ran_st1 = models.IntegerField("Stratification variable 1", blank=True) ran_st2 = models.IntegerField("Stratification variable 2", blank=True) bra_00A_act = models.IntegerField("Arm A activated", default=0, null=True, blank=True) bra_00A_lib = models.CharField("Arm A label", max_length=50, null=True, blank=True) bra_00B_act = models.IntegerField("Arm B activated", default=0, null=True, blank=True) bra_00B_lib = models.CharField("Arm B label", max_length=50, null=True, blank=True) ... bra_log = models.CharField("User login", max_length = 50) bra_dat = models.DateTimeField("Date of settings") log = HistoricalRecords() index.html {% extends 'layouts/base.html' %} {% load … -
Django register url is falling in infinitive loop
So relevant part of urls.py: path('register/', views.register, name="register"), path('login/', views.login_user, name="login_user"), path('logout/', views.logout_user, name="logout_user"), Settings.py: LOGIN_URL="/auth/register/" HTML call: <p><a href="{% url 'auth:register' %}" class="btn btn-success">REGISTER»</a></p> But that url is returninh this: http://127.0.0.1:8000/auth/register/?next=/auth/register/%3Fnext%3D/auth/register/%253Fnext%253D/auth/register/%25253Fnext%25253D/auth/register/%2525253Fnext%2525253D/auth/register/%252525253Fnext%252525253D/auth/register/%25252525253Fnext%25252525253D/auth/register/%2525252525253Fnext%2525252525253D/auth/register/%252525252525253Fnext%252525252525253D/auth/register/%25252525252525253Fnext%25252525252525253D/auth/register/%2525252525252525253Fnext%2525252525252525253D/auth/register/%252525252525252525253Fnext%252525252525252525253D/auth/register/%25252525252525252525253Fnext%25252525252525252525253D/auth/register/%2525252525252525252525253Fnext%2525252525252525252525253D/auth/register/%252525252525252525252525253Fnext%252525252525252525252525253D/auth/register/%25252525252525252525252525253Fnext%25252525252525252525252525253D/auth/register/%2525252525252525252525252525253Fnext%2525252525252525252525252525253D/auth/register/%252525252525252525252525252525253Fnext%252525252525252525252525252525253D/auth/register/%25252525252525252525252525252525253Fnext%25252525252525252525252525252525253D/auth/register/%2525252525252525252525252525252525253Fnext%2525252525252525252525252525252525253D/auth/register/ What am I doing wrong? -
TypeError: 'BasePermissionMetaclass' object is not iterable
I got this problem when i was trying to do an authentication function.Anybody got solution? REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], }