Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The number of rows after narrowing-down
This is my serializer. class MixSerializer(serializers.ModelSerializer): pub_date = serializers.DateTimeField(format="%m/%d/%Y,%I:%M:%S %p") new_order = #I want to get the number order class Meta: model = Mix fields = ('id','pub_date','detail','user','u_key') And I narrowing-down the rows like this below. def get_queryset(self): queryset = Mix.objects.all() u_key = self.request.query_params.get('u_key') if u_key is not None: queryset = queryset.filter(u_key=u_key) return queryset For example, it returns the 30 items from 100 items. so id should be (1,4,5,6,9,11,13...) like this, However I want to get the number new_order (1,2,3,4,5,6,....) I guess I should do some trick in Serializer? or any other way ? Any help appreciated. -
setAttribute also also setting the value for the following element
I'm pretty sure this one is silly but I can't seem to figure it out myself. This is a Django website containing a little bit of Javascript. In my HTML, I have a button that should send a few values to a Javascript function. The javascript function should then find and update some divs in the HTML. The strange thing is that the value assigned to the setAttribute statement is automatically also used for the following innerHTML statement (overruling whatever was configured there). HTML Button: <button class="btn btn-outline-dark" onclick="monthStats( {{simple_total_monthly_sent_volume}}, {{average_monthly_delivery_rate}}, {{average_monthly_unique_open_rate}}, {{total_monthly_unique_open_volume}}, {{average_monthly_unique_click_rate}}, {{average_monthly_rejection_rate}}, )">Month</button> Javascript: function monthStats (sentvolume, deliveryrate, uniqueopenrate, uniqueopenvolume, uniqueclickrate, rejectionrate ) { document.getElementById("sent").innerHTML = (sentvolume).toLocaleString("en-US"); document.getElementById("delivered").innerHTML = deliveryrate+"%"; document.getElementById("uniqueopened").innerHTML = uniqueopenrate+"%"; document.getElementById("uniqueopened").setAttribute("title", uniqueopenvolume.toString()); document.getElementById("uniqueclicked").innerHTML = uniqueclickrate+"%"; document.getElementById("rejected").innerHTML = rejectionrate+"%"; } HTML divs that should get updated: <div class="container"> <div class="row"> <div class="col"> <div id="sent" class="keymetric">{{simple_total_monthly_sent_volume|intcomma}}</div><div class="text-muted keymetricexplanation">sent volume</div> </div> <div class="col"> <div id="delivered" class="keymetric">{{average_monthly_delivery_rate}}%</div><div class="text-muted keymetricexplanation">delivery rate</div> </div> <div class="col"> <div id="uniqueopened" class="keymetric" data-bs-toggle="tooltip" data-bs-placement="top" title="{{total_monthly_unique_open_volume|intcomma}}">{{average_monthly_unique_open_rate}}%</div><div class="text-muted keymetricexplanation">unique open rate</div> </div> <div class="col"> <div id="uniqueclicked" class="keymetric">{{average_monthly_unique_click_rate}}%</div><div class="text-muted keymetricexplanation">unique click rate</div> </div> <div class="col"> <div id="rejected" class="keymetric">{{average_monthly_rejection_rate}}%</div><div class="text-muted keymetricexplanation">rejection rate</div> </div> </div> </div> Clicking on the Month button in the HTML results in the title and … -
safe tag in django template
hi i have a blog and i'm using latest ckeditor . i configed and tested my ckeditor but it does not show correctly! why {{post.body|safe}} not working ??? -
How to create messages if condition is True in django?
I am working on authentication webapp and I want to display message if user input doesn't match some conditions. It should look something like this. For example: if password has length less than 8 characters then display message 'Password should be longer than 8 characters!' My view: def signup(request): if request.method == "POST": context = {'has_error': False, 'data': request.POST, 'length_error': False, 'password_match_error': False, 'validate_email_error': False, } global password global password2 global email global username email = request.POST.get('email') username = request.POST.get('username') password = request.POST.get('password') password2 = request.POST.get('password2') if len(password) < 8: ############custom message context['length_error'] = True if password != password2: ############custom message context['password_match_error'] = True if not validate_email(email): ############custom message context['validate_email_error'] = True if not username: ############custom message context['has_error'] = True if models.CustomUser.objects.filter(email=email).exists(): messages.add_message(request, messages.ERROR, 'This email is already registered!') context['has_error'] = True return render(request, 'authentication/signup.html', context, status=409) if context['has_error']: return render(request, 'authentication/signup.html', context) body = render_to_string('authentication/email/email_body.html', { 'username': username, 'token': token, }) send_mail( "Email Confirmation", body, 'tadejtilinger@gmail.com', [email] ) return redirect('email-confirmation') return render(request, 'authentication/signup.html') My signup.html {% include "_base.html" %} {% load static %} {% block title %}Sign Up{% endblock title %} {% block content %} <link rel="stylesheet" href="{% static 'css/authentication/signup.css' %}"> <div class="container"> <form class="signup_form" method="post" action="{% url 'signup' … -
external network for django Webpage
I have a project in Django and it is running on my local machine, I got to make the setting by putting: Allowedhosts = ["*"] and python manage.py runserver 0.0.0.0:8000 This is enough so that I can access the page through another machine on the same network, but I would like to know a way to make access available through an external network, the question is, how do I do it ?? -
How to fetch with multiple query parameters Genereic API view
so I am building an API and i want to fetch based on multiple parameters. Here is the code base. The Url path: path('<str:order_id>/consumers/<int:user_id>/', SingleConsumerTradeAPIView.as_view(), name="single-consumer-trade" ), path('<str:order_id>/producers/<int:user_id>/', SingleProducerTradeAPIView.as_view(), name="single-producer-trade" ), Models.py: from django.db import models from authApi.models import User class Order(models.Model): user = models.ForeignKey(User,related_name='user',null=True, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True) class Trade(models.Model): consumer = models.ForeignKey(User,related_name='consumer',on_delete=models.CASCADE) producer = models.ForeignKey(User,related_name='producer',on_delete=models.CASCADE) order = models.ForeignKey(Order, related_name='trades',on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, max_length=255, decimal_places=2) location = models.CharField(max_length=255) energyQuantity = models.DecimalField(max_digits=10, max_length=255, decimal_places=2) startTime = models.DateField(auto_now_add=True) stopTime = models.DateField(auto_now_add=True) Serializers.py: class TradeSerializer(serializers.ModelSerializer): class Meta: model = Trade fields = ('id', 'order_id', 'startTime', 'stopTime', 'price', 'consumer_id', 'producer_id', 'location', 'energyQuantity', ) class OrderSerializer(serializers.ModelSerializer): trades = TradeSerializer(read_only=True, many= True) class Meta: model = Order fields = ('id', 'trades', 'date', ) What i tried: Views class SingleConsumerTradeAPIView(ListCreateAPIView): serializer_class=TradeSerializer queryset = Trade.objects.all() permission_classes = (permissions.IsAuthenticated,) lookup_fields = ('order_id', 'producer_id') def get_queryset(self): return self.queryset.filter(order_id=self.request.user,producer_id= self.request.user) I want to be able to fetch from the list of trades(via the trade model and serializers) using the order_id and the producer_id. -
Runtime Foreign Key vs Integerfield
I have a problem. I already have two solution for my problem, but i was wondering which of those is the faster solution. I guess that the second solution is not only more convienient- to use but also faster, but i want to be sure, so thats the reason why im asking. My problem is i want to group multiple rows together. The group won't hold any meta data. So im only interested in runtime. On the one hand i can use a Integer field and filter it later on when i need to get all entries that belong to the group. I guess runtime of O(n). The second solution and probably the more practicle way would be to create a foreign key to another model only using the pk there. Then i can use the reverse relation to find all the entries that belong to the group. -
Alert Message Not Rendering In Django
I am trying to create message before submitting the page, but i do not know why the message not rendering , can anyone help me to correct it. form.py class NameForm(forms.ModelForm): translated_names = TranslationField() class Meta: fields = "__all__" model = models.Name admin.py class NameAdmin(MasterDataBaseAdmin): form = forms.NameForm inlines = [AddressInline, RegistrationTypeInline] queryset = models.Name.objects.prefetch_related( "names", "name__id", "registrationstype") views.py class NameViewSet(viewsets.ReadOnlyModelViewSet): queryset = models.Name.objects.supported().prefetch_related("names", "registrationstype") serializer_class = serializers.NameSerializer def nametype(request): form = Form(request.POST) if form.is_valid(): return render(request, 'templates\ view2.html', form) view2.html {% extends "admin/base_site.html" %} {% load l10n %} <form action="" method="post">{% csrf_token %} <div> {% for obj in queryset %} <input type="hidden" name="{{ action_checkbox_name }}" value="{{ obj.pk|unlocalize }}" /> {% endfor %} <input type="hidden" name="post" value="yes" /> <input type="hidden" name="action" value="my_action" /> <input type="submit" value="Submit" /> </div> </form> -
Django & Migrate Error: I can't migrate my project
I was trying to run a Django project which I got from someone else. But I can't do the migration. I came from a mobile app development background. So I'm quite new to this backend thing including Django. Please have a look and help with this issue. Thank you Traceback (most recent call last): File "/Users/punreachrany/Desktop/MyProject/manage.py", line 22, in <module> main() File "/Users/punreachrany/Desktop/MyProject/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/punreachrany/opt/anaconda3/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/punreachrany/opt/anaconda3/lib/python3.9/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/Users/punreachrany/opt/anaconda3/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/punreachrany/opt/anaconda3/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/punreachrany/opt/anaconda3/lib/python3.9/site-packages/django/apps/config.py", line 228, in create import_module(entry) File "/Users/punreachrany/opt/anaconda3/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'bootstrap4' -
How to define models in django that provides custom values based on pre-selection for a field?
Given the following model that stores the user's wish list for reading books: class ReadingList(models.Model): user_id = models.ForeignKey(UserInfo, on_delete=models.DO_NOTHING, null=False, blank=False, default=None, db_column='user_id') book= models.CharField(max_length=255, blank=False) creation_time = models.DateTimeField(blank=True) class Meta: unique_together = (('user_id', book),) I want to create a model that helps in tracking the time spent in the reading the book on different days which looks something like this: class ReadingTracker(models.Model): user_id = models.ForeignKey(ReadingList, on_delete=models.DO_NOTHING, related_name='user', blank=False, db_column='user_id') book= models.ForeignKey(ReadingList, on_delete=models.DO_NOTHING, related_name='book-to-read', blank=False, db_column='book') time = models.DateTimeField(blank=True) time_spent = models.floatfield() On the client-side (corresponding to ReadingTracker) for both the fields user_id and book I see that ReadingList object (1), ReadingList object (2), ... are listed. But, this is not working as expected. What I want to achieve are the following: For user_id field I want to see the something like dummy_uid1, dummy_uid2, ... to be listed. Consider dummy_uid1 wants to read book1 and book2 whereas dummy_uid2 wants to read book1 and book3. When dummy_uid1 is selected as user_id, I want only book1 and book2 to be listed for selection. How do I define the model in django rest framework to achieve this? Any suggestions related to the above would be much appreciated and thank you in advance. -
Did you install mysqlclient? Django
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? -
Unable to serve django static files via nginx and docker
I am having issue with configuring a nginx server using docker and django. Here is my directory structure -nginx --default.conf --Dockerfile -portfolio_app (django webpapp) --main_app ---settings.py ---wsgi.py --sub_app ---views.py ---static ---media -docker-compose.yml -Dockerfile (django related) -entrypoint.sh (to start django server) Regarding django it working, but i am unable to serve the static files. I think i am not giving the path correctly. Here is Dockerfile related to django FROM python:3.8.13-slim-buster WORKDIR /app RUN pip install --upgrade pip COPY ./requirements.txt ./ RUN pip install -r requirements.txt COPY ./portfolio_app ./ COPY ./entrypoint.sh ./ ENTRYPOINT ["sh","/app/entrypoint.sh"] nginx files default.conf upstream django{ server portfolio_app:8000; } server { listen 80; location /{ proxy_pass http://django; } location /static/ { alias sub_app/static/; } } Dockerfile FROM nginx:1.19.0-alpine COPY ./default.conf /etc/nginx/conf.d/default.conf Here is docker-compose.yml file version: '3.3' services: portfolio_app: build: . container_name: portfolio_app volumes: - static_volume:/sub_app/static - media_volume:/sub_app/media ports: - "8000:8000" env_file: - .env nginx: build: ./nginx volumes: - static_volume:/sub_app/static - media_volume:/sub_app/media ports: - "80:80" depends_on: - portfolio_app volumes: media_volume: static_volume: I am not sure about the path of volumes in yml file and settings of default.conf. Here are the logs Successfully built 8459b7bb3baf Successfully tagged docker_nginx:latest Recreating b0f1b634454f_portfolio_app ... done Recreating docker_nginx_1 ... done Attaching to portfolio_app, … -
How to group by in a query for the Django admin serach?
I have a model called Task. The user shall search a specific search in the django admin area. So I implement the method: def get_search_results(self, request, queryset, search_term): in class TaskAdmin(admin.ModelAdmin): I define a queryset in a complicated way. But that works. I now have a wounderful queryset resulting in a nearly perfect SQL statement. There is just one thing missing. I would love to add a GROUP BY at the end. But how? I tried several things: The starting point: [...] queryset = self.model.objects.filter(joinedQ) Django aggregation: .values.aggregate() results normally in a group by, but I can't use .values for this query because django admin does not expect a dict as result. See: Group by day in django admin? using the hidden group_by attribute of the query: queryset.query.group_by = ["product"] queryset = QuerySet(query=queryset.query, model=Task) Does not work. The resulting query has all columns in group by, not only the product column like I specified. So it does not group anything. Query to string and than manually adding the GROUP BY string_query = str(queryset.query) string_query += 'GROUP BY "main_task"."product", "main_task"."version"' queryset = Task.objects.raw(string_query) This results in the correct query what will find the correct results, but I get an exeption: AttributeError: … -
how to insert data to database without forms.py in django
This method works fine for me can some one say how to add file or images like this def insert_students(request); name = request.POST['name'] class = request.POST['class'] student = studentsmodels(name=name, class=class) student.save() return redirect('/') return render(request, "insertpage.html") -
django get latest release QuerySet
class Release(models.Model): version = models.PositiveIntegerField(default=1) class Project(models.Model): project = models.ForeignKey('projects.Project', related_name='releases', on_delete=models.SET_NULL, blank=1, null=1) def getObjects(): releases = [] for project in Project.objects.all(): if project.releases.all(): releases.append(project.releases.all().order_by('-version')[0]) return releases is it possible to get a queryset of latest releases of each project if it has release? sorry I literally have no idea how to write the queryset. -
Django : make a migration run last consistently
I have a migration 0042_db_views.py creating database views that currently depends on the last migration. I want this migration 42 to always be the last one without rewriting its dependencies every time a new migration file is generated, even if we add a new migration say 0043_my_migration.py. I have red the Django docs and a bunch of SO questions, but did not found any solution for it, there is a run_before option but not a run_after... Is there a proper and reliable way to do it ? Something that would make dependencies=* in 0042_db_views.py for example, or an option that I did not found ? My Django version is 4.0.5 # 0042_db_views.py class Migration(migrations.Migration): dependencies = [ ("networks", "0041_migration_41"), ] operations = [ CreateView( name="My_Name", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ], options={ "abstract": False, }, ) # 8 other views are created, not detailing them here ] -
Prevent concurrent logins django rest framework jwt authentication
I am using djangorestframework-simplejwt==4.4.0 in my application for User Authentication. But by default it provides multiple logins for a single user i.e. I can generate n number of tokens. What I want is to prevent multiple logins from the same account. How do I do that? Models.py class Company(models.Model): region_coices = (('East', 'East'), ('West', 'West'), ('North', 'North'), ('South', 'South')) category = (('Automotive', 'Automotive'), ('F.M.C.G.', 'F.M.C.G.'), ('Pharmaceuticals', 'Pharmaceuticals'), ('Ecommerce', 'Ecommerce'), ('Others', 'Others')) type = models.ManyToManyField(CompanyTypes) name = models.CharField(max_length=500, default=0) email = models.EmailField(max_length=50, default=0) class User(AbstractUser): is_admin = models.BooleanField(default=False) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) @property def full_name(self): return self.first_name + " " + self.last_name class EmployeeTypes(models.Model): emp_choices = (('Pool Operator', 'Pool Operator'), ('Consignor', 'Consignor'), ('Consignee', 'Consignee')) emp_type = models.CharField(max_length=500, default='Pool Operator', choices=emp_choices) class Employee(models.Model): role_choices = (('CRUD', 'CRUD'), ('View', 'View')) user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="company") name = models.CharField(max_length=500, default=0) Urls.py path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), -
Recommendations on setting up models for Django social media app
I'm working on a personal social media project. Every user has a profile. --Profile model-- from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') background_image = models.ImageField(upload_to='profile_background_pics', blank=True, null=True,) bio = models.CharField(max_length=200, help_text="200 characters or less") In the profile, I want to have the option for the user to list all the tech stacks (programming languages and frameworks) that they work with and their level for each. Example pseudocode..: @testuser - Tech Stacks model - { Programming Languages: [Python (Intermediate), Java (Noob)], Frontend: [HTML (Intermediate), CSS (Intermediate), JS (Intermediate)], Frameworks: [Django (Getting there..)], Devops: [AWS (Noob), Heroku (Noob)], and so on... So each profile (since profile has OneToOne with contrib.auth.user) will have a tech stack model. The tech stack model will have multiple categories (languages, frameworks, etc). Each category has multiple objects. And each object will have user's level of proficiency. So if I query user.tech_stacks then it should return something like above. And user.tech_stacks.programming_languages should return [Python (Intermediate), Java (Noob)], I should also be able to query all the users that are Python (Intermediate) and Python (Advanced) Thanks for your help.. not really sure where to … -
How to call model method from serializer
I have method inside model: def has_midterm_contracts(self): """ Returns True if midterm contract has uploaded :rtype: boolean """ return MidtermContractFile.objects.filter( reservation_id=self.pk ).exclude( Q(attachment__isnull=True) | Q(attachment__exact='') ).exists() and how can I call it from serializer? I tried with needs_mid_term_contract_upload = serializers.SerializerMethodField() def get_needs_mid_term_contract_upload(self, record): if not record.has_midterm_contracts(): return False else: return True It gives me error AttributeError: 'dict' object has no attribute 'has_midterm_contracts' But, when I use if not record['has_midterm_contracts()']: it gives me other error KeyError: 'has_midterm_contracts()' Is there other way to try? -
WARNING:django.request:Not Found: /static/pygiustizia/js/common.js
I have set STATIC_ROOT and STATIC_URL in settings.py in my django webapp. settings.py import os STATIC_URL = 'static/' STATIC_ROOT = '/var/www/html/elastic_queries/python/djangosite/giustiziasite/pygiustizia/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "pygiustizia/static"), ) When I run one test I get these warnings messages Found 1 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). nel costruttore model Users WARNING:django.request:Not Found: /static/pygiustizia/bootstrap-msg/examples/vendors/font-awesome-4.7.0/css/font-awesome.min.css WARNING:django.request:Not Found: /static/pygiustizia/bootstrap-msg/dist/css/bootstrap-msg.css WARNING:django.request:Not Found: /static/pygiustizia/js/common.js WARNING:django.request:Not Found: /static/pygiustizia/bootstrap-msg/dist/js/bootstrap-msg.js WARNING:django.request:Not Found: /static/pygiustizia/js/common.js If I insert url "/static/pygiustizia/js/common.js" with success I obtain common.js file displayed in browser. My test is made with selenium for python and web app is written with django framework. I don't understand how solve these warnings messages. -
How validate date in inlines in django admin?
How validate and work with cleaned data in inlines? my models: class ModelA(model.Model): name = models.CharField(max_length=20) class ModelB(model.Model): name = models.CharField(max_length=20) model_a = models.ForeignKey(ModelA, on_delete=models.CASCADE) my admin: @admin.register(ModelA) class ModelAAdmin(admin.ModelAdmin): inlines = [ModelBInLine,] class ModelBInLine(StackedInline): model = ModelB formset = ModelBForm can_delete = True class ModelBForm(BaseInlineFormSet): def __init__(self, *args, **kwargs): super(ModelBForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super(ModelBForm, self).clean() #there cleaned_data is None for form in self.forms: form.instance.name = new_name #it's doesn't work return self.cleaned_data I need rewrite any fields in inlines model and make some validation logic. But, if I rewrite field, it's doesn't work. -
How to make my background image full screen?
I'm doing a project in python django and trying to make my background full screen. The html code: <div class="container-login100" style="background-image: url('{% static "webmonitor/images/bg-01.jpg" %}') ;" > The css code: .container-login100 { width: 100%; min-height: 100vh; display: -webkit-box; display: -webkit-flex; display: -moz-box; display: -ms-flexbox; display: flex; flex-wrap: wrap; justify-content: center; align-items: center; padding: 15px; background-repeat: no-repeat; background-position: center; background-size: cover; height: 100%; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; } It currently looks like this: -
Django + Graphene + DjangoModelFormMutation : dissociating create and update
I am using a DjangoModelFormMutation from Graphene-python to expose a generic mutation for a model, like so : from graphene import Field from graphene_django.forms.mutation import DjangoModelFormMutation from django.db import models class Pet(models.Model): name = models.CharField() legs = models.PositiveIntegerField() class PetForm(forms.ModelForm): class Meta: model = Pet fields = ('name', 'legs') # This will get returned when the mutation completes successfully class PetType(DjangoObjectType): class Meta: model = Pet class PetMutation(DjangoModelFormMutation): pet = Field(PetType) class Meta: form_class = PetForm Then in my schema file, I register the mutation like this : create_pet = mutations.PetMutation.Field() update_pet = mutations.PetMutation.Field() This works, but there are two desired behaviors I can't achieve this way : Have two different mutations : one for create that can only create and not update, and one for update that can only update, and not create. Have the update mutation work partially as well , i.e only updating the client-provided fields. How can I achieve the desired behavior ? -
Transfer balance from one account to other using raw code
I am making a single page website where in a table username,balance are provided,and there is a from field that takes id and balance and transfer it to other accounts,but I am facing problems with transfering amount, heres my code, models.py, class Account(models.Model): username = models.CharField(max_length=30) balance = models.IntegerField() freeze_type = models.BooleanField(default=False) hold = models.BooleanField(default=False) def __str__(self): return self.username views.py, def transfer(request): transfer_id = int(request.GET.get('Account_id')) transfer_amount = int(request.Get.get('amount')) balance_1 = Account.objects.filter(id=id) balance_2 = Account.objects.filter(transfer_id) balance_1 = balance_1.balance - balance_2.balance balance_1.save() accounts = Account.objects.all() return render(request,'home.html',{'accounts':accounts}) and my froms code from html page, <form action="{% url 'transfer' %}"> <label for="Account_id">Account Id</label><br> <input type="text" id="Account_id" name="Account_id" ><br> <label for="Transaction_amount">Transaction Amount</label><br> <input type="text" id="Transaction_amount" name="amount" ><br> <input type="submit" class="button button4" value="Submit"> </form> I have also added a screenshot of my index page for better understanding,Home page when I run this code I got the error 'WSGIRequest' object has no attribute 'Get' so my question is that why is this error and is my views.py code is right? or to code for transferring balance -
My django project is missing a lot of defaults and installed packages are not working
When I make my django app there is typically a default sqlite3 that comes with it but for some reason it does not show up so I created a database in the MySQL workbench and then in my settings.py I made sure to add the relevant info. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'nameofDB', 'USER': 'root', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '3306', } } In my virtual environment 'env' after activating it I made sure to install everything django, django-admin, pip. The name of my project is 'studybud' and the directory is: C:\Users\User\Desktop\studybud After making my project, I worked on it for a little and checked how the html was rendered so it was activted and I ran the server but after I left it alone for a while my powershell froze so i simply exited out of everything. Not sure if this affects my current problem. I tried opening my project again but now I get this error: in my virtual environment i did make sure to install mysqlclient before creating the mysql database but as you see its installed in a completely different directory which is the global one. although i would have thought the python …