Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Replacing templates in [os.path.join(BASE_DIR, 'templates')]
Since I don't have a Template folder with all my HTML, I cant use 'template in 'DIRS': [os.path.join(BASE_DIR, 'templates')], I place all my HTML directly in the site folder. MySite ├── MySite │ └── settings.py <--`'DIRS': [os.path.join(BASE_DIR, 'templates')],` └── index.html How can I change the 'templates' in 'DIRS': [os.path.join(BASE_DIR, 'templates')], to take the HTML files directly from my site folder? -
Error: [dpkg: error: cannot access archive '/home/uzair38/Downloads/wineqq2012-2-longene.deb': No such file or directory]
I am getting the above error message while downloading Visual Studio on Ubuntu 14.04. Any help would be appreciated :) -
Django insert getlist data
I am selecting a mark for every student and every core value then sending all data back to the database, please help me guys.. I’m completely stuck with this problem, I tried to solve it for several days. my problem is i didnt get the right value of every mark is for student and which marks is for what core value here is my views.py for desc, i in zip(request.POST.getlist('marking'), request.POST.getlist('coredescription')): coredesc = corevalues[int(desc)] coredescription = CoreValuesDescription(id=coredesc) p = marking[int(i)] print(desc, p) s = StudentBehaviorMarking(id=p) for student in request.POST.getlist('student'): students = StudentPeriodSummary(id=student) V_insert_data = StudentsCoreValuesDescription( Teacher=teacher, Core_Values=coredescription, Marking=s, Students_Enrollment_Records=students, grading_Period=coreperiod, ) V_insert_data.save() i = +1 desc = +1 return render(request, "Homepage/updatebehavior.html") and here is my html <form method="post" id="DogForm" action="/studentbehavior/" class="myform" style="width: 100%" enctype="multipart/form-data">{% csrf_token %} <table class="tblcore"> <input type="hidden" value="{{teacher}}" name="teacher"> <tr> <td rowspan="2" colspan="2">Core Values</td> {% for core in corevalues %} <td colspan="8"><input type="hidden" value="{{core.id}}" name="core">{{core.Description}}</td> {% endfor %} </tr> <tr> {% for corevalues in corevaluesperiod %} <td colspan="4" style="font-size: 12px"><input type="hidden" value="{{corevalues.id}}" name="coredescription">{{corevalues.Description}}</td> {% endfor %} </tr> <tr> <td colspan="2">Student's Name</td> {% for corevalues in period %} <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" … -
Django-rest-framework read url data
urls.py from rest_framework import routers router = routers.DefaultRouter() router.register('fan/<str:name>', FanView) urlpatterns = [ path(r'', include(router.urls)), ] view.py class FanView(viewsets.ModelViewSet): queryset = Fan.objects.all() serializer_class = FanSerializer def get_queryset(self): queryset = Fan.objects.all() print(self.request.query_params.get('name', None)) return queryset Hi i am trying to send name in djnago-rest-framework url. And reading the same in my viewSet. But, i am always getting None. I don't wants to send data like fan/?name=foo Please have a look Is there any way to achive that ? -
How do I make all the container sizes same and also how to set the images in a proper way?
enter image description here How do I set a standard container size and also how do I size the images in a proper way so that the clarity of the images dont disturb and also gives a good look. The images are of different sizes so dont know what to do exactly, should I set them to a standard size? or is there any better way? <div class="album py-5 bg-light"> <div class="container"> <div class="row "> {% for job in jobs.all %} <div class="col-md-4"> <div class="card mb-4 shadow-sm"> <img class = "card-img-top" src = "{{job.image.url}}"> <div class="card-body" > <p class="card-text" >{{job.summary}}</p> <div class="d-flex justify-content-between align-items-center"> </div> </div> </div> </div> {% endfor %} </div> </div> </div> -
Django - how to get Table that is connected to User?
I have a built-in table from Django, "Users". Every user is getting stored in there. Now, I have created another table called "Questions" - Questions contains personal questions (fields) that every User on their own should answer. They are connected OneToOne: class Question(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) So far it's working. I can create a Question object and then assign it to a user. But: How can I query the fields of Question that is assigned to a user? In the end I want to have a big HTML form that contains all these questions the user can answer. I have tried following: questions = request.user.question.objects.get(user=user) context = {'questions':questions} That does not work and results in AttributeError: Manager isn't accessible via Question instances. I am stuck here and don't know how to do this. If anyone can help me, thank you. -
Django Taggit error "too many SQL variables" how can i do limit query?
Hello i have a wallpaper website. Im using taggit. I have 200k tags and have 20k wallpaper. I want use related wallpapers in view like this def detail(request,slug): wallpaper = get_object_or_404(Wallpapers, slug = slug) category = Category.objects.all() similar_posts = wallpaper.tags.similar_objects()[:20] random.shuffle(similar_posts) return render(request, "detail.html", {"wallpaper": wallpaper, "category": category, "similar_posts": similar_posts, }) and i take "too many SQL variables" error. example wallpaper tags: anime, water, rain 15k+ wallpaper have anime tag How can i limit or filter query this related wallpaper items? -
How to solve content.Keywords.key_words: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples
So I wrote My first ChoiceFIeld Model I facing Some Isuues : from django.db import models from django.conf import settings from django.utils import timezone from django.utils.translation import gettext_lazy as _ class Keywords(models.Model): POLITICS = 'politics', SPORTS = 'sports', ENTERTAINMENT = 'entertainment', FOOD = 'food', LIFESTYLE = 'lifestyle', RANDOM = 'random', TOPIC = [ (POLITICS, _('News About Politics')), (SPORTS, _('News About Sports')), (ENTERTAINMENT, _('News About Entertainment')), (FOOD, _('News About Food')), (LIFESTYLE, _('News About Lifestyle')), (RANDOM, _('Random News')), ] key_words = models.CharField(max_length=2, choices=TOPIC, default=RANDOM,) This is the code i wrote. But when I am trying to makemigrations It gives me this error?message: content.Keywords.key_words: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. What I did wrong? Thanks Good People. -
How to migrate db in django using CI/CD with Google CloudSQL?
I have a django repository setup in gitlab and I am trying to automate build and deploy on google cloud using gitlab CI/CD. The app has to be deployed on App Engine and has to use CloudSQL for dynamic data storage. Issue that I am facing is while executing migration on the db, before deploying my application. I am supposed to run ./manage.py migrate which connects to cloudSQL. I have read that we can use cloud proxy to connect to cloudSQL and migrate db. But it kind of seems like a hack. Is there a way to migrate my db via CI/CD pipeline script? Any help is appreciated. Thanks. -
flutter's dio to access django's api 403
I use flutter's dio to access django's api, I have commented out 'django.middleware.csrf.CsrfViewMiddleware' , and added @csrf_exempt to the view function, but dio still reports a 403 error when accessing. The python version I use is 3.7.5, the django version is 3.0.3, the flutter version is 1.9.1 + hotfix6, and the dio version is 3.0.8 Here is the flutter code: enter image description here Here is the django code: enter image description here Here is the error: enter image description here -
How to deploy django Web application in windows IIS using AWS instance?
I'm currently working on the application which will call services to perform backend operations and I want to deploy those API'S in AWS instance using windows IIS. Can someone explain me the steps to deploy the same? -
How to silent Django's warning for 405 Method Not Allowed
I am working with Django Rest Framework, and each time there is a request resulting in 405 Method Not Allowed, an annoying warning will be printed in the console. I wonder if I can opt to silent this warning, since it is rather not helpful in my settings. -
How to call an API with images without store image in django Python
I built an API system using django which take ID card front and back image. It will output the OCR of the two images. If my system is not do OCR properly it will call another API to do the OCR. so, i have to send those image to that API. But the problem is i do not send those images to that API without store those images in my system but i do not want to store those image. How can i do that? Here is my code class OCR_API(APIView): parser_classes = (MultiPartParser,) def post(self, request, format=None): frontImg = cv2.imdecode(np.fromstring(request.FILES['nidFrontImage'].read(), np.uint8), cv2.IMREAD_UNCHANGED) backImg = cv2.imdecode(np.fromstring(request.FILES['nidBackImage'].read(), np.uint8), cv2.IMREAD_UNCHANGED) requestRefId = request.POST.get("requestReferenceId", "") data = do_my__ocr(frontImg,backImg,requestRefId) if data['status'] == 'FAILED': write_image_file("front_img_.jpg", mainfrontImg) write_image_file("back_img_.jpg", backImg) fr = "media/images/" + "front_img_.jpg" bc = "media/images/" + "back_img_.jpg" data = call_another_api_service(fr, bc, requestRefId) return Response(data,status=200, content_type="UTF-8") #another API function def call_another_api_service(frontImg,backImg,requestRefId): url = 'http:' files = {'Image': open(frontImg, 'rb')} response = requests.post(url, files=files) print(response.text) N.B: I do not want to store those image. I want to use variable like fronimg and backimg to call the API. please help -
Forbidden (403) error when calling the callback URL in django
I am working on a django webapp. I connected the paytm payment gateway with the django app. I did everything according to the docs, and everything works. almost. I am having a problem when calling the callback URL once the payment is over. Here is the code views.py def donate(request): if request.method == "POST": form = DonateForm(request.POST) name = request.POST.get('firstName') phone = request.POST.get('phone') email = request.POST.get('email') amount = float("{0:.2f}".format(int(request.POST.get('amount')))) ord_id = OrdID() cust_id = CustID() paytm_params = { "MID" : MERCHANTID, "WEBSITE" : "WEBSTAGING", "INDUSTRY_TYPE_ID" : "Retail", "CHANNEL_ID" : "WEB", "ORDER_ID" : ord_id, "CUST_ID" : cust_id, "MOBILE_NO" : phone, "EMAIL" : email, "TXN_AMOUNT" : str(amount), "CALLBACK_URL" : "http://127.0.0.1:8000/handlerequest/", } paytm_params['CHECKSUMHASH'] = Checksum.generate_checksum(paytm_params, MERCHANTKEY) return render(request, 'paytm.html', {'paytm_params': paytm_params}) else: form = DonateForm() context = {'Donate': form} return render(request, 'donate.html', context=context) @csrf_exempt def handlerequest(request): form = request.POST response_dict = {} for i in form.keys(): response_dict[i] = form[i] if i == 'CHECKSUMHASH': checksum = form[i] verify = Checksum.verify_checksum(response_dict, MERCHANTKEY, checksum) if verify: if response_dict['RESPCODE'] == '01': print('order successful') else: print('error: ' + response_dict['RESPMSG']) return render(request, 'paymentstatus.html', {'response': response_dict}) urls.py path('donate', views.donate, name='donate'), path('handlerequest', views.handlerequest, name='handlerequest'), donate.html <form class="test_paytm" action="{% url 'donate' %}" method="post"> {% csrf_token %} <div class="row"> <div class="col"> {{ Donate.firstName|as_crispy_field … -
Django Models Create
my friends from the internet I just wanna ask how can I create a model in Django that will look like this? Table Image -
reset value of model fields to default value in djnago after some time
I was trying to make a Leave management system. there are different types of leaves like PL, SL, CL. Every user gets particular no. Of leaves every year. How do I reset it to default value every year -
Django - updating database with an excel file is causing an error when primary key already exists
Note in my model contact_email is my primary key for the Contact model I have an html page and form where users can upload an excel file to upload their contacts to the database. If contact_email has not been uploaded previously, everything works fine, and contacts are uploaded. However, if the contact_email already exists an error is thrown and contact's info is not updated, for example if in new excel file an existing contact's fav_sport has changed it will not update. Error given is IntegrityError at /upload/ duplicate key value violates unique constraint "contacts_contact_pkey" DETAIL: Key (contact_email)=(john@gmail.com) already exists. Here is the code causing the error: for index, row in df.iterrows(): created = Contact.objects.update_or_create( contact_name = row[0], fav_sport = row[1], contact_email = row[2], ) How can this code be modified to resolve this error? -
Any equivalents of isfile() or isdir() in Django Template Language?
I'm using Python 3.8.1 / django 3.0.3 I wanted to avoid showing directories in my fileList like this: {% for file in fileList %} {% if file isfile %} {{file}} {% endif %} {% endfor %} Previously, I was advised to use {% if file.media %} and it worked perfectly, but it doesn't work anymore. fileList looks like this: def index(request): fileList = os.listdir(settings.MEDIA_ROOT) context = {'fileList':fileList} return render(request, 'gallery/index.html', context) -
Why isn't CSS and Javascript recognized when executing from python?
I'm currently building a website using Django and I've noticed that whenever I execute python manage.py runserver the CSS and Javascript isn't working at all. The HTML is working perfectly but somehow the CSS and JS doesn't get recognized at all. However, when I open the HTML file, the CSS and JS works perfectly, so there is nothing wrong with the CSS and JS files. Somehow it doesn't get recognized when I run the server from python. Is there a reason for this? Here is some code: Views.py from django.shortcuts import render from django.http import HttpResponse import json from django.views.decorators.csrf import csrf_exempt from chatterbot import ChatBot # Create your views here. chatbot = ChatBot( 'Ron Obvious', trainer='chatterbot.trainers.ChatterBotCorpusTrainer' ) @csrf_exempt def get_response(request): response = {'status': None} if request.method == 'POST': data = json.loads(request.body.decode('utf-8')) message = data['message'] chat_response = chatbot.get_response(message).text response['message'] = {'text': chat_response, 'user': False, 'chat_bot': True} response['status'] = 'ok' else: response['error'] = 'no post data found' return HttpResponse( json.dumps(response), content_type="application/json" ) def Index (request): context = {'title': 'Chatbot Version 1.0'} return render(request, "AI.html", context) Settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) project_root = os.path.abspath(os.path.dirname(__file__)) STATIC_DIRS = ( os.path.join(project_root, 'static'), ) INSTALLED_APPS … -
On passing correct instance of FK django still throws error ValueError: Cannot assign "(<>,)": "" must be a " instance. django
So I am updating a model PrescriptionItemDrug, this model has a FK to drug_item = models.ForeignKey(Brand, related_name='drug_item_brand', null=True, on_delete=models.CASCADE) So now on updating the PrescriptionItemDrug prescription_item_drug = models.PrescriptionItemDrug.objects.get(id=drug_item['id']) print('Brand', type(models.Brand.objects.get(id=drug_item['what']))) ## <class 'apps.apis.models.Brand'> prescription_item_drug.drug_item = models.Brand.objects.get(id=drug_item['what']), This raises ValueError: Cannot assign "(<Brand: xyz>,)": "PrescriptionItemDrug.drug_item" must be a "Brand" instance. I've scratched my head a lot but i'm not able to identify whats happening here? Can someone please give me a workaround -
Calling management command from view with file creation
I've a management command which is called from a view via call_command and during the launch of the management command a file gets created on the filesystem. It seems it's jailed to somewhere. How do i make this creation to be located on the "real" root filesystem. And where do i find the jailed files? Django: 1.11.16 Python: 2.7 . -
how to iterate json in django template?
It should be rather obvious and easy to acomplish but for some reason my code doesn't do what I want. My goal is to itterate nested json to get the deep content. My json is created manualy from data fetched from DB and the variable is called reserved. I do pass it to template as json and also I created the simple tag to load the json. It prints only the first level (date) and when I try to print the date's content it prints nothing. What my be the reason of that ? reserved = {} for reservation in user_reservations: date = str(reservation.date) time = str(reservation.time) times = {time:[]} if not date in reserved: reserved.update({date:{"times":{}}}) for seat in reservation.seats.all(): user_seat = {seat.row:seat.number} times[time].append(user_seat) reserved[date]["times"].update(times) context = {} context["reserved"] = json.dumps(reserved) {% for k in reserved|loadjson %} <span>{{k.times}}</span> {% endfor %} -
Keys/values mapping with html select
Please, how can I map fields from excel file and json response(from api) using HTML select elements for the two fields (one for each) -
Aggragate Value django
I would like to aggregate some values from a table in django. Show how many projects I`ve got in my table Aggregate values of the column budget Subtract two values between two objects: Tobeinvoiced = Budget - Invoiced views.py def index(request): projects = Project.objects.all() project_count = Project.objects.count() return render(request, 'projects/index_table.html', {'projects': projects}) models.py class Project(models.Model): budget = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) invoiced = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) tobeinvoiced = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) part of the code from projects.html <h6 class="text-uppercase"align="center">Work in Progress</h6> <h1 class="display-4"align="center">{{ project_count }}</h1> <tbody> {% for project in projects.all %} <td>{{ project.invoiced }}</td> <td>{{ project.budget }}</td> {% endfor %} </tbody> Many Thanks -
register page couldnt register user and not even showingùùùùùùùùùùùùùùùù [closed]
view url patterns url patterns enter image description here register