Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django view function for navbar
I have my page only for navigation bar and I include it in base page. Now I have drop down menu in that navigation bar and links I get from database(that links are my categories). But how can I call my function in views without path, because I don't need to have path for navigation bar? And I need that view function to get data from database. -
The 'imagem_post' attribute has no file associated with it
Estou tentando fazer com que as imagens estejam na tela.Estou tentando resolver isso parece que meu código não está reconhecendo as informações do meu model.py, tudo isso acontece quando tento chamar as informações na tag do html. model.py import django from django.db import models from categorias.models import Categoria from django.contrib.auth.models import User from django.utils import timezone class Post(models.Model): titulo_post = models.CharField(max_length=255, verbose_name='Titulo') autor_post = models.ForeignKey(User, on_delete=models.DO_NOTHING, verbose_name='Autor') data_post = models.DateTimeField(default=django.utils.timezone.now, verbose_name='Data') conteudo_post = models.TextField(verbose_name='Conteúdo') excerto_post = models.TextField(verbose_name='Excerto') categoria_post = models.ForeignKey(Categoria, on_delete=models.DO_NOTHING, blank=True, null=True, verbose_name='Categoria') imagem_post = models.ImageField(upload_to='post_img/%Y/%m/%d', blank=True, null=True, verbose_name='Imagem') publicado_post = models.BooleanField(default=False, verbose_name='Publicado') def __str__(self): return self.titulo_post Na tag de img é onde estou tentando referenciar minhas imagens quando coloco: imagem_post.url aí começa a dar erro se eu não colocar .url o erro some mais eu fico sem imagens na tela index.html {% extends 'base.html' %} {% load static %} {% block conteudo %} <!-- CONTENT --> <div class="card-columns mt-4"> <!-- FOR LOOP --> {% for post in posts %} <div class="card"> <a href="post.html"> <img class="card-img-top" src="{{ post.imagem_post.url }}" alt="{{ post.titulo_post.url }}"> </a> <div class="card-body"> <h5 class="card-title"> <a href="post.html">A wonderful </a> </h5> <p class="card-text">When, while the lovgleams steal ...</p> <p class="card-text"> <small class="text-muted">hoje | 1 comentário | Tecnologia</small> </p> … -
python selenium - how can i find out exactly when an alert happens?
I want to find out when an alert happens so I can automatically accept. I've placed self.driver.switch_to.alert.accept() in various places in the code but I always get a selenium.common.exceptions.NoAlertPresentException. When I don't place it anywhere I get an selenium.common.exceptions.UnexpectedAlertPresentException. When I use expected_conditions I get a selenium.common.exceptions.TimeoutException. I don't know what to do at this point. Can anyone help? Python/Django Backend. Using Selenium (Firefox) -
why models.BooleanField returning bytes instead of Boolean value?
I am trying to assigning a boolean value to model.BooleanField otp_object = models.Otp( blocked=(user_agent is None and route == 'exposed') ) Here is where I am checking if the bool is true but it's returning b'\x00' if otp_object.blocked: I am unable to understand where I am going wrong? -
Django HTML User authentication
I have a condition like this: {% if object.author == user or object.res_person_1_username == user %} If I view variables with, for example: <p class="article-content mb-1"><strong>object.res_person_1_username: </strong>{{ object.res_person_1_username }}</p> They are the same, all three, but condition object.res_person_1_username == user is always False. Why is that? What I'm missing? Do I need to change data type or something? models.py res_person_1_username = models.TextField(blank=True, max_length=40) -
How to seperate import and export fields in Django-Import-Export
I am using Django-Import-Export and have a model-fields like below id, date, val1, val2, val3 what i want is to import by only 2 fields (date and val1) and i want to export 4 fields (date val1 val2 val3) if i do like below i can see import fields changing but in export only 2 fields are coming class MyResource(ExportImportObjectHere): class Meta: model = ModelName skip_unchanged = True fields = ('date', 'val1') -
Django 1.11's signed_cookie session backend sets a new sessionid for every request
This makes the vary_on_cookie decorator useless because the coookie is different at every request, and also it makes the sessions never expire regardless of SESSION_COOKIE_AGE because every request pushes the expiration forward. I did some digging, and process_response in sessions/backends/middleware.py does request.session.save(), which causes the signed_cookie backend to create a new session key with this code: return signing.dumps( self._session, compress=True, salt='django.contrib.sessions.backends.signed_cookies', serializer=self.serializer, ) This code returns a different value even if called with the same argument (I guess it's built into the encryption). Am I missing something? This doesn't sound right... any ideas? Thanks! -
How do I make Django Website public on my local network?
I am building a website for myself and family in Django and React. Every time I ask them to check my process and get their opinions they get a webpage not found error or this site can't be reached. How do I make is so that anyone on my local network can check my page when its running. This is the default in flask, I don't understand why django runs like this? (safety maybe?) I can't find any good information on how to add an allow all to the ALLOWED_HOSTS section in the settings of the main app. I also know that you can add IP address, But I'm a noob and I don't follow how to get the ip address of all my families devices without alot of work?? Does anyone have a good solution for this?? -
Django zappa error: InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on
So, I'm using Zappa on AWS Lambda. I just added a custom user model to my project and tried to migrate to the RDS on AWS and Zappa gives me the following error: InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on database 'default'. Now, I know that if I got this error on my local server, I would do this: python manage.py migrate admin zero python manage.py migrate auth zero python manage.py migrate contenttypes zero python manage.py migrate sessions zero I would then run the migrations to destroy their tables and recreate them again (see this helpful SO post) However, if I ran zappa manage dev migrate after that, I get InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on database How should I do the same thing on the AWS RDS using Zappa or should I do something else? -
How to get the Refresh Token with the django-graphql-social-auth library
Hi I am using the django-graphql-social-auth library and whenever I create a social user using this mutation: import graphene import graphql_social_auth class Mutations(graphene.ObjectType): social_auth = graphql_social_auth.SocialAuthJWT.Field() and this Graphql mutation: mutation SocialAuth($provider: String!, $accessToken: String!) { socialAuth(provider: $provider, accessToken: $accessToken) { social { uid } token } } I am just able as you see to get the token. Because if add the refreshToken to be also returned from the mutation (just as I did with the token above) it says it refreshToken is not defined. So I am not actually sure about how to get the refreshToken using this library. -
django: View to delete html table row not taking effects in Database
I have a page that displays rows from a db table. I added a button to each row that is designed to delete the row upon its click as well as redirect toward a deleted confirmation page. Everything seems to work, unless that nothing gets deleted in the database table. Here is what my views.py look like: def ProductsView(request): queryset = Products.objects.all() products_list = list(queryset) request.session['context'] = products_list #table = ProductsTable(queryset) #context = {'table':table} return render(request, 'inventory.html', {'products_list':products_list}) def DeleteProduct(request, Id): Products.objects.filter(ProductId=Id).delete() return render(request,'delete_confirmation.html') and here is what the html page look like, including the code for the delete button <table class="table text-center table-bordered table-hover"> <thead class="thead-dark"> <tr> <th scope="col">ID</th> <th scope="col">NAME</th> <th scope="col">CATEGORY</th> <th scope="col">TAG NUMBER</th> <th scope="col">STOCK ON HAND</th> <th scope="col">DELETE</th> </tr> </thead> <tbody style="background-color: white"> {% for Products in products_list %} <tr> <td>{{ Products.ProductId }}</td> <td>{{ Products.ProductName }}</td> <td>{{ Products.ProductCategory }}</td> <td>{{ Products.ProductTagNumber }}</td> <td>{{ Products.StockOnHand }}</td> <td> <a class="btn btn-primary" href="{% url 'delete_confirmation' Id=Products.ProductId %}" style="color: white">Delete</a> </td> </tr> {% endfor %} </tbody> </table> I can't find out what I am doing wrong, I have been at it all day and need a pair of fresh eyes to look at it! Does anyone has a clue … -
How to optimize Django API Query
How can I optimize my api View or Serializer ? It takes more than 3 minutes to perform the task. I think it due to foreign key fields but even I retrieve them on the serializer fields, it still run slowly. api/View.py @api_view(['GET', 'POST']) def edge_list(request): """ List all edges of all networks, or create a new edge. """ if request.method == 'GET': edges = Edge.objects.all() context = {'request': request} # for filtering by field in url serializer = EdgeSerializer(edges, many=True, context=context) return Response(serializer.data) elif request.method == 'POST': serializer = EdgeSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.error, status=status.HTTP_400_BAD_REQUEST) api/serializers.py class EdgeSerializer(DynamicFieldsMixin, serializers.ModelSerializer): class Meta: model = Edge fields = ( 'id', 'edge_id', 'name', 'length', 'speed', 'lanes', 'param1', 'param2', 'param3', 'network', 'road_type', 'source', 'target' ) api/models.py class Edge(models.Model): network = models.ForeignKey(RoadNetwork, on_delete=models.CASCADE) source = models.ForeignKey(Node, related_name='source', on_delete=models.CASCADE, help_text='Source node of the edge', ) target = models.ForeignKey(Node, related_name='target', on_delete=models.CASCADE, help_text='Target node of the edge', ) road_type = models.ForeignKey(RoadType, on_delete=models.CASCADE, help_text='Roadtype of the edge' ) edge_id = models.PositiveBigIntegerField(db_index=True) name = models.CharField(max_length=80, blank=True, help_text='Name of the edge') geometry = models.LineStringField() length = models.FloatField() speed = models.FloatField(null=True, blank=True) lanes = models.SmallIntegerField(null=True, blank=True) param1 = models.FloatField(null=True, blank=True) param2 = models.FloatField(null=True, blank=True) param3 = models.FloatField(null=True, … -
how to make full html page as pfd in django
i have a html page in my django templates, its a pdf type, the for loop should make a transactions based on the number of which the object model returns, however i want every transaction to be in a full html page, and the other transaction come net page, i have tried to do it but seems a bit hard since im new to django html. {% extends "base.html" %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> {% block title %} Report {% endblock title %} <div id="container"> {% block content %} {% for transaction in transactions %} {% if transaction.complete %} <table class="tg"> <thead> <tr> <th class="tg-fv77" colspan="12" rowspan="2"><span style="color:#3531FF">Report For Tenant ( {{ transaction.chp_reference }} )</span></th> </tr> <tr> </tr> </thead> <tbody> <tr> <td class="tg-0pky" colspan="9">CHP Reference</td> <td class="tg-0pky" colspan="3">{{transaction.chp_reference}}</td> </tr> <tr> <td class="tg-0pky" colspan="9">Rent Effective From (dd/mm/yyyy)</td> <td class="tg-0pky" colspan="3">{{transaction.rent_effective_date}}</td> </tr> <tr> <td class="tg-0lax" colspan="9">CRA Fortnightly Rates valid for 6 months from</td> <td class="tg-0lax" colspan="3">{{transaction.cra_rate_from}}</td><hr> </tr> <tr> <td class="tg-0lax" colspan="9">Market Rent of the Property</td> <td class="tg-0lax" colspan="3">{{transaction.property_market_rent}}</td> </tr> <tr> <td class="tg-0lax" colspan="9">Number of Family Group(s)</td> <td class="tg-0lax" colspan="3">{{transaction.number_of_family_group}}</td> </tr> </tbody> </table> {% if transaction.complete %} <table class="tg" style="undefined;table-layout: fixed; width: 714px"> <colgroup> <col style="width: … -
Reference an unsaved field on a Django model when saving
I am uploading my media to an S3 bucket and would like to reference the name field before uploading to S3. class Customer(models.Model): name = CharField() img = ImageField(upload_to='<name>/avatars/') How do I use the name field dynamically in upload_to? -
Django: combining a DetailView and a form on the same view
Is there a way I can combine a detailview and a form into the same view? I'm making a rental system where when a user clicks on a particular house, he will be directed to a detailview page of that house. And after viewing the details of the house he intends to rent, he will fill a form while still on the detailview page then the form will be saved in the database. Here's what I have so far views.py class HouseDetailView(DetailView): model = House template_name = 'Home/detail.html' def get_context_data(self, **kwargs): context = super(HouseDetailView, self).get_context_data(**kwargs) context['house_list'] = House.objects.all() return context def Callback (request): form = CallbackForm() if request.method == 'POST': form = CallbackForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Callback Submission Successful.') return redirect('Home') context = {'form':form} return render(request, 'Home/callback.html', context) urls.py from django.urls import path from .views import ( HouseView, HouseDetailView, ) from . import views urlpatterns = [ path('Home/', views.Home, name='Home'), path('SignUp/', views.SignUp, name='SignUp'), path('Login/', views.Login, name='Login'), path('house/', HouseView.as_view(), name='house'), path('callback/', views.Callback, name='callback'), path('Logout/', views.Login, name='Logout'), path('<slug:slug>/', HouseDetailView.as_view(), name='detail'), ] forms.py from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from .models import House, Lease, Agent, Customer, Callback class CreateUserForm(UserCreationForm): class Meta: model … -
I can't get a value from a field in a one-to-one relationship, tabularinline
How do I get the value from the field in a one-to-one relationship. The tables Tables and Table are linked using TabularInline. And I want to get a value from a field by OneToOneField relationship. I do it with signals. In this case I'm using post_save. I get an error "Tables has no data" class Tables(models.Model): title = models.CharField(max_length=10) class Table(models.Model): count = models.IntegerField() obj = models.OneToOneField(Tables, on_delete=models.CASCADE, related_name="data") @receiver(post_save, sender = Tables) def create(instance, sender, **kwargs): print(instance.data) If I write it like this, it returns the old queryset @receiver(post_save, sender = Tables) def create(instance, sender, **kwargs): print(Table.objects.filter(table__id=instance.id)) -
Django Resf Framework: auto fill a field of a Model when POST?
Is there a way of filling some particular fields in a model using a field value of another model object? For example, I thought of the following scenario: 1 - there are some models from django.db import models class Supplier(models.Model): supplier = models.Charfield(max_length=50, unique=True) class Object(models.Model): object = models.Charfield(max_length=50) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, to_field="supplier") class Transaction(models.Model): object_id = models.ForeignKey(Object, on_delete=models.CASCADE) supplier = models.Charfield(max_length=50) 2 - Those models are serialized from . import models from rest_framework.serializers import ModelSerializer class SupplierSerializer(ModelSerializer): class Meta: model = models.Supplier fields = '__all__' class ObjectSerializer(ModelSerializer): class Meta: model = models.Object fields = '__all__' class TransactionSerializer(ModelSerializer): class Meta: model = models.Transaction exclude = ('supplier',) 3 - And there is a view from . import models, serializers from rest_framework.viewsets import ModelViewSet class TransactionApiViewset(ModelViewSet): queryset = models.Transaction.objects.all() serializer_class = serializers.TransactionSerializer When submiting a post with 'object_id' field to Transaction Api, I'd like that the 'supplier' field in Transaction Model autofills with the 'supplier' field value of Object object related to 'object_id'. I'd appreciate any help. -
Many-to-many relationships | adding objects
I have two moedls, Factures and Réglements In template i have a list of factures objects with checkbox next to every one using this method i want to add a Réglements for the checked objects Views: def Ajout_Réglement_Vente(request): if request.method == "POST": N_Réglement = request.POST["Numéro_Réglement"] Date_Réglement = request.POST["Date_Réglement"] réglement = Réglements(N_Réglement=N_Réglement, Date_Réglement= Date_Réglement) réglement.save() if not request.POST.get('Action', None) == None: m = request.POST.getlist('Action') for i in m: f = Factures.objects.get(pk=i) f.Type_Facture = 'Facture Vente Réglé' f.save() Models: class Réglements(models.Model): N_Réglement=models.CharField( max_length=50, default='null') Date_Réglement=models.DateField(auto_now_add=False, auto_now=False,blank=True, null=False) Mode_Réglement=models.CharField(max_length=50, default='null') Montant= models.CharField(max_length=50, default='null') N_Pièce = models.CharField(max_length=50, default='null') Factures = models.ManyToManyField(Factures) def __str__(self): return self.N_Réglement class Factures(models.Model): N_Facture=models.CharField( max_length=50, default='null') Date_Facture=models.DateField(auto_now_add=False, auto_now=False,blank=True, null=False) Valeur= models.CharField(max_length=50, default='null') Type_Facture = models.CharField(max_length=50, default="Facture Achat") def __str__(self): return self.N_Facture -
Even after having the account_account I am facing the error "django.db.utils.ProgrammingError: relation "account_account" does not exist"
I am trying to create a API with OAuth 2 Authentication. I have created custom user models called Accounts. When I am running the command "py manage.py migrate" it is throwing me the below error. E:\Django\api\app>py manage.py migrate Operations to perform: Apply all migrations: account, admin, app_v2, auth, contenttypes, oauth2_provider, sessions, social_django Running migrations: Applying oauth2_provider.0001_initial...Traceback (most recent call last): File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "account_account" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "E:\Django\api\app\manage.py", line 22, in <module> main() File "E:\Django\api\app\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 230, in apply_migration migration_recorded = True File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\schema.py", line 118, in __exit__ self.execute(sql) File "C:\Users\HAMEED-PC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\schema.py", line … -
Django CRUD :Update function is not working
I made CRUD in django. Update is not working while creating and deleting views are working.Pleas fix my problem.And tell me where i am lacking. This is views.py: ` from .import models from django.http import HttpResponse,HttpResponseRedirect from django.shortcuts import render from .forms import readerRegistrationForm from .models import Reader, books from django.views.generic import TemplateView,RedirectView,UpdateView from django.views import View # Create your views here. def done(request): return render(request,'done.html') class addshowView(TemplateView): template_name='add&show.html' def get_context_data(self,*args,**kwargs): context= super().get_context_data(**kwargs) fm=readerRegistrationForm() stu=Reader.objects.all() cone=books.objects.all() context={'str':stu,'form':fm,'con':cone} return context def post(self,request): fm=readerRegistrationForm(request.POST) if fm.is_valid(): fm.save() return HttpResponseRedirect('/') class userdeleteview(RedirectView): url='/' def get_redirect_url(self, *args, **kwargs): p=kwargs['id'] Reader.objects.get(pk=p).delete() return super().get_redirect_url(*args, **kwargs) class Updateview(UpdateView): def get(self,request,id): pi=Reader.objects.get(pk=id) fm=readerRegistrationForm(instance=pi) return render(request,'updateit.html',{'form':fm}) def post(self,request,id): pi=Reader.objects.get(pk=id) fm=readerRegistrationForm(request.POST,instance=pi) if fm.is_valid(): fm.save() return render(request,'updateit.html',{'form':fm})` This is forms.py ''' from django.forms import fields, widgets from .models import books,Reader class readerRegistrationForm(forms.ModelForm): class Meta: model=Reader fields=['name','email','comment'] 'this is models.py' from django.db.models.deletion import CASCADE #Create your models here. class books(models.Model): name=models.CharField(max_length=200) gener=models.CharField(max_length=200) author=models.CharField(max_length=200) isbn=models.BigIntegerField() def __str__(self) : return self.name class Reader(models.Model): name=models.CharField(max_length=200) email=models.EmailField(max_length=200) comment=models.TextField() def __str__(self) : return self.comment ''' This is urls.py ''' from django.contrib import admin from django.urls import path from boom import views urlpatterns = [ path('', views.addshowView.as_view() , name='show'), path('updated/',views.done,name='done'), path('delete/<int:id>/', views.userdeleteview.as_view() , name='doNow'), path('update/<int:id>/', views.Updateview.as_view() , name='UpNow'), … -
How to run Django channels with StreamingHttpResponse in ASGI
I have a simple app that streams images using open cv and the server set in wsgi. But whenever I introduce Django channels to the picture and change from WSGI to ASGI the streaming stops. How can I stream images from cv2 and in the same time use Django channels? Thanks you in advance My code for streaming: def camera_feed(request): stream = CameraStream() frames = stream.get_frames() return StreamingHttpResponse(frames, content_type='multipart/x-mixed-replace; boundary=frame') settings.py: ASGI_APPLICATION = 'photon.asgi.application' asgi.py application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AuthMiddlewareStack(URLRouter(ws_urlpatterns)) }) -
Django - Authentication not functioning in when deployed
I am unable to log in after deploying my Django application, but can when using the inbuilt dev server. I'll put the error and what im using below. I have migrated to the live sql server with no errors. I created a superuser with no errors. the only real change to the django files was getting static files set up which shouldnt impact the db (where im assuming this error is coming from). Here is the error: TypeError at /login/ argument of type 'NoneType' is not iterable Request Method: POST Request URL: http://sitename/login/ Django Version: 3.0 Exception Type: TypeError Exception Value: argument of type 'NoneType' is not iterable Exception Location: c:\python39\lib\site-packages\sql_server\pyodbc\base.py in encode_value, line 59 Python Executable: c:\python39\python.exe Python Version: 3.9.4 Now a few core notes about whats running in the environment and how its deployed: deployed on windows IIS utilizing mssql with django_mssql_backend-2.8.1 (ive verified all packages are on the same version. I think the only difference is python on 3.9.1 in dev vs 3.9.4 in prod) Django 3.0 SQL Server is on 2019 in dev vs 2017 in prod. not sure if that changes anything or i need to change any settings due to this but the inital … -
Can we deploy Two stand alone projects On Production Level and connect it together
My Social Media Team want to use NodeJs(for backend) and ReactJs(for frontend). and my other team want to use Django(for backend) and ReactJs(Frontend). My Question is Can We connect these two Program together on the production level and make it a single project at time of deployment? -
All values go into one column in a table in Django. How to separate?
I would like to create a table as an output, like in the picture below. views.py: test = filtered_transaction_query_by_user.values('coin__name').annotate( total = (Sum('trade_price' ) * Sum('number_of_coins'))).order_by('-total') Desired outcome: What I has tried: Can you please help me why all goes under the Currency, and not into the Number of coins column? -
I have a problem in POST method in python
I am using windows(10) and django library I wanted to make sign up option in my e-commerce so I made an app called accounts, I wrote in its models from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) print('In Post') else: form = UserCreationForm() context = {'form' : form} return render(request , 'registration/signup.html' , context) And I wrote in my signup.html page {% extends "base.html" %} {% block body %} <main class="mt-5"> <div class="container mynav"> <form action="" method="post"> {% csrf_token %} {{form}} <button type="submit" class="btn btn-primary">Sign up</button> </form> </div> </main> {% endblock body %} The problem in the POST method when I tried to run it he said The view accounts.views.signup didn't return an HttpResponse object. It returned None instead. What do I write to solve this problem? And Thanks.