Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to use docker-compose for ecs farget deployment by cdk?
Current, my source code is here below export class CdkFargateStack extends Stack { constructor(scope: Construct, id: string, props?: StackProps) { super(scope, id, props); const cluster = new ecs.Cluster(this, "SampleCluster", { clusterName: "SmapleCluster" }); const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef"); const container = taskDefinition.addContainer("DefaultContainer", { image: ecs.ContainerImage.fromAsset("app"), memoryLimitMiB: 512, cpu: 256 }); container.addPortMappings({ containerPort: 3000 }); const ecsService = new ecs.FargateService(this, "Service", { cluster, taskDefinition, desiredCount: 2 }); const lb = new elb.ApplicationLoadBalancer(this, "LB", { vpc: cluster.vpc, internetFacing: true }); const listener = lb.addListener("Listener", { port: 80 }); const targetGroup = listener.addTargets("ECS", { protocol: elb.ApplicationProtocol.HTTP, port: 3000, targets: [ecsService] }); new cdk.CfnOutput(this, "LoadBalancerDNS", { value: lb.loadBalancerDnsName }); } } It build the Dockerfile under app directory (app/Dockerfile) and It works well. However now I want to use two docker written in docker-compose.yml, Dockerfile.django and Dockerfile.nginx are built in docker-compose. There are files app/docker-compose.yml app/Dockerfile.nginx app/Dockerfile.django Different from Dockerfile, it makes two docker image. So my idea is 1) Ignore docker-compose.yml and make two containers somehow? (I want to indicate the docker file name though,,) const container1 = taskDefinition.addContainer("DefaultContainer", { image: ecs.ContainerImage.fromAsset("app/Dockerfile.django"), memoryLimitMiB: 512, cpu: 256 }); const container2 = taskDefinition.addContainer("DefaultContainer", { image: ecs.ContainerImage.fromAsset("app/Dockerfile.ngingx"), memoryLimitMiB: 512, cpu: 256 }); I can use … -
when i trying to object.save() i got an error "missing 1 required keyword-only argument: 'manager'" in django
when i trying save something in views . get an error , " post_obj.save() TypeError: __call__() missing 1 required keyword-only argument: 'manager' " models.py class Post(models.Model): title = models.CharField(max_length=150) owner = models.ForeignKey(Customer, on_delete=models.CASCADE) views.py @api_view(["POST"]) def create_post(request): if request.data != {}: id = request.data["customer_id"] title = request.data["title"] user = Customer.objects.filter(id=id) if user.count() != 0: post_obj = Post(owner=user, title = title) post_obj.save() then i get this error . how can i fix this error ? -
Django - Diplay a form in a modal
I'm building a Django application and I try to display one of my forms in a modal window. It has been initially developed for a normal one, the scripts worked fine, but I cannot manage implement properly the modal. The context is classical: a window displays a list of objects with, for each of them, a button to edit it, and an additional global button to create a new object. Each button is supposed to open the same modal. It could have become easy if I did not have several js scripts dedicated to the form, because they are my issue: the do not work properly now that the form is in a modal. So there is something I did wrong, and at the end I'm not even sure my approach is the best one. The modal is displayed using bootstrap, HTML code is the following: <div id="grp_detail" class="modal fade hide" role="dialog" tabindex='-1'> <div class="modal-dialog modal-lg"> <div class="modal-content form_content"> {% include './adm_group_detail.html' %} </div> </div> </div> Tell me if you need the included template - it's quite big because the form is a bit tricky. The view that displays de page with the list is the following: @user_passes_test(lambda u: u.is_superuser … -
Define email subject in a Django template
Say I want to send an email using the send_mail() method. The body of the email lives in templates/email.html. I would like to define the email subject in the same file to keep things in one place. But send_mail() needs the subject in a separate variable. So I came up with an ugly hacky way to do it. I start the template like this: {% comment "The second line of this template will be used as email subject" %} Congratulations, your account was created! {% endcomment %} And then extract it in the code like this: template = loader.get_template('email.html') subject = template.template.source.splitlines()[1] This works, but I dislike this solution. Is there an easier and more readable way to do this? More generally, can I define a variable in Django template and then extract it in the application? Something like template.get_variable("email_subject")? -
django-cors-headers does not allow a request from an allowed origin
The problem that I am facing is that I cannot fetch an existing user from my NextJS frontend. The backend framework that I use is Django (along with the django-cors-headers package). django-cors-headers does not allow a certain HTTP request, while it should. My next.config.js contains a rewrite, so that I can access my backend. async redirects() { return [ { source: '/api/:path*', destination: 'http://localhost:8000/:path*/', permanent: true, }, ] }, And my django-cors-headers settings look like this: # CORS CSRF_TRUSTED_ORIGINS = [ 'http://localhost:3000', ] CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', 'http://localhost:8000', 'http://127.0.0.1:3000', 'http://127.0.0.1:8000', ] CORS_ALLOW_ALL_ORIGINS = True The request that fails attempts to fetch a user with an ID of 1. This user exists and therefore, this request should succeed. fetch(`/api/users/${String(userId)}/`, { mode: 'cors', credentials: 'include', headers: { 'Content-Type': 'application/json', }, }) However, the only thing that I get back from the request is an error message about CORS. Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/users/1. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 301. It looks like my django-cors-headers setup is wrong. But I am allowed to obtain my JWT tokens. The following request succeeds. fetch('/api/token', { method: 'POST', mode: 'cors', headers: { 'Content-Type': 'application/json', }, … -
Why the data is not being saved in another model?
class AdvancePaymentCreateSerializer(serializers.ModelSerializer): PAYMENT_MODE = ( ("cash", "Cash"), ("cheque", "Cheque"), ("upi", "UPI"), ("imps", "IMPS"), ("neft", "NEFT"), ("rtgs", "RTGS"), ("demand_draft", "Demand Draft"), ) STATUS = ( ("pending", "Pending"), ("hold", "Hold"), ("completed", "Completed"), ("canceled", "Canceled"), ) center = serializers.PrimaryKeyRelatedField(queryset=center_models.Centers.objects.all(), many=True) payment_date = serializers.DateField(required=False, allow_null=True) amount = serializers.FloatField(required=False, allow_null=True) payment_mode = serializers.ChoiceField(choices=PAYMENT_MODE) cash_receipt_no = serializers.CharField(max_length=100, required=False, allow_null=True) invoice_no = serializers.CharField(max_length=100, required=False, allow_null=True) remarks = serializers.CharField(max_length=255, required=False, allow_null=True) status = serializers.ChoiceField(choices=STATUS) center_balance = serializers.FloatField(required=False, allow_null=True) payment_receipt = serializers.FileField(required=False, allow_null=True, allow_empty_file=False, use_url=True) is_active = serializers.BooleanField(default=True) class Meta: model = package_models.AdvancePayment fields = "__all__" def create(self, validated_data): center = validated_data.get("centre") payment_date = validated_data.get("payment_date") amount = validated_data.get("amount") payment_mode = validated_data.get("payment_mode") cash_receipt_no = validated_data.get("cash_receipt_no") invoice_no = validated_data.get("invoice_no") remarks = validated_data.get("remarks") status = validated_data.get("status") center_balance = validated_data.get("center_balance") payment_receipt = validated_data.get("payment_receipt") is_active = validated_data.get("is_active") obj = package_models.AdvancePayment.objects.create( center=center, payment_date=payment_date, amount=amount, payment_mode=payment_mode, cash_receipt_no=cash_receipt_no, invoice_no=invoice_no, remarks = remarks, status = status, center_balance = center_balance, payment_receipt = payment_receipt, is_active = is_active ) ledger = package_models.CollectionCenterLedger( ledger_type="credit", amount=amount, center_id=center, remarks="Advanced Amount by Center" ).save() center=center_models.Centers.objects.get_or_create(id=center).first() center.rcl_amount =float(center.rcl_amount) + float(amount) center.save() obj.center_balance =center.rcl_amount obj.save() ledger.center_rem_balance=center.rcl_amount ledger.save() obj.save() return obj This is create serializer of AdvancePayment Model. While creating object in this model i also want to save data in CollectionCenterLedger Model.But while doing this the data … -
django not finding redirect page
hey guys i have the following codes, I'm trying to redirect the GoalUpdate view to GoalPageView , but I get the following Error: Reverse for 'Goals.views.GoalPageView' with keyword arguments '{'kwargs': {'username': 'admin', 'goal_id': '1'}}' not found. 1 pattern(s) tried: ['people/(?P[^/]+)/goals/(?P<goal_id>[^/]+)/\Z'] My URLs urlpatterns = [ path('<username>/goals/',GoalsView,name='Goals'), path('<username>/goals/<goal_id>/',GoalPageView,name='Goal Page'), path('<username>/goals/<goal_id>/update/',GoalUpdate,name='Goal Update'), ] My Views: def GoalPageView(request,username,goal_id): some view code return render(request,'goal_page.html',context=context) def GoalUpdate(request,username,goal_id): Some View Code return redirect(GoalPageView,kwargs={'username':username,'goal_id':goal_id}) -
I cant create a page with an empty path in Django
centralsite/views def centralsite(request): return render(request, 'centralsite/text.html', {}) centralsite/urls from django.urls import path from . import views urlpatterns = [ path('', views.centralsite, name='centralsite'), ] urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [path(' ', include('centralsite.urls')), path('polls/', include('polls.urls')), path('admin/', admin.site.urls),] error message is: Request Method: GET Request URL: http://localhost:8000/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^$ polls/ admin/ The empty path didn’t match any of these. how do i make this empty path work? -
Django Dependent Dropdown List not displaying
my dropdown list is not getting displayed. Not only the filtered value but the whole doctor_dropdown.html. Is there some problem my Ajax? The thing that i want is that when a patient clicks on neurology dropdown list the doctors are to be displayed should be a neurologist only. HTML AND SCRIPT <div class="loginContainer" id="signupContainer"> <div class="img"> <img src="{% static 'image/booking.svg' %}"> </div> <div class="login-content"> <form method="POST" id="signupForm" data-doctor-url="{% url 'ajax_load_doctor' %}"> {% csrf_token %} <h2 class="title">Booking form</h2> {% for d in patient_details%} <div class="input-div one"> <div class="i"> <ion-icon name="person-circle"></ion-icon> </div> <div class="div"> <h5>Patient ID: PID - {{d.id}}</h5> <input type="hidden" name="PatientID" value="{{d.id}}"> </div> </div> <div class="input-div one"> <div class="i"> <ion-icon name="person"></ion-icon> </div> <div class="div"> <h5>Name: {{d.FirstName}} {{d.LastName}}</h5> </div> </div> {% endfor %} <div class="input-div one" id = "bookingField"> <div class="i"> <ion-icon name="business"></ion-icon> </div> <div class="div"> <div class="custom-select"> <select name="Department" id="Department" required> <option value="General">Select a Department</option> //department part {% for d in department_details%} <option value="{{d.id}}">{{d.name}}</option> {% endfor %} </select> </div> </div> </div> <a href="doctors" id="bookingMoreBtn" class="section-btn btn btn-default btn-blue smoothScroll">Visit our Departments</a> <div class="input-div one" id = "bookingField"> <div class="i"> <ion-icon name="medkit"></ion-icon> </div> <div class="div"> <div class=""> <select name="doctor" id="doctor" required> //doctors to be displayed here </select> </div> </div> </div> <a href="doctors" … -
Not able to save data in Database using for loop
my proposal: I want add network IP range with prefix in web UI and need to process using command ipaddress.IPv4Network(subnet).hosts()) then after IP range will crate and save all range of IP into DATABASE. I have tried deferent methods still not able to complete my requirement. some one could help about. below the code which I made. def Indexping(request): form = IpModelForm Ipform = {'form':form} if request.method=='POST': subnet = IpModelForm(request.POST) if subnet.is_valid: data= list(ipaddress.IPv4Network(subnet).hosts()) for f in data: #f = [x for x in subnet] f.save() Exception Value: Only one '/' permitted in Getting Below Error: AddressValueError at /cbv/ind/ Only one '/' permitted in Request Method: POST Request URL: http://127.0.0.1:8000/cbv/ind/ Django Version: 4.0.2 Exception Type: AddressValueError Exception Value: Only one '/' permitted in Exception Location: D:\Program Files\Python\Python39\lib\ipaddress.py, line 162, in _split_optional_netmask Python Executable: E:\Django_Projects\Portal-env\Scripts\python.exe Python Version: 3.9.10 Python Path: ['E:\Django_Projects\Portal-env\portal', 'D:\Program Files\Python\Python39\python39.zip', 'D:\Program Files\Python\Python39\DLLs', 'D:\Program Files\Python\Python39\lib', 'D:\Program Files\Python\Python39', 'E:\Django_Projects\Portal-env', 'E:\Django_Projects\Portal-env\lib\site-packages'] Server time: Sat, 19 Feb 2022 09:35:57 +0000 -
Getting SUM for each unique fields in Django Query
I have the following table relations. I want SUM of total_cost from Sales_Transaction for each party_name from the Party table. The Parties have 1:M relation with Sales and Sales has 1:M relation with Sales_Transction. I tried this query but it returns the sum for all parties: Party.objects.aggregate(sales=Sum('sales__salestransaction__total_cost')) This is similar to this simple query: SalesTransaction.objects.aggregate(sales=Sum('total_cost')) I want output like this: | Party Name | Total Purchase | ----------------------------- |Party 1 | total_cost (calculated form Sales Transaction) |Party 2 | total_cost (calculated form Sales Transaction) How can I achieve these results in Django Query? -
admin change_view is being called twice
Is there a chance to keep django admin from calling change_view twice when clicking "save and continue editing"? class SomeAdmin(admin.ModelAdmin): form = SomeAdminForm def change_view(self, request, object_id, form_url = "", extra_context = None): extra_context = extra_context or {} print("test") return super().change_view(request, object_id, form_url, extra_context = extra_context,) prints test once, when entering the change form layout, prints test twice when clicking "save and continue editing". I run a costly query inside that change_view function, that needs to be displayed in the admin change form. But I want it to only run once. Any ideas? -
AttributeError: module 'BackendApp.views.GoogleLogin' has no attribute 'as_view'
path('dj-rest-auth/google/', GoogleLogin.as_view(), name='google_login'), AttributeError: module 'BackendApp.views.GoogleLogin' has no attribute 'as_view' I have this error coming from url.py which is weird as I am following this guide https://dj-rest-auth.readthedocs.io/en/latest/installation.html on the Google section. I am pretty sure I have all the relevant settings and I copied the codes for url.py and GoogleLogin.py. Does anyone have any clues on how to deal with this issue? url.py from django.contrib import admin from django.urls import path from django.urls import include, re_path from django.conf.urls.static import static from django.conf import settings from dj_rest_auth.views import PasswordResetConfirmView, PasswordResetView from django.views.generic import TemplateView from .router import router from BackendApp.views import P2PListingModule, empty_view, GoogleLogin urlpatterns = [ path('admin/', admin.site.urls), path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('entity/', include(router.urls)), path('enduser/<str:pk>/service/', P2PListingModule.userServiceListing), path('enduser/<str:pk>/request/', P2PListingModule.userRequestListing), path('enduser/<str:pk>/swap/', P2PListingModule.userSwapListing), path('enduser/<str:pk>/premade', P2PListingModule.userPremadeListing), path('entity/p2p_listing/order/', P2PListingModule.placeOrder), path('api/p2plisting/service', P2PListingModule.ServiceListingView.as_view()), path('api/p2plisting/request', P2PListingModule.RequestListingView.as_view()), path('api/p2plisting/swap', P2PListingModule.SwapListingView.as_view()), path('api/p2plisting/premade', P2PListingModule.PremadeListingView.as_view()), re_path(r'^', include('django.contrib.auth.urls')), path('dj-rest-auth/password/reset/', PasswordResetView.as_view(), name="rest_password_reset"), path( "dj-rest-auth/password/reset/confirm/", PasswordResetConfirmView.as_view(), name="rest_password_reset_confirm", ), # path( # "/dj-rest-auth/password/reset/confirm/<uidb64>/<token>/", # PasswordResetConfirmView.as_view(), # ) path('dj-rest-auth/google/', GoogleLogin.as_view(), name='google_login'), path('accounts/', include('allauth.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # urlpatterns = [ # url(r'^admin/', include(admin.site.urls)), # ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) BackendApp.views.GoogleLogin.py from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter from allauth.socialaccount.providers.oauth2.client import OAuth2Client from dj_rest_auth.registration.views import SocialLoginView class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter #I do not know if this client id is the callback_url … -
Reverse for 'chi_tiet_hop_dong' with keyword arguments '{'so_hd': ''}' not found. 1 pattern(s) tried: ['chi_tiet_hop_dong/(?P<so_hd>[^/]+)/$']
I have the issue this error my model. class testimport(models.Model): id=models.AutoField(primary_key=True) so_hd=models.CharField( max_length=50, unique=True) ten_kh=models.CharField( max_length=500) def get_absolute_url(self): return "/chi_tiet_hop_dong/%s/" % self.so_hd class report(models.Model): id=models.AutoField(primary_key=True) so_hd=models.ForeignKey(testimport, on_delete=models.CASCADE, to_field="so_hd") If I dont use to_field="so_hd" in model report, the error doesnt appear, but I need to link it with "so_hd" in model testimport not "id primary key" in model testimport without using to_field my view: def chi_tiet_hop_dong(request,so_hd): contract=testimport.objects.filter(so_hd=so_hd) print("số hợp đồng trong def chi tiết hợp đồng",so_hd) request.session["save_so_hd"]=json.loads(json.dumps(so_hd)) lst_contract=request.session["get_contract_detail"] try: the_next = lst_contract[lst_contract.index(so_hd) + 1] print("the next",the_next) except: the_next=None try: the_prev=lst_contract[lst_contract.index(so_hd) - 1] print("the prev",the_prev) except: the_prev=None baocao=report.objects.filter(so_hd=so_hd) form=AddReportForm() return render(request, "caller_template/contract_detail.html", {"contract":contract,"the_next":the_next,"the_prev":the_prev,"baocao":baocao,"form":form}) I check to print out the_next, the_prev and so_hd, it is ok my url: path('chi_tiet_hop_dong/<str:so_hd>/', CallerViews.chi_tiet_hop_dong, name="chi_tiet_hop_dong"), Please help me -
Is there any Pythonic way to manipulate Dictionaries to follow DRY philosophy in Django?
I have got dictionary set of required queries as shown below: [{'primary_attribute__name': 'Color', 'primary_attr_values__name': 'Red'}, {'primary_attribute__name': 'Color', 'primary_attr_values__name': 'Green'}] Now I want : [{'primary_attribute__name: 'Color', { 'primary_attr_values__name': 'Red', 'primary_attr_values__name': 'Green', 'primary_attr_values__name': 'Yellow' }] Or is this good approach: primary_attribute= { "Color" : {"primary_attr_values__name" : ["red", "green", "yellow"]} } How it can be achieved? -
How to configure redis 6 in django
I know how to configure postgress on digitalocean with django. However I have a redis 6 database cluster and I've been unable to configure it with my django app. Here is the postgress configuration as is in settings.py POSTGRES_DB = os.environ.get("POSTGRES_DB") #database name POSTGRES_PASSWORD = os.environ.get("POSTGRES_PASSWORD") # database user password POSTGRES_USER = os.environ.get("POSTGRES_USER") # database username POSTGRES_HOST = os.environ.get("POSTGRES_HOST") # database host POSTGRES_PORT = os.environ.get("POSTGRES_PORT") # database port POSTGRES_READY = ( POSTGRES_DB is not None and POSTGRES_PASSWORD is not None and POSTGRES_USER is not None and POSTGRES_HOST is not None and POSTGRES_PORT is not None ) if POSTGRES_READY: DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": POSTGRES_DB, "USER": POSTGRES_USER, "PASSWORD": POSTGRES_PASSWORD, "HOST": POSTGRES_HOST, "PORT": POSTGRES_PORT, } } The environment variables in DO are below. POSTGRES_HOST ${db.HOSTNAME} POSTGRES_DB ${db.DATABASE} POSTGRES_USER ${db.USERNAME} POSTGRES_PASSWORD ${db.PASSWORD} POSTGRES_PORT ${db.PORT} My redis 6 details are username = default password = ... host = llr-redis-db-do-user-47-0.b.db.ondigitalocean.com port = 25061 How would I have this configured with the environment variables in DO then pass to the settings.py?? -
"response": "strptime() argument 1 must be str, not datetime.datetime" django datetime format problem
In Django, I have written a delete method in which I am getting some requests of data from the delete API The requested data is [ { "acerage": 1, "batch_health": null, "actual_produce": null, "actual_yield_per_acre": null, "batch_id": 2583, "batch_status": "running", "commodity_id": 6, "commodity_variety_id": 20, "current_gdd": null, "current_pdd": null, "expected_delivery_date": "2022-02-15T18:30:00.000Z", "expected_produce": null, "farm_id": "1806", "historic_gdd": null, "historic_pdd": null, "historical_yield_per_acre": null, "sop_adherence": null, "stage": "germination", "start_date": "2022-02-06T18:30:00.000Z" } ] I am deleting a row in my DB based on batch_id by using the delete method and the delete method looks like def destroy(self, request, *args, **kwargs): """ This function is used to destroy batch object """ try: instance = self.get_object() instance.batch_status = 'aborted' instance.save() solr_delta_import() except Exception as e: return Response({"response": str(e)}, status=status.HTTP_400_BAD_REQUEST) return Response({"response": "deleted successfully"}, status=status.HTTP_200_OK) and the row gets deleted when we run this function My problem here is the requested data values start_time and expected_delivery_date is coming in the string format but due to some calculations in my model file, I am converting that string to a DateTime format which looks like this the model file looks like def update_batch_median_health(self): if self.start_date and self.expected_delivery_date: if self.id: start_date = datetime.strptime(self.start_date, '%Y-%m-%dT%H:%M:%SZ') expected_delivery_date = datetime.strptime(self.expected_delivery_date, '%Y-%m-%dT%H:%M:%SZ') else: start_date = datetime.combine(self.start_date, … -
keep getting error: ModuleNotFoundError: No module named 'requests' when i have requests installed
i have python installed but i keep seeing the below error when i try to import requests. File "/x/y/z/views.py", line 3, in <module> import requests ModuleNotFoundError: No module named 'requests' here is what my code looks like: from django.shortcuts import render from django.http import HttpResponse import requests def say_hello(request): return render(requests, 'hello.html') apologies in advance if this is a dumb question, i have just started to learn django. -
Create Single Forms by Two Models in Django with Dynamic Fields
I want to create Django Forms to save transactions for the store. I want a final template similar to this. The ER Diagram for my database is also shown in the image. My Django Models are: class Party(models.Model): party_id = models.BigAutoField(primary_key=True) party_name = models.CharField(max_length=128) party_phone = models.CharField(max_length=128) party_address = models.CharField(max_length=128) def __str__(self): return self.party_name class Items(models.Model): item_no = models.BigAutoField(primary_key=True) item_type = models.BooleanField(default=True) item_name = models.CharField(max_length=128) item_qty = models.PositiveIntegerField(default=0) item_cost = models.PositiveIntegerField(default=0) def __str__(self): return self.item_name class Sales(models.Model): invoice_no = models.BigAutoField(primary_key=True) invoice_date = models.DateField(default=date.today) party = models.ForeignKey(Party, on_delete=models.CASCADE) def __str__(self): return str(self.invoice_no) class SalesTransaction(models.Model): sales = models.ForeignKey(Sales, on_delete=models.CASCADE) items = models.ForeignKey(Items, on_delete=models.CASCADE) purchase_qty = models.PositiveIntegerField(default=0) total_cost = models.PositiveIntegerField(default=0) def __str__(self): return self.item_name I can achieve this with AJAX but I don't think it is the best solution because lots of validations have to be made with hardcoding. How can I create Django Form to save data in that multiple tables in a single Save Click? -
The login function in Django not working properly
views.py def login_view(request): form = AuthenticationForm() if request.method == 'POST': form = AuthenticationForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request,user) messages.info(request,'登入成功!') return redirect('index') else: messages.error(request,'帳戶無效或密碼錯誤! 請重試!') else: messages.error(request,'帳戶無效或密碼錯誤! 請重試!') context = {'form':form} return render(request,'customer/login.html',context) login.html <form method="POST" action="" style="position:absolute;top:300px;left:125px;"> {% csrf_token %} {{ form.username|as_crispy_field }}<br> {{ form.password|as_crispy_field }}<br> <button class="btn btn-primary" type="submit">登入</button> </form> For the login function in Django, I am trying to use the username and password based on the User model in django.contrib.auth.models to login into the account. However, even though I am using my superuser status to login and the error message appears showing that invalid username or password. May I ask is AuthenticationForm following the User model information to authenticate the user or anything I am missing? -
The Django admin site
I start the development server and explore it. When I open the Web browser and go to “/admin/” on my local domain, http://127.0.0.1:8000/admin/.I face this screen: enter image description here -
Django: Query .all() not hitting the database
THe django docs says: Returns a copy of the current QuerySet (or QuerySet subclass). This can be useful in situations where you might want to pass in either a model manager or a QuerySet and do further filtering on the result. After calling all() on either object, you’ll definitely have a QuerySet to work with. When a QuerySet is evaluated, it typically caches its results. If the data in the database might have changed since a QuerySet was evaluated, you can get updated results for the same query by calling all() on a previously evaluated QuerySet. I am using Django-Debug-Toolbar to optimize a query. If I have code like this (returning an empty list to ensure .all() is hitting the DB at this point in time: def get_querysets(): foo_list = Foo.objects.filter(...).all() bar_list = Bar.objects.filter(...).all() caz_list = Caz.objects.filter(...).all() return [] then Django debug toolbar won't register those queries, i.e. DB was not querried. However if I change it to: def get_querysets(): foo_list = Foo.objects.filter(...).all() bar_list = Bar.objects.filter(...).all() caz_list = Caz.objects.filter(...).all() print(foo_list) print(bar_list) print(caz_list) return [] Now in the toolbar I can see the queries. I know querysets are lazy, but the whole point of .all() is to make it hit the … -
Not viewing file in flutter
I have converted my Django website into flutter app. in that website, view file link is there. but in APK file, it is not viewing when I click on it. How to solve this problem. Please tell. -
created virtual environment , but cant access it
it shows created virtual environment. But it is not redirect to virtual environment . after I upgraded the pip no changes where appear . please help me to get that. enter image description here -
Django regex not working when adding other branches to url
I am a complete beginner in Django, and I have encountered a problem while trying to set up a url for each "room". Here is the code: from django.conf.urls import url from . import views urlpatterns = [ url(r'^home/$', views.home, name='home'), url(r'^room/<str:pk>/$', views.room, name='room'), ] Everything was working perfectly, until I add /<str:pk>/$. I have also add this code in the views.py section: def room(request,pk): return render(request, 'base/room.html') However I still get an error when loading the website. Image of the error message Does someone know how to make it work?