Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python/Django button to redirect user depending on the actual site
I've searched for the best idea to clearly implement a button that redirects a user to the post creation page depending on the current URL but I still don't have a good solution. I have 1 same template for 3 pages. Each page has 10 categories (subpages). Maybe example: urls.py: app_name = 'forum' 1 category path('category1/, View.as_view(), name = category1 2 category path('category2/, View.as_view(), name = category2 1 category post creation path('category1/create-post/', PostCreateView.as_view(my_id=11), name = category1-new-post 2 category post creation path('category2/create-post/', PostCreateView.as_view(my_id=12), name = category2-new-post If the user is on the first subpage/category and clicks the button then redirect him to {% url 'forum:category1-new-post' %} If the user is on the second subpage/category and clicks the button then redirect him to {% url 'forum:category2-new-post' %} and etc 28x times (3 pages x 10 categories) I've tried to write something like this: {% if request.resolver_match.url_name == 'category1' %} button with href '{% url 'forum:category1-new-post' %}' {% elif request.resolver_match.url_name == 'category2' %} button with href '{% url 'forum:category2-new-post' %}' and etc 28x times. The code above doesn't seem good. Writing 30 ifs is not the best idea and i don't know how to handle it. For each subpage/category post creation i have … -
NoReverseMatch at /main/insert_num/ Django
I'm trying to make to make a django web app which has a form that asks a user to input a phone number and stores that number in a postgres database. The following code is giving me the error: NoReverseMatch at /main/insert_num/ Reverse for '' not found. '' is not a valid view function or pattern name. And I can't figure out what the issue is, can someone help? index.html <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Test Form 1</title> </head> <body> <form action="{% url 'insert_my_num' %}" method="post" autocomplete="off"> {% csrf_token %} <!-- {{ form.as_p }} --> <input type="submit" value="Send message"> </form> </body> </html> forms.py from django import forms from phone_field import PhoneField from main.models import Post class HomeForm(forms.ModelForm): phone = PhoneField() class Meta: model = Post fields = ('phone',) models.py from django.db import models from phone_field import PhoneField class Post(models.Model): phone = PhoneField() main/urls.py from django.urls import path from . import views urlpatterns = [ path('insert_num/', views.insert_my_num,name='insert_my_num') ] project/urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('main/',include('main.urls')) ] views.py def insert_my_num(request: HttpRequest): phone = Post(request.POST.get('phone')) phone.save() return redirect('') -
why does Django returns BadHeaderError when adding a new line in my 'Contact' page's 'message' field
Everything works except when I add a new line via 'enter' in the "Message" field. It goes through if I don't add new lines in the message textfield. What am i missing here? Tried to solve this problem for 2 days, nothing similar on google. I feel like there could be the problem of my views.py config: def success(request): return render(request, 'home/success.html') def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): # send email code goes here sender_name = form.cleaned_data['name'] sender_email = form.cleaned_data['email'] sender_phone = form.cleaned_data['phone'] sender_message = form.cleaned_data['message'] subject = "Enquiry: {0}".format(sender_message[:50]) message = "New message from {0}\n phone number: {1}\n email: {2}\n\n{3}".format(sender_name, sender_phone, sender_email, sender_message) recipients = ['john.smith@gmail.com'] sender = "{0}<{1}>".format(sender_name, sender_email) try: send_mail(subject, message, sender, recipients, fail_silently=False) except BadHeaderError: return HttpResponse('Invalid header found') return HttpResponseRedirect('success') else: form = ContactForm() return render(request, 'home/contact.html', {'form': form}) Any ideas? -
Data not passing to django template on DetailView
I have a model that should show data on the home page but isn't. I think the problem has to do with fetching data from an external API that also shows on the home page. `models.py` class Stats(models.Model): confirmed = models.CharField(max_length=20) recovered = models.CharField(max_length=20) death = models.CharField(max_length=20) def __str__(self): return str(self.confirmed) `views.py` import services # API comes from services.py class IndexData(DetailView): template_name = 'pages/home.html' stats = Stats.objects.all() def get(self, request): article_data = services.get_data() return render(request, 'pages/home.html', article_data) home.html {% for s in stats %} {{ s.recovered }} {{ s.deaths }} {{ s.confirmed }} {% endfor %} It should show: But is showing: -
"django_site" does not exist on migration
Earlier today I was having some problems with conflicting migrations for various reasons. I decided to just destroy the entire DB and start from scratch (we're pretty early in the project there is no harm in resetting everything). However, when I tried to get things back up and running with manage.py migrate I get this error: File "/Users/travis/Documents/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "django_site" does not exist LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): ... return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "django_site" does not exist LINE 1: ..."django_site"."domain", "django_site"."name" FROM "django_si... ^ This seems to be a very common error and the main solutions I have seen (and tried) are: add SITE_ID = 1 to base.py; in my case, it's already in there. Include "django.contrib.sites" earlier in DJANGO_APPS I've tried putting it first and got the same error. run manage.py migrate sites before other migrations; running this migration gives me the same error. Additionally, I have completely removed the DB, and created a new PGSQL instance, I've removed the project locally and cloned it from our repo. I've tried creating new … -
Record IP Address with Form Submission Django
I am trying to use the django-ipware pacakge to record the IP address of someone submitting a form submission via Django. The form is a ModelForm. Here's the model: # models.py from django.db import models class Upload(models.Model): email = models.EmailField() title = models.CharField(max_length=100) language = models.ForeignKey('about.channel', on_delete=models.CASCADE, default='Other') date = models.DateField(auto_now_add=True) file = models.FileField() ip_address = models.GenericIPAddressField() Here is the form: # forms.py class UploadForm(forms.ModelForm): class Meta: model = Upload fields = ['email', 'title', 'language', 'file'] labels = { 'email': 'E-Mail', 'title': 'Video Title', 'file': 'Attach File' } The business logic for getting the IP address is pretty simple, but I've tried placing it in different locations with no luck. Where should I place the logic so it will be submitted along with the other form data? # views.py from ipware.ip import get_real_ip ip = get_real_ip(request) -
django calendar make first day sunday
Currently my calendar is formatted with Monday being the first day of the week. What I would like is for the first day to be Sunday. I used this to start out: https://medium.com/@unionproject88/django-and-python-calendar-e647a8eccff6 I messed around and began looking at the Documentation but not matter what I added it wouldn't work. utils.py class Calendar(calendar.HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super().__init__() # formats a day as a td # filter events by day def formatday(self, day, events, year, month): events_per_day = events.filter(start_date__day=day).order_by("start_date") d = "" for event in events_per_day: d += f"<a class='calendar-event' href='{reverse('events:detail', args={event.uid})}'>{event.title}</a> <a class='calendar-event-mobile' href='{reverse('events:detail', args={event.uid})}'><i class='fas fa-dot-circle'></i></a>" if day != 0: scope = datetime.date(year, month, day) if scope == datetime.date.today(): return f"<td class='date-today'><span class='date'>{day}</span><div> {d} </div></td>" return f"<td><span class='date'>{day}</span><div> {d} </div></td>" return "<td></td>" # formats a week as a tr def formatweek(self, theweek, events, year, month): week = "" for d, weekday in theweek: week += self.formatday(d, events, year, month) return f"<tr> {week} </tr>" # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): events = Event.objects.filter(start_date__year=self.year, start_date__month=self.month) cal = ( f'<table border="0" cellpadding="0" cellspacing="0" class="table table-striped table-bordered calendar">\n' ) cal += f"{self.formatmonthname(self.year, self.month, withyear=withyear)}\n" … -
Most efficient database design (models) for tracking daily object rankings in huge database
I am designing a Django project that needs to be able to track 1 million+ products and produce daily rankings for which product had the most total number of sales. I need to store and reference this historical ranking data and be able to retrieve rankings for any day in the past. Therefore, my models.py looks like: class Product(models.Model): product_name = models.CharField(max_length=200, unique=True) updated_at = models.DateTimeField(auto_now=True) sub_description = models.CharField(max_length=500, default='') class Rank(models.Model): class Meta(object): unique_together = ['pub_date', 'product'] pub_date = models.DateField(db_index=True) product = models.ForeignKey(Product, on_delete=models.DO_NOTHING) total_sold = models.IntegerField() My plan is to run a django management command script each day. The script will create a new Rank object for each Product in the database every day. Here is a simplified version of the script logic: now = datetime.datetime.utcnow().replace(tzinfo=utc) for prod in Product.objects.all(): try: rank = Rank.objects.get(product=prod, pub_date=now) print("Already updated for ", str(now)) except Rank.DoesNotExist: rank_value = prod_api.get(prod) rank = Rank(product=prod, pub_date=now) rank.total_sold = rank_value rank.save() Because it is possible for a user to request daily rankings while the management command is only halfway through adding new Rank objects for today, the following annotates were a bit tricky for me. I am returning the most recently updated Rank object for each … -
Django how to change the admin panel template
I am trying to change what is displayed when I click on a model in the django admin. For example if I have the model Book and then I go into the admin panel and click book, it will give me all the fields that I created the model with. But I want to edit that page that shows all that data. For example, if I click on the "Book" model in the admin panel and see my fields to edit, I want to put another bit of fields on the bottom from another model. Or maybe I want to put like a "Similar Books" list. Is it possible to edit this page? -
Static url goes after the regular page url
My static files only load on index page, but when navigating to another page like: examle_url/page, it returns a 404 error since it loads it like that: http://127.0.0.1:8000/categories/default/static/js/main.js, see the static loads after page settings.py STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_root/') STATICFILES_DIRS = ( os.path.join(BASE_DIR, '/static/base'), ) urls.py "all my urls are in main directory and then i import views from apps" urlpatterns = [ path('admin/', admin.site.urls), path('profile/', profile, name="profile"), path('', index, name="index"), path('category/', category, name="category"), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) If it matters my load static files are all in theme.html file and is then extended in all other html files. Any help will be greatly appreciated, thanks in advance! -
Having Issues trying to display my Order on my Order page can't seem to find the issue
How I tried to display it on my html template <div class="container"> <div class="col-md-12 h-100"> {% if messages %} {% for msg in messages %} <div class="alert alert-success"> {{msg.message}} </div> {% endfor %} {% endif %} {% for order in order_details %} <p>Order Number: {{order.id}}</p> <p>Order Date: {{order.created}}</p> <table class="table table-bordered table-hover table-condensed"> <thead> <tr> <th>Id</th> <th>Name</th> <th>Quantity</th> <th>Price</th> <th>Total</th> </tr> </thead> <tbody> {% for order_item in order.get_items %} <tr> <td>{{order_item.id}}</td> <td>{{order_item.product}}</td> <td>{{order_item.quantity}}</td> <td>&euro; {{order_item.price}}</td> <td>&euro; {{order_item.get_cost}}</td> </tr> {% endfor %} </tbody> </table> <div class="row"> <div class="col-md-12"> <p class="text-right"><strong>Order Total: &euro; {{order.get_total_cost}}</strong></p> </div> </div> <p> <a href=""><button class="btn btn-primary">Cancel Order</button></a> </p> {% endfor %} <div class="mx-auto"> {% if orders.paginator.num_pages > 1 %} <hr> <div class="text-center"> {% for pg in orders.paginator.page_range %} <a href="?page={{pg}}" class="btn btn-light btn-sm {% if orders.number == pg %} active {% endif %}">{{pg}}</a> {% endfor %} </div> {% endif %} </div> </div> </div> I have two models one for the user to fill out their address and a another to save the use details and products they bought. Not all the code is being displayed just more to do with user details class Order(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() address = models.CharField(max_length=120) address2 … -
using aggregate in generic view django rest
I am going to calculate sum of a field in django but I am failing to do this I am getting this error AttributeError: 'dict' object has no attribute 'model' with annotate it works but it shows one field multiple times that's why I need to use aggregate here my code class TestStatistics(generics.ListAPIView): serializer_class = TestSerializer permission_classes = (permissions.AllowAny,) filter_class = TestStatisticsFilter def get_queryset(self): test_id = self.request.GET.get('test_id') data = Test.objects.filter( test_id=test_id).aggregate(total=Sum('total')) print(data) return data can anybody help me, please? Thanks in advance! -
Django PostGIS spatial query
I'm trying to do a spatial query in Django to a PostGIS database, but I've not been able to do it. I've try it with raw querys a with this GIS QuerySet API Reference. I dont know what I'm doing wrong. this is my modeles.py file: class RayosTotal(models.Model): ka = models.FloatField(db_column='kA', blank=True, null=True) # Field name made lowercase. tiempo = models.DateTimeField(db_column='Tiempo',primary_key=True, blank=True, null=False) # Field name made lowercase. geom = models.PointField(blank=True, null=True) class Meta: managed = False db_table = 'Rayos_total' unique_together = (('lat', 'lng', 'tiempo'),) class Departamentos(models.Model): geom = models.MultiPolygonField(blank=True, null=True) cod_dane = models.IntegerField(db_column='COD_DANE',primary_key=True, blank=True, null=False) nom_dpto = models.CharField(db_column='NOM_DPTO', max_length=250, blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'departamentos' and this is my views.py def join1(request): points = serialize('geojson',RayosTotal.objects.all()) x=serialize('geojson',Departamentos.objects.filter(geom__contains=points)) return HttpResponse(x,content_type='json') #with join1 I get this message: Couldn't create spatial object from lookup value def join2(request): x=RayosTotal.objects.raw("""SELECT "Rayos_total".geom AS geom FROM "public"."Rayos_total" INNER JOIN "public"."departamentos" ON ST_Within("Rayos_total".geom, "departamentos".geom) WHERE "departamentos"."NOM_DPTO" = 'CHOCO'""") return HttpResponse(x,content_type='json') #with join2 I get this message: Raw query must include the primary key any ideas ? thank you for the help -
Keep Bootstrap dropdown open a new page?
I use a bootstrap dropdown in my django framework. In the dropdown menu in my sidebar there are several links to other pages. If I click it, my dropdwon menu disappear becouse the menu fades away. Is there anyway way to prevent this? I tried e.startPropagation, but that didn't seem to work: Here the HTML section with the dropdown manu: <div class="container-fluid"> <div class="row"> <nav class="col-md-2 d-none d-md-block bg-dark sidebar"> <div class="sidebar-sticky"> <ul class="nav flex-column"> <li class="nav-item"> <a class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1" href="#homeSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">Performance Monitoring<span data-feather="plus-circle"></span></a> <ul class="collapse list-unstyled" id="homeSubmenu"> <li> <a class="nav-link" href="#"> <span data-feather="monitor"></span> Dashboard</a> </li> <li> <a class="nav-link" href="#"> <span data-feather="trending-up"></span> Conto Economico</a> </li> <li> <a class="nav-link" href="#"> <span data-feather="home"></span> Stato patrimoniale </a> </li> <li> <a class="nav-link" href="#"> <span data-feather="dollar-sign"></span> Rendiconto Finanziario</a> </li> </ul> </li> -
Invalid input syntax for type inet
Im having trouble persisting ip_addresses from my users via Django into Postgres. Can I just convert the ip_address field from inet to string and store that in the VARCHAR postgres field? -
After setting up cookiecutter for Django, I get a ConnectionRefusedError for sign-up and sign-in
I'm working on a project using cookiecutter, but for whatever reason, I can't sign in or sign up. If I sign in as a superuser through the admin, I am then logged in when I refresh the homepage and have access to the site, but can't authenticate otherwise. This is the error: ConnectionRefusedError at /accounts/login/ [WinError 10061] No connection could be made because the target machine actively refused it Request Method: POST Request URL: http://127.0.0.1:8000/accounts/login/ Django Version: 3.0.5 Exception Type: ConnectionRefusedError Exception Value: [WinError 10061] No connection could be made because the target machine actively refused it Exception Location: C:\Users\Machine\miniconda3\envs\portfolio\lib\socket.py in create_connection, line 796 Python Executable: C:\Users\Machine\miniconda3\envs\portfolio\python.exe Python Version: 3.8.2 Python Path: ['C:\Users\Machine\Desktop\portfolio-project', 'C:\Users\Machine\miniconda3\envs\portfolio\python38.zip', 'C:\Users\Machine\miniconda3\envs\portfolio\DLLs', 'C:\Users\Machine\miniconda3\envs\portfolio\lib', 'C:\Users\Machine\miniconda3\envs\portfolio', 'C:\Users\Machine\AppData\Roaming\Python\Python38\site-packages', 'C:\Users\Machine\miniconda3\envs\portfolio\lib\site-packages', 'C:\Users\Machine\Desktop\portfolio-project\portfolio', 'C:\Users\Machine\Desktop\portfolio-project\portfolio'] Server time: Mon, 20 Apr 2020 15:19:25 -0500 When I search for this error, I get some references to setting up an e-mail back-end, but as far as I can tell, this is already set up for local development. I went through Daniel Feldroy's Django Crash Course which uses a modified version of cookiecutter, but don't remember having this issue then. -
ValueError at /books/results/
"Field 'id' expected a number but got 'results'." I'm getting this error while trying to use search filter over a list of books. It was working fine until I changed the Class-based view to Function based view. This was the Class based view earlier using the default DetailView class: class BookDetailView(LoginRequiredMixin,DetailView): model = models.Book template_name='book_detail.html' login_url='login' This is the new Function based detail view I changed to: @login_required def book_detail(request,book_id): model =models.Book book=model.objects.get(id=book_id) template ='book_detail.html' owner =CustomUser.objects.get(username=book.owner) return render(request,template,{'book':book,'owner':owner}) Independently when I'm trying to go to detail view, its working fine. But when I try to search using the 'book_search' view, its throwing this error. Previously search functionality was also working fine. @login_required def book_search(request): template ='book_list.html' model =models.Book query =request.GET.get('q') results =model.objects.exclude(owner =request.user).order_by('-available','-id') if query: results =results.filter(Q(title__icontains =query)) paginator = Paginator(results, 9) page =request.GET.get('page') try: books =paginator.page(page) except PageNotAnInteger: books =paginator.page(1) except EmptyPage: books= paginator.page(paginator.num_pages) return render(request,template,{'books':books,'query':query,'page':page}) It has something to do with the result set that the search view is returning a list of books while detail view only require just one id. -
Failing Docker install of Jupyter on Django
I'm following the recommended way to install jupyter on django by installing the following pip packages: jupyter ipython django-extensions As described here for example: https://medium.com/ayuth/how-to-use-django-in-jupyter-notebook-561ea2401852 it was working for a while but since some days is failing and I cannot figure out what the problem really is: The error I'm getting is the following: ERROR: Complete output from command /usr/local/bin/python /usr/local/lib/python3.6/site-packages/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-2xou1hp2/overlay --no-warn-script-location --no-binary :none: --only-binary :none: --no-index -- setuptools wheel 'ipython>=5' 'jupyter_core>=4.2' jupyter_client: ERROR: Collecting setuptools ERROR: Could not find a version that satisfies the requirement setuptools (from versions: none) ERROR: No matching distribution found for setuptools something seems to have broken the install but I'm lost about what it is. -
Django : error with form_valid and get_full_path()
I am trying to acquire the current tenant's domain name through a form. I am trouble with writing the view that would achieve that. here is my form.py: class ETL(forms.Form): Historical = forms.FileField() Pre_processing = forms.FileField() Supplier = forms.FileField() parameters = forms.FileField() def process_data(self, *args, **kwargs): url = self.request.get_full_path() dbschema = remove_www(url.split(':')[0]).lower() engine = create_engine('postgresql://pierre:56-Pmtmpmtm@127.0.0.1:5432/dbexostock12', connect_args={'options': '-csearch_path={}'.format(dbschema)}) fh = io.TextIOWrapper(self.cleaned_data['Historical'].file) fpp = io.TextIOWrapper(self.cleaned_data['Pre_processing'].file) fs = io.TextIOWrapper(self.cleaned_data['Supplier'].file) fp = io.TextIOWrapper(self.cleaned_data['parameters'].file) .... view.py @method_decorator(login_required, name='dispatch') class Getfiles(LoginRequiredMixin,FormView): template_name = 'upload.html' form_class = ETL success_url = 'Home' def form_valid(request, form): url = request.get_full_path() form.process_data() return super().form_valid(form) and here is the error that I get: AttributeError at /upload.html 'Getfiles' object has no attribute 'get_full_path' I am beginner with django, I am not sure how to resolve this, and the documentation about it got me a bit confused, especially about the form_valid() method. Thank you! -
Required parameter name not set - Django + Amazon S3
I'm trying to setup Amazon S3 for my Django app and I keep getting told 'Required parameter name not set '. This error seems to happen when an image needs to be displayed. For example, it works fine on the homepage where there are no images. Really don't know where I have went wrong. I have following set up in my settings.py. INSTALLED_APPS = [ 'projects', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', ] #S3 BUCKET CONFIG AWS_ACCESS_KEY_ID = 'acccess key' AWS_SECRET_ACCESS_KEY = 'secret access key' AWS_BUCKET_NAME = 'bucket name' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' Full traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/projects/createListing Django Version: 2.2 Python Version: 3.7.3 Installed Applications: ['projects', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages'] Installed Middleware: ['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'] Template error: In template C:\Users\Maksims\Desktop\CA4106-Cloud-Computing\test\src\personal_portfolio\templates\base.html, error at line 10 Required parameter name not set 1 : {% load static %} 2 : <!doctype html> 3 : <html lang="en"> 4 : <head> 5 : <!-- Required meta tags --> 6 : <meta charset="utf-8"> 7 : <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 8 : 9 : <!-- Bootstrap CSS --> 10 : <link re l="stylesheet" href="https://stack … -
Django ValidationError EmailField
I've been struggling with this error below. I am trying to checkout a user as guest with email but I get a validation error: ValidationError at /register/guest['“NU1@company.com” value must be either True or False.'] next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None if form.is_valid(): email = form.cleaned_data.get('email') new_guest_email = GuestEmail.objects.create(email=email) request.sesssion['guest_email_id'] = new_guest_email.id if is_safe_url(redirect_path, request.get_host()): return redirect(redirect_path) else: return redirect('/register/') return redirect('/register/') -
Displaying User Data in Django Admin from multiple models
If I have user data stored in multiple models (Account, x, y, z), how can I have them all displayed on one admin page? For example, If I try something along the lines of: from account.models import Account, XModel, YModel, ZModel class AccountAdmin(UserAdmin): list_display = ('email', . . . , 'a', 'b', 'c') # . . . admin.site.register(Account, AccountAdmin) admin.site.register(XModel, AccountAdmin) admin.site.register(YModel, AccountAdmin) admin.site.register(ZModel, AccountAdmin) I'll get a ton of error messages, i.e. System check identified 30 issues (0 silenced). -
Making changes to Add page description in Django Admin
I'm working on django.And have created a custom user model for sign up.But in the add page there a description which I want to change,have a look at the red mark in the pic And my admin file look like this: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): summary="hi" list_display = ('first_name','last_name','email','is_staff', 'is_active',) list_filter = ('first_name','email', 'is_staff', 'is_active',) search_fields = ('email','first_name','last_name','a1','a2','city','state','pincode') ordering = ('first_name',) add_fieldsets = ( ('Personal Information', { # To create a section with name 'Personal Information' with mentioned fields 'description': "", 'classes': ('wide',), # To make char fields and text fields of a specific size 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','check', 'password1', 'password2',)} ), ('Permissions',{ 'description': "", 'classes': ('wide', 'collapse'), 'fields':( 'is_staff', 'is_active','date_joined')}), ) fieldsets = ( ('Personal Information', { 'classes': ('wide',), 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','password')}), ('Permissions', {'fields': ('is_superuser','is_staff', 'is_active','date_joined')}), ) admin.site.register(CustomUser, CustomUserAdmin) What should I add to my admin file and where so that I change it?? Thanks in advance!! -
Django Rest Framework serialization.save() parameters
The below code perform saving new user inputs. In the serializer.save() code block why can't we pass data like serializer.save(ebook,review_author) instead serializer.save(ebook=ebook,review_author=review_author) ? class ReviewCreateView(CreateAPIView): queryset = Review.objects.all() serializer_class = ReviewSerializers def perform_create(self, serializer): pk = self.kwargs.get('e_pk') ebook = get_object_or_404(Ebook,pk=pk) review_author = self.request.user serializer.save(ebook=ebook,review_author=review_author) -
How to make Django Rest Apis Async
Following is my Django application configuration: django = 2.2.11 djangorestframework = 3.9.2 Python = 3.8.2 I am exposing a set of Rest apis for react js frontend, which connects to Postgres using a layered architecture views (controller) - services - data_layer. In data layer, I fetch the data using Connection.Cursor, then transform the data fetched using cursor.fetchall. By default the rest apis are synchronous apis, I am trying to find a way to make them Async, so that system scalability can be increased, otherwise every call will block the main thread. I have tried the following options: Using asyncio library, but I am unable to make the complete call chain Async. I generally get an error that expected return was Response / HttpResponse, but the method is returning Co-routine. I can find examples which contains running simple methods as async, but there's isn't an example of Django Rest API Tried the following link, which use the Threadpool executor to segregate every call on a thread in the controller itself, though the challenge is where to make the Asyncio call in the Main method as shown in the link, since these APIs are externally invoked. Can aiohttp help, not sure, but …