Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
GitHub repository not found during pipenv install
Here in the picture you can see what happened Actually I received the Djoango project from my developer with a virtual environment (pipenv) And when I try to install with his given instructions Like Pipenv install then I got the error GitHub repository not found. during installing dependencies. And a few days ago he solved it by accessing my Mac with anydesk and solved easily like the same steps. And when I try to do same in my other Mac Again after installing some dependencies, it has given me the error GitHub repository not found. Can Anyone tell me what's the real problem? What should I do? -
'JpegImageFile' object has no attribute '_committed' Django ,Pillow
I wanted to take an online image modify it with pillow and returns that modified file on request using Django. I uploaded an image on github and use requests library to get that file. then i added some texts upon it using pillow and returns that file. I tried this import requests from PIL import Image from PIL import ImageFont from PIL import ImageDraw from io import BytesIO def send(request): url='https://github.com/AJITH-klepsydra/images/blob/master/aa.jpg?raw=true' image=requests.get(url).content img = Image.open(BytesIO(image)) font = ImageFont.truetype("arial.ttf", 15) draw = ImageDraw.Draw(img) draw.text((300, 200),"Hello World !",(255,255,255),font=font) return HttpResponse(img, content_type="image/png") but on execution I am getting an error 'JpegImageFile' object has no attribute '_committed' -
How to iterate models.objects.all() in django template when html tags classes are different
models.py class Article(models.Model): title = models.CharField('Title', max_length = 200) text = models.TextField('Descriptiom') pub_date = models.DateTimeField(default=datetime.now(), editable=True) image = models.ImageField(upload_to='images', blank=True) views.py def home(request): articles = Article.objects.all().order_by("-pub_date")[:10] return render(request, 'home.html', {'articles': articles} home.html {% load static %} <hr class="line2"> <a class="other_articles">Другие статьи</a> {% for art in articles %} <rect class="rectangle2_1"> <img src="{{ art.img.url }}" id="rect_img"> <a id="rect_date">{{ art.pub_date }}</a> <p href="#" id="rect_title">{{ art.title }}</p> </rect> <rect class="rectangle2_2"> <img src="{{ art.img.url }}" id="rect_img"> <a id="rect_date">{{ art.pub_date }}</a> <p href="#" id="rect_title">{{ art.title }}</p> </rect> <rect class="rectangle2_3"> <img src="{{ art.img.url }}" id="rect_img"> <a id="rect_date">{{ art.pub_date }}</a> <p href="#" id="rect_title">{{ art.title }}</p> </rect> {% endfor %} Cant iterate through my queryset "articles" in django template, because html classes are different. I know the method: {% for art in articles %} <rect....>art.title</rect> {% endfor %} but it doesn't work for current situation -
DJANGO + SAML2 + CSRF
I have to introduce SAML2 authentication in my Django Project. My base app use CSRF Token that is provided by @ensure_csrf_cookie decorator in the main page. For implementing SAML, I've added a new "login" button on main page (the one that set se csrf token cookie). The button send the SAML request to IDP. When I return from IDP to a landing page (a view in saml2 sub-app that reads the response) I got a 403 Forbidden error about CSRF Token. I'm using OneLogin python Library (python3-saml). https://github.com/onelogin/python3-saml The landing page is the one that ends with: ?acs What I want to know is if its a problem of my landing page or the IDP Response has to be binded with csrf token in some way. Thanks. -
Extracting users from manytomany field from model Django
I want to extract users which are followed by specific user. I have two models here class User(AbstractUser): pass class Follower(models.Model): user = models.ForeignKey(User,null=True, on_delete=models.CASCADE, related_name="follow") following = models.ManyToManyField(User, null=True, blank=True) How to do achieve this in views.py? -
Filtering and Pagination with Django Class Based Views
Looking to add pagination to my view that uses django-filter - to my surprise I found no documentation regarding pagination (which seems should be super common) in this otherwise well-documented package. I did however find several questions on this topic but none have had any clear solutions and even less addressed class-based views. Pagination and django-filter Django Filter with Pagination django-filter use paginations I am following this guide closely but currently stuck (error messages below) https://www.caktusgroup.com/blog/2018/10/18/filtering-and-pagination-django/ urls.py path('trade/', TradeFilteredListView.as_view(), name="trade-list"), filters.py def associated_portfolios(request): associated_portfolios = Portfolio.objects.filter(user=request.user) return associated_portfolios.all() class TradeFilter(django_filters.FilterSet): associated_portfolios = django_filters.ModelMultipleChoiceFilter(queryset=associated_portfolios) date_range = django_filters.DateFromToRangeFilter(label='Date Range', field_name='last_entry', widget=RangeWidget(attrs={'type': 'date'})) class Meta: model = Trade fields = ['status', 'type', 'asset', 'symbol', 'broker', 'patterns', 'associated_portfolios'] views.py class FilteredListView(ListView): filterset_class = None def get_queryset(self): # Get the queryset however you usually would. For example: queryset = super().get_queryset() # Then use the query parameters and the queryset to # instantiate a filterset and save it as an attribute # on the view instance for later. self.filterset = self.filterset_class(self.request.GET, queryset=queryset) # Return the filtered queryset return self.filterset.qs.distinct() #.filter(user=self.request.user).order_by('last_entry') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # Pass the filterset to the template - it provides the form. context['filterset'] = self.filterset_class return context # Attempt @ … -
i am unable to save content of a form in database via Django
hello everyone i am trying to save a form in my database my models.py class customer(models.Model): customerid = models.CharField(default=str(uuid.uuid1()), max_length=500, primary_key=True) customername=models.CharField(max_length=1000,) my forms.py from .models import customer class createcustomerform(ModelForm): class Meta: model=customer fields=['customername'] my views.py def createcustomer(request): if request.method=='GET': return render (request,'marketing/createcustomer.html',{'form':createcustomerform()}) else: try: form=createcustomerform(request.POST) newcreatecustomer=form.save(commit=False) newcreatecustomer.user=request.user newcreatecustomer.save() return redirect('createcustomer') except ValueError: return render(request,'marketing/createcustomer.html',{'form':createcustomerform(),'error':'Check for Invalid Data. Try Again.'}) my html is <form method="POST"> {% csrf_token %} <div id="customernamename"> <span>Company Name</span> <input type="text" id="customername" placeholder="Enter Company's Full name"> </div> </form> When i am clicking save button its redirecting me again to createcustomer but not saving data in my database. kindly help what is wrong or what am i missing ? Its saving the customer by admin area not by html page. -
Django doesn't see css in chrome
Django 3.0 Python 3.8 ubuntu /venv I have default settings.py STATIC_URL = '/static/' and the base.html like this <link href="{% static 'css/base.css'%}" rel="stylesheet" type = "text/css"> path to css file like this myapp/static/css/base.css I used to always do this and it worked. but in this project for some reason does not see chrome / checked in firefox, it works there. -
How to get data for calculated fields in new model django
Im a newbie in Django. I would like to know how can I fill data for calculated fields in a new model. Please help!!! I have 3 models: class StockBalanceSheet(models.Model): finance_year = models.CharField('Finance Year', max_length=90, blank=True, null=True) total_short_and_long_term_assets = models.FloatField('Total Assets', blank=True, null=True, default=0) class StockIncomeStatement(models.Model): finance_year = models.CharField('Finance Year', max_length=90, blank=True, null=True) net_profit_after_tax_parent_company = models.FloatField('Net Profit', blank=True, null=True, default=0) class StockFinanceIndexes(models.Model): finance_year = models.CharField('Finance Year', max_length=90, blank=True, null=True) stock_balance_sheet = models.ForeignKey(StockBalanceSheet, on_delete=models.CASCADE) stock_income_statement = models.ForeignKey(StockIncomeStatement, on_delete=models.CASCADE) roa = models.FloatField('ROA (%)', blank=True, null=True, default=0) @property def get_roa(self): return (self.stock_income_statement.net_profit_after_tax_parent_company / self.stock_balance_sheet.total_short_and_long_term_assets) def save(self, *args, **kwargs): self.roa = self.get_roa super(StockFinanceIndexes, self).save(*args, **kwargs) The data for StockBalanceSheet: 2019 ------ 100 2018 ------ 90 2017 ------ 80 The data for StockIncomeStatement: 2019 ------ 200 2018 ------ 190 2017 ------ 180 Im expecting the data for StockFinanceIndexes based on 2 models: StockBalanceSheet and StockIncomeStatement as the following: 2019 ------ 200/100 = 2 2018 ------ 190/90 = 2.11 2017 ------ 180/80 = 2.25 Thank you a lot!!! -
How to aggregate if the
In django template I could access the price with {% for x in done %} and then access the the product, which is a foreign key to a table about products. So I access the price of the product like this {{x.productt.omzet}}. My question is: How can I sum them up? In views.py I successfully used the aggregate function to sum values from a child table; however, in this case I need to aggregate values from a grand child table. I failed to do that in a for loop at views.py. def factuur(request, id): factuur = Factuur.objects.get(id=id) leerling = Leerling.objects.get(name=factuur.leerling) jezelf = Leerling.objects.get(id=2) paid = BankTransactions.objects.filter(actor=factuur.leerling) total_paid = paid.aggregate(Sum('amount')) done = Product.objects.filter(leerling=factuur.leerling) total_done = done.aggregate(Sum('productt')) if leerling.status == 4: bedrag1 = "done - paid = factuur" elif leerling.status == 3: bedrag1 = "factuur is any" else: bedrag1 = "factuur is niet van toepassing" notice = bedrag1 context = {'factuur': factuur, 'leerling': leerling, 'jezelf': jezelf, 'paid': paid, 'done': done, 'total_paid': total_paid, 'total_done': total_done, 'notice': notice, } return render(request, 'rozendale/factuur.html', context) template: <div class="row"> <div class="col-lg-6"> <table> <tr> <th>Datum</th> <th>Service</th> <th>Bedrag</th> </tr> {% for x in done %} <tr> <td> <a href="/item/{{x.id}}">{{x.date|date:"SHORT_DATE_FORMAT"}}</a> </td> <td> <a href="/product/{{x.productt.id}}">{{x.productt.name}}</a> </td> <td> {{x.productt.omzet}} </td> </tr> {% … -
Automate my task of creating a virtualenv and django
Recently I tried to automate few of my tasks which I perform on daily basis. The task are : go to a specific folder create a virtual environment in that folder go inside the virtual environment folder and then activate the virtual environment install django using pip command I am using subprocess module in python and for now I am able to achieve till step 2 Here is the code : py_sample.py import os import subprocess cwd = os.getcwd() change_dir = os.chdir(cwd) # to create a virtual env virtualenv = input('Enter the name of virtual env : ') #run the python virtualenv command p1 = subprocess.run('python -m virtualenv {}'.format(virtualenv),shell=True) virtualenv = os.path.join(os.getcwd(), virtualenv) #go inside the virtual env folder os.chdir(virtualenv) #activate the virtual environment p2 = subprocess.run(r'.\Scripts\activate.bat',shell=True) cmd C:\Users\swaru\Downloads>python py_sample.py Enter the name of virtual env : django_env created virtual environment CPython3.8.2.final.0-32 in 1423ms creator CPython3Windows(dest=C:\Users\swaru\Downloads\django_env, clear=False, global=False) seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=C:\Users\swaru\AppData\Local\pypa\virtualenv) added seed packages: pip==20.1.1, setuptools==49.2.1, wheel==0.34.2 activators BashActivator,BatchActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator C:\Users\swaru\Downloads>dir/b django_env You can see the virtualenv is created but I am unable to activate the virtualenv. What I am missing here can anyone guide me how to proceed. -
Django error OperationalError, migrations doesnt helped
In my localhost I am getting Django OperationalError and in all stackoverflow questions everybody is talking about python manage.py makemigrations <appname> and python manage.py migrate, but I did the migrations 5 times and I am getting still the same error. Here are my models, views, template and urls file codes. HTML <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'f/ask/ask.css' %}"> <title>BareTalk</title> </head> <body> <div id="wrapper"> <form method="POST"> {% csrf_token %} {{ form }} <!-- TODO: input submit Reg() function javascript --> <input name="final" id="final" type="submit" value="Ask"> </form> </div> </body> <script src="{% static 'f/ask/ask.js' %}"></script> </html> views function view def Answer(request, pk): form = AnswerForm() if request.method == 'POST': form = AnswerForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('f')) content = {'form': form} return render(request, 'f/answer.html/', content) models class Answer(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) content = models.TextField('Body', null=True, blank=True, default='Answer') date = models.DateTimeField(default=timezone.now) def __str__(self): return self.content class Meta: verbose_name_plural = 'Answers' verbose_name = 'Answer' urls file urlpatterns urlpatterns = [ # path('', QuestionListView.as_view(), name='f'), path('', index, name='f'), path('<hex:pk>/update/', QuestionUpdateView.as_view(), name='question-update'), path('<hex:pk>/delete/', QuestionDeleteView.as_view(), name='question-delete'), path('new/', QuestionCreateView.as_view(), name='question-create'), path('<hex:pk>/', QuestionDetailView.as_view(), name='current'), path('<hex:pk>/answer', Answer, name='answer') ] and the Django … -
How to get complete contact form information in Django?
This is my code: setting.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'my email@gmail.com' EMAIL_HOST_PASSWORD = 'myemail password' EMAIL_PORT = 587 EMAIL_USE_TLS = True forms.py class ContactForm(forms.Form): name = forms.CharField(max_length=100) email = forms.EmailField() message = forms.CharField(widget=forms.Textarea, required=True) views.py def contact(request): form = ContactForm if request.method == 'POST': form = ContactForm(data=request.POST) if form.is_valid(): sender_name= form.cleaned_data['name'] sender_email= form.cleaned_data['email'] message = "{0} has sent you a new message:\n\n{1}".format(sender_name, form.cleaned_data['message']) try: send_mail('New Enquiry', message, sender_email, ['my email@gmail.com']) except BadHeaderError: return HttpResponse('Invalid header found.') messages.success(request, "Your message has ben sent. Thank you for your interest.") return render(request, 'contact.html', {'form': form}) But the sender's email is not displayed inside the email , I want the sender's email to be both at the (from:) and in the text of the message, Thanks for your help image contact test -
RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it
I am trying to run pytest and am getting this error: RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. I have the following test in test_models.py that checks if the uuid has been added to the User (it is on autoadd): import pytest from backendapps.core.models import User pytestmark = pytest.mark.django_db class TestUserModel(): user = User.objects.create() assert user.uuid is not None I also have a fixtures file called conftest.py at the root level. import pytest from backendapps.core.models import Org, User @pytest.fixture(autouse=True) def enable_db_access(db): pass I then also have this pytest.ini also at the root level: [pytest] testpaths = backendapps addopts = --ds=config.settings.local --reuse-db --create-db python_files = tests.py test_*.py *_tests.py``` My test database is set to: 'TEST': { 'NAME': 'project_test_db', }, Going through other posts, here are the debug steps I have taken: add the pytestmark = pytest.mark.django_db line - I have this Check the db permissions - my user has superuser permissions Check for migration errors on your db - I migrated all my migrations to zero and reran them to check if I had any manual settings when I migrated and it was all fine. Any thoughts on what to … -
Cannot get the result of celery group with AsyncResult
I am using django cache to store the id of the celery group. Then I need to retrieve it from cache and get the result of group. cel_group = celery_group(tasks) //tasks is list of some celery tasks to be executed res = cel_group() children = [task.id for task in res.children] cache.set('some_key', res.id) return Response({'task_id': res.id,'children': children,'status': 'PENDING'}) So, here it stores the id of res. However, when I try to get the task from cached task id, it do not return the children. task_id_cached=cache.get('some_key') task=AsynResult(task_id_cached) print task_not_parent print task_not_parent.children >> 5e6fbfa3-691c-4e8f-b911-27a05ea122d3 >> None Who knows why ? -
Determine model instance from file URL
Given the URL in the request is for a known static file, how can I determine which model instance references that file? If I have several different Django model each with an ImageField, those fields each know how to store a relative path on the filesystem: # models.py from django.db import models class Lorem(models.Model): name = models.CharField(max_length=200) secret_icon = models.ImageField(upload_to='secrets') secret_banner = models.ImageField(upload_to='secrets') class UserProfile(models.Model): user = models.ForeignKey(User) secret_image = models.ImageField(upload_to='secrets') Templates can then render those images, using (for example) the instance.secret_banner.url attribute. When a request comes in for that same URL, I want to handle the request in a view: # urls.py from django.urls import path from .views import StaticImageView urlpatterns = [ ..., path(settings.MEDIA_URL + 'secrets/<path:relpath>', StaticImageView.as_view(), name='static-image'), ] So the StaticImageView.get method will be passed the relpath parameter parsed from the URL. At that point I need to do more handling based on which instance made the URL for this static image. # views.py from django.views.generic import View class StaticImageView(View): def get(self, request, relpath): instance = figure_out_the_model_instance_from_url_relpath(relpath) do_more_with(instance) What I don't know is how to write that figure_out_the_model_instance_from_url_relpath code. How can I use that path to find which model and which instance, generated that URL? -
django-allauth with facebook login error: callback uri is using http
I have deployed my app using django-allauth for facebook login. As you may know, facebook login requires a callback url that uses https. The app domain runs on https but the facebook receives the callback url with the http protocol, thus cannot login. I read through the code of allauth/socialaccount/providers/views/OAuth2Adapter and it handles the redirect_uri_protocol which by default is set to None. The method get_callback_url calls build_absolute_url which is looking for DEFAULT_HTTP_PROTOCOL in settings. Am I missing something here or I should just add DEFAULT_HTTP_PROTOCOL to the account settings? I couldn't find any documentation or similar issues on this. -
How to limit the amount of posts on a page in django blog
I built this django blog following along with a tutorial. It's all done but I need to limit the amount of posts displayed on the home view so the page just doesn't go on forever with every post ever made. views.py class HomeView(ListView): model = Post template_name = 'home.html' cats = Category.objects.all() #ordering = ['post_date'] ordering = ['-id'] def get_context_data(self, *args, **kwargs): cat_menu = Category.objects.all() context = super(HomeView, self).get_context_data(*args, **kwargs) context["cat_menu"] = cat_menu return context models.py class Post(models.Model): title = models.CharField(max_length=255) attatch_image = models.ImageField(null=True, blank=True, upload_to="images/") author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank=True, null=True) #body = models.TextField() post_date = models.DateField(auto_now_add=True) snippet = models.CharField(max_length=255) category = models.CharField(max_length=255, default='uncatigorized') likes = models.ManyToManyField(User, related_name='blog_posts') def total_likes(self): return self.likes.count() def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): #return reverse('article-detail', args=(str(self.id))) return reverse('home') home.html {% for post in object_list %} <div class="card" style="background-color: #E6FEFF;"> <div class="card-body"> <li><strong><a href="{% url 'article-detail' post.pk %}">{{ post.title }}</a></strong> - <span class="badge badge-success"><a href="{% url 'category' post.category|slugify %}" style="color:white">{{ post.category }}</a></span> <b>- {{post.author.username}}</b> - {{post.post_date}} {% if user.is_authenticated %} {% if user.id == post.author.id %} <small>✏️<a href="{% url 'update_post' post.pk %}">[Edit]</a> ❌<a href="{% url 'delete_post' post.pk %}">[Delete]</a></small><br/> {% endif %} {% endif %} <br/> {{ post.snippet … -
Django redirect with GET to url but webpage not changing in browser
"GET /login/ HTTP/1.1" 200 0 This appear in the log but page not changing to login page.. It only refresh the page after submit. I make the redirect like this return redirect("main:login") but it doesn't work. view.py view.py main/urls.py main/urls.py -
Is there a tool in django like ruby on rails scaffolding?
I`m starting to learn django development and i would like to know if like ruby on rails django comes with a scaffolding feature to generate templates files and views -
Django Logging Filter with KeyError
I have trouble with the Django logging and setting the custom filter. This is my current settings: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'filters': { 'user_filter': { '()': 'myapp.user_logging_filter.UserFilter', } }, 'formatters' : { 'standard': { 'format': '%(asctime)s [%(levelname)s] %(name)s %(current_user)s %(message)s' }, }, 'handlers': { 'default': { 'level': 'DEBUG', 'filters': ['user_filter'], 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'logs/debug.log', 'maxBytes': 1024*1024*10, # 10 MB 'backupCount': 5, 'formatter': 'standard', }, 'django': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'logs/django.log', 'maxBytes': 1024*1024*10, # 10 MB 'backupCount': 5, 'formatter': 'standard', }, }, 'loggers': { 'my': { 'handlers': ['default'], 'level': 'DEBUG', 'propagate': True }, 'django': { 'handlers': ['django'], 'level': 'DEBUG', 'propagate': True }, } } and the filter class is currently: import logging class UserFilter(logging.Filter): def filter(self, record): print('INSIDE') record.current_user = 'Marko' return True I get the error stack: --- Logging error --- Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/logging/handlers.py", line 71, in emit if self.shouldRollover(record): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/logging/handlers.py", line 187, in shouldRollover msg = "%s\n" % self.format(record) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/logging/__init__.py", line 839, in format return fmt.format(record) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/logging/__init__.py", line 579, in format s = self.formatMessage(record) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/logging/__init__.py", line 548, in formatMessage return self._style.format(record) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/logging/__init__.py", line 391, in format return self._fmt % record.__dict__ KeyError: 'current_user' Call stack: File … -
Django data not being inserted into postgresql
This codes gets the system performance reading using flask and plots it on a Django webpage using Chart which refreshes every second. I am trying to store the data into postgresql however it is not working. No data is being inserted into the table that was created in the database. views.py from django.shortcuts import render import requests from django.http import HttpResponse, request from .models import Usage def monitor(request): url = "http://127.0.0.1:5000/stats" data = requests.get(url) print(data.text) data2 = data.text return render(request, "home.html", {'alldata': data2}) def cpu_monitor(request): url = "http://127.0.0.1:5000/cpu" cpu_data = requests.get(url) cpu_data2 = cpu_data.json() for key in cpu_data2: cpu = cpu_data2['CPU'] time = cpu_data2['Time'] print(cpu) print(time) val = key return render(request, "chart.html", {'data': val}) def cp(request): url = "http://127.0.0.1:5000/cpu" cpu_data = requests.get(url) cpu_data2 = cpu_data.json() for key in cpu_data2: cpu = cpu_data2['CPU'] time = cpu_data2['Time'] print(cpu) print(time) val = [cpu] return HttpResponse(val) def mm(request): url = "http://127.0.0.1:5000/memory" memory_data = requests.get(url) memory_data2 = memory_data.json() for key in memory_data2: memory = memory_data2['Memory Percentage'] time = memory_data2['Time'] print(memory) print(time) mem = [memory] return HttpResponse(mem) def dk(request): url = "http://127.0.0.1:5000/disk" disk_data = requests.get(url) disk_data2 = disk_data.json() for key in disk_data2: disk = disk_data2['Used Partition'] time = disk_data2['Time'] print(disk) print(time) dsk = [disk] return HttpResponse(dsk) … -
how to convert this code to django requests?
/** This example uses comments and variables for clarity. These are not used in JSON. Do not include these comments or verbatim variable strings in your batch request. To batch multiple requests in one call, use the following POST HTTP request, and use the following request body syntax. POST https://www.googleapis.com/batch/reseller/v1 */ POST /batch/reseller/v1 HTTP/1.1 Authorization: auth_token Host: host Content-Type: multipart/mixed; boundary=batch_foobar Content-Length: total_content_length --batch_foobar Content-ID: %lt;item1:xxx@example.com%gt; Content-Type: application/http Content-Transfer-Encoding: binary POST /apps/reseller/v1/customers/example.com/subscriptions?customerAuthToken=token value Content-Type: application/json Content-Length: part_content_length { "kind":"subscriptions#subscription", "customerId":"example.com", "skuId" : "Google-Drive-storage-20GB", "plan" : { "planName": "FLEXIBLE" }, "seats": { "kind": "subscriptions#seats", "maximumNumberOfSeats": 10 }, "purchaseOrderId": "purchase-id-1" } --batch_foobar Content-ID: %lt;item2:xxx@example.com%gt; Content-Type: application/http Content-Transfer-Encoding: binary POST /apps/reseller/v1/customers/resold.com/subscriptions?customerAuthToken=token value Content-Type: application/json Content-Length: part_content_length { "kind":"subscriptions#subscription", "customerId":"resold.com", "skuId" : "Google-Apps-For-Business", "plan" : { "planName": "ANNUAL_MONTHLY_PAY" }, "seats": { "kind": "subscriptions#seats", "numberOfSeats": 10 } } --batch_foobar-- -
Django File Upload - form.is_valid() always false
Any help would be greatly appreciated. I am just starting with Django and ran into this issue. I have tried doing just a form as well without a model but still no luck. Here is my form html <form enctype="multipart/form-data" action="/upload" method="post"> {% csrf_token %} <input id="your_image" type="file" name="your_image"> <input class="upload-button" type="submit" value="Upload Now"> </form> Here is my views method from .forms import UploadFileForm from .models import UploadFileModel def upload(request): form = UploadFileForm() if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): print("file uploaded!") return render(request, 'pages/index.html') else: print("no luck") return render(request, 'pages/index.html') else: print("other function") return render(request, 'pages/index.html') Here is my models.py from django.db import models class UploadFileModel(models.Model): file = models.FileField(upload_to='images') def __str__(self): return self.file And here is my forms.py from django import forms from .models import UploadFileModel class UploadFileForm(forms.ModelForm): class Meta: model = UploadFileModel fields = ['file'] -
Django queryset param value auto change?
I have problem with parameter value pass into queryset This is my code recognition_date = str(recognition_date_arr[index]) print(recognition_date) data = EntryExitHistory.objects.filter(company_id=company_id, account_id=account_id, recognition_date=recognition_date) print(data.query) this is print output 2020-08-22 13:29:33 /home/ubuntu/.local/lib/python3.8/site-packages/django/db/models/fields/__init__.py:1365: RuntimeWarning: DateTimeField EntryExitHistory.recognition_date received a naive datetime (2020-08-22 13:29:33) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" SELECT `entry_exit_history`.`recognition_date`, `entry_exit_history`.`recognition_status`, `entry_exit_history`.`recognition_result`, `entry_exit_history`.`recognition_image_path`, `entry_exit_history`.`integration_code`, `entry_exit_history`.`company_id`, `entry_exit_history`.`account_id`, `entry_exit_history`.`device_id` FROM `entry_exit_history` WHERE (`entry_exit_history`.`account_id` = 2 AND `entry_exit_history`.`company_id` = 1 AND `entry_exit_history`.`recognition_date` = 2020-08-22 04:29:33) ORDER BY `entry_exit_history`.`recognition_date` ASC i don't know why value of recognition_date auto change from '2020-08-22 13:29:33' to '2020-08-22 04:29:33'