Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cookies do not work after browser close on mobile
I have Vue frontend app and Django Rest Framework backend on the same domain. The app is working fine and this is the only problem. I use Session Cookie for authentication and CSRF Cookie with HTTPOnly = False from which i read a csrftoken value and add it to the X-CSRFToken header in requests to my API. On mobile devices, after closing browser without closing app window, after opening browser in persisted window cookies do not work (which is ok because i know that they should be deleted when browser is closed) , but after making get requests to the api they are not set. -
AttributeError - 'dict' object has no attribute 'split'
Using django-redis I came across the AttributeError when trying to get the cache. My full traceback can be seen here, the part which shows there're problems with django-redis is here: File "/usr/local/lib/python3.9/site-packages/django_redis/cache.py", line 87, in get value = self._get(key, default, version, client) File "/usr/local/lib/python3.9/site-packages/django_redis/cache.py", line 27, in _decorator return method(self, *args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django_redis/cache.py", line 94, in _get return self.client.get(key, default=default, version=version, client=client) File "/usr/local/lib/python3.9/site-packages/django_redis/cache.py", line 71, in client self._client = self._client_cls(self._server, self._params, self) File "/usr/local/lib/python3.9/site-packages/django_redis/client/default.py", line 41, in __init__ self._server = self._server.split(",") Exception Type: AttributeError at / Exception Value: 'dict' object has no attribute 'split' My project's config file's part which uses caching is: from environs import Env # environment variables setup env = Env() env.read_env() INSTALLED_APPS = [ ... 'debug_toolbar', 'compressor', ... ] STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', ] CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": env.dj_cache_url("CACHE_URL", default="redis://redis:6379/1"), "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } # django-debug-toolbar import socket hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS = [ip[:-1] + "1" for ip in ips] # celery CELERY_BROKER_URL = env.dj_cache_url("CACHE_URL", default="redis://redis:6379/1") CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' I build my project in Docker, so use an according URL for containerization purposes. In addition, I didn't have AttributeError until … -
asyns requests to api in django view
I have a django application and I need to return a value from one api in one view. For example: a person will enter the page, a request will be made to the api and return a value, I wonder should I make requests asynchronously? if a lot of people visit this page, here's my code: import aiohttp import asynsio asyns def get_rate(): url = 'https://api.ratesapi.io/api/latest?base=USD&symbols=GBP' async with session.get(url) as response: json_response = await response.json() return json_response def test_view(request): usd = asyncio.run(get_rate())['ratest]["USD] return render(request, '???.html', {'usd':usd}) it is correct? or no -
Failing when running celery from docker
I'm trying to get celery to work with Django and docker and the building works well but I celery won't run. Any ideas? Here is are the docker-compose logs -f errors Starting django-celery_redis_1 ... done Starting django-celery_db_1 ... done Starting django-celery_flower_1 ... done Starting django-celery_celery_beat_1 ... done Starting django-celery_celery_worker_1 ... done Starting django-celery_web_1 ... done Attaching to django-celery_db_1, django-celery_redis_1, django-celery_celery_worker_1, django-celery_flower_1, django-celery_celery_beat_1, django-celery_web_1 celery_beat_1 | standard_init_linux.go:219: exec user process caused: exec format error db_1 | 2021-03-28 18:18:15.611 UTC [1] LOG: starting PostgreSQL 12.0 on x86_64-pc-linux-musl, compiled by gcc (Alpine 8.3.0) 8.3.0, 64-bit db_1 | 2021-03-28 18:18:15.613 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2021-03-28 18:18:15.616 UTC [1] LOG: listening on IPv6 address "::", port 5432 celery_worker_1 | standard_init_linux.go:219: exec user process caused: exec format error db_1 | 2021-03-28 18:18:15.648 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" redis_1 | 1:C 28 Mar 2021 18:18:15.425 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo redis_1 | 1:C 28 Mar 2021 18:18:15.425 # Redis version=5.0.12, bits=64, commit=00000000, modified=0, pid=1, just started redis_1 | 1:C 28 Mar 2021 18:18:15.425 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf redis_1 | … -
Is it necessary to make the channel room name unique in django channels? I have a function which works fine but have some concerns. HELP NEEDED
Hey guys I have made a small feed system which uses websockets and opens at the moment someone visits the website and login, all the new feeds will be send live and is updated realtime to those people who are subscribed to a particular user. I am using django-channels for this and have a non-unique room_name as of now, so that it is accessible to every user who is logged in and visits the website. but is it a good practice to do have a non unique room_name for such a system? Does it affect the performance or becomes obsolete if large number of users visits the website at the same time? OR Should I create a new table with the current user and a manyTomanyField which contains the subscribed users? if that's the case how do I add all the users to a channel group? This is the code I have which is working fine now, async def connect(self): print('connected') user = self.scope["user"] self.user = user room_name = f'sub-feeds' self.room_name = room_name await self.accept() for now, I am checking a condition which returns True if the user is subscribed to me else it returns False. async def external_feed(self, event): … -
React / Apollo: Displaying Error of GraphQL mutation (useMutation hook)
I am having a hard time trying to figure out why I can't show the error of my mutation. I have implemented error codes in my mutation: if location_lat < 0.1 and location_lon < 0.1: return GraphQLError('E_CF_002') now on the client-side, I call the following mutation, which is called onSubmit of a form and I purposefully trigger the error. const [ createEvent, { data: createData, loading: createLoading, error: createError} ] = useMutation(CREATE_EVENT); The error code is successfully returned as seen in my network tab: {"errors": [{"message": "E_CF_002", "locations": [{"line": However, when I try to show the error in a dialogue box {createError && ( <div> <Dialog open={openDialog} onClose={handleClose}> <h3>Sorry, an error occured while creating the event.</h3> <h3>Plese try again later. {JSON.stringify(createError)} </h3> <DialogActions> <Button onClick={handleClose} color="primary"> Okay </Button> </DialogActions> </Dialog> </div> )} I only see: Sorry, an error occured while creating the event. Plese try again later. {} Can anyone help me understand why my error variable does not hold the message etc.? I first tried directly printing createError.message or createError[0].message or even createError.errors and even createError.errors[0] however later on I saw that even the entire JSON is empty by printing JSON.stringify(createError). I haven't been able to find this specific … -
How to output and save two models that are related in django CreateView
I want to showcase and save my recipes. However I have a Recipe model that has a many to many relationship with a recipelist model. my model: class IngredientList(models.Model): name = models.CharField(max_length=100) image = models.ImageField(default='ing.jpg', blank=True, null=True) recipes = models.ManyToManyField('RecipeList', through='RecipeList') def __str__(self): return self.name class Units(models.Model): name = models.CharField(max_length=20, default='') unit = models.CharField(default=None, max_length=5) def __str__(self): return self.name class RecipeList(models.Model): choice = [ ('Italian', 'It'), ('French', 'Fr'), ('Mexican', 'Mx'), ('Trinidad & Tobado', 'TT'), ] name = models.CharField(max_length=100) ingredients = models.ManyToManyField( 'IngredientList', through='ShoppingList') instructions = models.TextField(max_length=3000) serving_size = models.IntegerField() cuisine_type = models.CharField(max_length=100, choices=choice) image = models.ImageField(default='recipe.jpg', blank=True, null=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('recipe-detail', kwargs={'pk': self.pk}) class RecipeList(models.Model): ingredients = models.ForeignKey(IngredientList, on_delete=models.CASCADE) recipe = models.ForeignKey(RecipeList, on_delete=models.CASCADE) unit = models.ForeignKey( Units, on_delete=models.CASCADE, null=True, blank=True) measurement = models.FloatField(default=1) my view: class RecipeCreateView(CreateView): model = RecipeList fields = ['name', 'instructions', 'cuisine', 'serving_size', 'image'] I want to output on the view a form which has: Recipe.name Recipe.RecipeList.measurement - Recipe.RecipeList.unit - Recipe.RecipeList.ingredients Recipe.instructions ... Instead of outputing Recipe.ingredients and not being able to define the unit or measurements for each, I want to be able to save all the ingredients in one form. But i am very weak with databasing, and new to … -
My django site stopped working after a crash and the errors make no sense
I have a large django 3.1 project that was working as of my last git push last Sunday. After that push, I started working on some bash deployment scripts and had a system crash (Ubuntu) related to testing these scripts (bash is not my forte!). I rebooted the machine, and continued working. I started running some tests on the django code and low and behold the working code in my django project is broken in a very weird way. Weirdness #1 - imports not working In one of my save_model functions in the admin.py of one of my apps, I have this line, which on Sunday was working. obj2.computed_sha256 = image_processing_utils.compute_sha256(f) I got a django error message that image_processing_utils was not defined. However, there is an import statement at the top of the admin file from image_processing import image_processing_utils. I copied the import statement to the line above the obj2.computed_sha256 = image_processing_utils.compute_sha256(f) and the save_model function worked correctly. Weirdness #2 - database values incorrect I ran another admin test where a post_delete signal is called. I have these lines: @receiver(post_delete, sender=Face) def auto_delete_face_metadata(sender, instance, **kwargs): # delete the Face metadata when the Face object is deleted doc_id = instance.document.document_id doc_metadata … -
'ordering' refers to the nonexistent field, related field, or lookup 'order'
I am getting this error and couldn't resolve it since 2 hours. If anyone could help. This is my models.py models.py Error : enter image description here -
Handling a null header value
I'm passing a header value to a list endpoint to only get objects after a certain date, this works all fine until the front end pass null as the value. My code for this looks like this; updated = self.request.headers.get("Updated", None) type(updated) if updated is None or updated is "null": .... else: .... If the header value passed is Updated: null this crashes, I've tried comparing to both None and the text null but I still get the error; django.core.exceptions.ValidationError: ['“null” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] As it's falling into the else category, type(updated) prints out null in the terminal but I can't find anywhere where to compare updated to a null value, according to what I've found this should be covered by None. I could fix this on my FE but I feel like this would leave the BE open to a 500 error for no reason. -
Adding payment method and escrow to a site in Python [closed]
How do I add a payment method on a site designed in python django -
Django python problem finding h1 element and title
I am reading the book "TDD in practice" and I follow it, however, when I want to check functional tests, I get this error: ====================================================================== ERROR: test_title (__main__.NewvisitorTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\Piotr\AppData\Local\Programs\Python\Python39\pythonProject\superlists\functional_tests.py", line 19, in test_title header_text = self.browser.find_element_by_tag_name('h1').text File "C:\Users\Piotr\AppData\Local\Programs\Python\Python39\pythonProject\venv2\lib\site- packages\selenium\webdriver\remote\webdriver.py", line 530, in find_e lement_by_tag_name return self.find_element(by=By.TAG_NAME, value=name) File "C:\Users\Piotr\AppData\Local\Programs\Python\Python39\pythonProject\venv2\lib\site- packages\selenium\webdriver\remote\webdriver.py", line 976, in find_e lement return self.execute(Command.FIND_ELEMENT, { File "C:\Users\Piotr\AppData\Local\Programs\Python\Python39\pythonProject\venv2\lib\site- packages\selenium\webdriver\remote\webdriver.py", line 321, in execut e self.error_handler.check_response(response) File "C:\Users\Piotr\AppData\Local\Programs\Python\Python39\pythonProject\venv2\lib\site- packages\selenium\webdriver\remote\errorhandler.py", line 242, in che ck_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"h1"} (Session info: chrome=89.0.4389.90) ---------------------------------------------------------------------- Ran 2 tests in 11.605s FAILED (errors=1) I understand that the h1 tag is a problem, but I don't understand why it can't find it. functional_tests.py from selenium import webdriver from selenium.webdriver.common.keys import Keys import unittest class NewvisitorTest(unittest.TestCase): def setUp(self): self.browser = webdriver.Chrome() self.browser.implicitly_wait(4) def tearDown(self): self.browser.quit() def test_can_start_a_list_retrieve_it_later(self): self.browser.get('http://localhost:8000') def test_title(self): self.assertIn('', self.browser.title) header_text = self.browser.find_element_by_tag_name('h1').text self.assertIn('Listy', header_text) inputbox = self.browser.find_element_by_id('id_new_item') self.assertEqual(inputbox.get_attribute('placeholder'),'Wpisz rzecz do zrobienia') inputbox.send_keys('Kupić pawie pióra') inputbox.send_keys(Keys.ENTER) table = self.browser.find_element_by_id('id_list_table') rows = table.find_elements_by_tag_name('tr') self.assertTrue(any(row.text == '1: Kupić pawie pióra' for row in rows)) self.fail('Zakończenie testu!') if __name__ == "__main__": unittest.main() home.html <html> <head> <meta charset="UTF-8"> <title>Listy … -
AWS S3 Usage Limit : How to reduce usage?
I have nearly reached my AWS S3 usage limit for the month, after having started it just a couple of weeks ago, and I'm trying to understand why. I've never used AWS before, and I'm a newb in general. I literally have 3 jpegs in storage, nothing else. Is usage solely determined by hrs? I read that hrs are instances where the storage is made available. Right now I have the Django project hosted on Heroku with media on AWS. I am very much still in dev mode, and only need AWS when testing project on Heroku, but most of the time I'm in local env. Given that, I am confused how my usage limit could be nearly reached within a couple of weeks. Any guidance is appreciated. -
Django: ModelViewSet update() returns TypeError: update() got an unexpected keyword argument 'pk' during image upload
I want to upload an image from the user's profile page. The URL from where I am uploading the image is the Detail page. That's why it has the user ID at the end of the URL. But, when I make a PATCH request after adding the image in Postman, Django returns this error: TypeError: update() got an unexpected keyword argument 'pk' This is my URL: Since, I need to update a profile from it's detail page, the ID is present in the URL. If I remove the ID it says: {"detail": "Method \"PATCH\" not allowed."} This is my update(): def update(self, request): serializer = self.serializer_class(instance = self.request.user, data=request.data, partial=True) if serializer.is_valid(raise_exception=True): serializer.save() return Response({ 'status': status.HTTP_200_OK, 'message': 'Profile updated successfully' }, serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) So how do I upload an image as someone who updates profile picture from the profile page? Assuming that the profile page is a DETAIL or RETRIEVE view. -
Django: Offcanvas pdf preview iteration issue
Hy guys i'm setting up a page where there is a table which contains some meta data about a pdf file. Ofcourse for user friendliness i want to give the user a preview of a stored file and i'd like to do that in an off-canvas. my html file <h5>Add a document </h5> <div class="addition"> <form method="POST" action="" enctype='multipart/form-data' autocomplete="off"> {% csrf_token %} <div> <input type="text" class="form-control form-control-sm" aria-describedby="emailHelp" placeholder="name" name="name" maxlength="50" autocomplete="off"> </div> <div> <label for="myfile">Select a file:</label> <input type="file" id="myfile" name="pdf"> </div> <div> <button type="submit" class="btn btn-sm btn-primary">Submit</button> </div> </form> </div> <h4>Overview documents</h4> <div class="table-responsive"> <table class="table table-striped table-sm"> <thead> <tr> <th>#</th> <th>Name</th> <th>Descritpion</th> <th></th> <th></th> </tr> </thead> <tbody> {% for item in all_pdfs %} <tr> <td>{{ forloop.counter }}</td> <td>{{ item.name }}</td> <td><a href="{{item.pdf.url}}">{{ item.name }}</a></td> <td> <div> <button class="btn btn-primary" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasRight" aria-controls="offcanvasRight">Toggle right offcanvas</button> <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasRight" aria-labelledby="offcanvasRightLabel"> <div class="offcanvas-header"> <h5 id="offcanvasRightLabel">Offcanvas right</h5> <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button> </div> <div class="offcanvas-body"> <embed src="{{ item.pdf.url }}" type="application/pdf" height="700px" width="350"> </div> </div> </div> </td> </tr> {% endfor %} </tbody> </table> </div> This html page contains 2 sections: the actual form and below the table that represents all the records in my database models.py class … -
How to create superuser in django through gcp?
I have recently deployed my django project to gcp. The deployment went well and i am able to access the url aswell. The only thing i can't do is login into the admin panel. How can i run the manage.py commands in gcp so that i can migrate and create a superuser aswell? This is how my settings.py file looks """ Django settings for portfolio_backend project. Generated by 'django-admin startproject' using Django 1.11.29. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os from decouple import config # import django_heroku from dj_database_url import parse as dburl # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG') ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'ckeditor', 'corsheaders', 'contact', 'about', 'work', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", … -
Json values into databse with Django
how I can insert json values that Im getting from request.get("some url") into database in django? -
Dashbord url unique url generate to permit non connected user to see a specific dashboard
I, m using dash to generate a dashboard for different services / company. I would like to generate a url that permit a user (not connected) to access to his dashboard he dashboard is the same for every user except that data queries differ. I'm using dash in a django app. I really don t know how to code this. -
why does my form validation not work in django
I am trying to make it so that if the user already exists then log in the user else return error message. I read the documentation and implemented it into my own project. I get error: "The view sign_in.views.sign_in didn't return an HttpResponse object. It returned None instead." from django.shortcuts import render, redirect from .forms import SignInForm from django.contrib.auth import authenticate, login from django.contrib import messages def sign_in(request): if request.method == "POST": form = SignInForm(request.POST) else: form = SignInForm() username = request.POST.get("username") password = request.POST.get("password") user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect("boom-home") messages.success(request, f"Signed in as {user}") else: return messages.error(request, f"Failed to sign in as {user}.") context = { "form": form } return render(request, "sign_in/sign_in.html", context) NOTE: usually this error is because people do not put "return" before the "render" method but I do put return. -
Value from views.py, not getting reflected in HTML page : Django
i got a problem while passing element from views.py to html page , first i will explain about UI , i have a single html page with name . side-menu-light-tabulator.html and UIlooks something like this and when i click on show server list , it will toogle the div and show me another div with another table replacing the old one , as u can see "Document Editor" remains same in header only table changes. consider the first UI as table 1 and second UI as table2 , so i am getting the data for table 2 by performing some queries on table 1 data , table 1 works fine and when performing queries with data obtained from table 1 is also getting printed on terminal , but when i send the data through return render , it is not getting printed in table 2. So here is my code : def secondtableonDashboard(request): Server_list = "" NewList = "" afterConcat = "" conn = pyodbc.connect('Driver={SQL Server};' 'Server=ABC\SQLEXPRESS;' 'Database=WebstartUI;' 'Trusted_Connection=yes;') cursor = conn.cursor() cursor.execute("select * from CustomerServer") result = cursor.fetchall() if request.method=='POST': # ------> getting value from first table user_list = request.POST.getlist('checked_list') Server_list = listToString(user_list) +"," else: print("No Values") for listValue … -
Creating a Simple form using django. Stuck between two error, Attribute Error and Key error
This is my form code and I am getting error an Keyerror on line 8 and 9 i.e name and also email.I am also getting attribute error on line with ValidationError. from django import forms from django.core.exceptions import NON_FIELD_ERRORS, ValidationError class StudentRegistration(forms.Form): name= forms.CharField() email= forms.EmailField() def clean(self): cleaned_data = super().clean() valname= self.cleaned_data ['name'] valemail=self.cleaned_data [ 'email'] if len(valname) < 8: raise forms.ValidatonError('Name should be more than or equal to 4') if len(valemail) < 10: raise forms.ValidatonError('Abe dhang se daal') My Error: AttributeError at /regi/registration/ module 'django.forms' has no attribute 'ValidatonError' Request Method: POST Request URL: http://127.0.0.1:8000/regi/registration/ Django Version: 3.0.2 Exception Type: AttributeError Exception Value: module 'django.forms' has no attribute 'ValidatonError' Exception Location: C:\Users\pkish\OneDrive\Desktop\GS\gs41\enroll\forms.py in clean, line 11 Python Executable: C:\Users\pkish\AppData\Local\Programs\Python\Python38-32\python.exe Python Version: 3.8.1 Python Path: ['C:\Users\pkish\OneDrive\Desktop\GS\gs41', 'C:\Users\pkish\AppData\Local\Programs\Python\Python38-32\python38.zip', 'C:\Users\pkish\AppData\Local\Programs\Python\Python38-32\DLLs', 'C:\Users\pkish\AppData\Local\Programs\Python\Python38-32\lib', 'C:\Users\pkish\AppData\Local\Programs\Python\Python38-32', 'C:\Users\pkish\AppData\Local\Programs\Python\Python38-32\lib\site-packages', 'C:\Users\pkish\AppData\Local\Programs\Python\Python38-32\lib\site-packages\confusable_homoglyphs-3.2.0-py3.8.egg'] Server time: Sun, 28 Mar 2021 15:42:39 +0000 -
How use rabbitmq in django
https://github.com/wangyuhuiever/django-rabbitmq Guys need help use it code, i don't understand how use is. Pls need example code -
I am trying to implement an image upload feature on my Django project but no file is being created. What is wrong with my code?
I have a profile page with a default profile picture and a 'Change' button beside it which will trigger a modal upon being clicked. In this modal, the image upload button (for choosing the image) will appear along with a submit button. I have created a separate view for handling the image upload. I do not know why a file is not being created after upload. No error message is being given by Django. I suspect it has something to do with settings.py configuration or the action part of my modal field. views.py from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from .forms import KeyForm, Weekly_Item_Form, Daily_Item_Form, ProfileForm from .models import Key, Weekly_Item, Daily_Item, Profile def profile_view(request): profiles = Profile.objects.all() mainprofile = profiles.last() if profiles: form = ProfileForm() context = { 'page_title':"Profile", 'mainprofile':mainprofile, 'form': form } else: context = {'page_title':"Profile"} return render(request, "bujo/profile.html", context) def update_image(request, pk): mainprofile = Profile.objects.get(id=pk) form = ProfileForm(instance=mainprofile) if request.method == 'POST': form = ProfileForm(request.POST, request.FILES, instance=mainprofile) if form.is_valid(): form.save() return redirect('profile') return redirect('profile') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('profile/', app_views.profile_view, name='profile'), app_views.update_image, name='update_image'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_URL = '/media/' MEDIA_ROOT … -
Difference between queryset attribute and get_queryset() method in django?
I am learning class based views in Django. I was reading the Django documentation and read about queryset attribute and the get_queryset() method. When googled them I came across this answer. I tried to replicate the result using my code: class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): return Question.objects.order_by('-pub_date')[:2] class IndexView2(generic.ListView): template_name = 'polls/index2.html' context_object_name = 'latest_question_list2' queryset = Question.objects.all() In answer it is mentioned that when you set queryset, the queryset is created only once, when you start your server. On the other hand, the get_queryset method is called for every request. But I was able to insert questions in database and they were available in the page index2.html without restarting, I was able to change the database and changes were reflected on the page index2.html after refreshing the page. I further googled and found this link. In the DRF website, it is mentioned that queryset will get evaluated once, and those results will be cached for all subsequent requests. Can you point where I am going wrong ? What link I am missing ? -
How to compare two dates (not time) in django-python project?
Here It is my function to print the previous(oldTickets) and upcoming(newTickets) bookings. journeyDate is database attribute(column name) which is of type date and ticketDetail is model name. Here It is showing error in comparing date attributes. def booking(request): if request.user.is_authenticated: user_name = request.user.username today = date.today() oldTickets = ticketDetail.objects.all() oldTickets = ticketDetail.objects.filter(userName=user_name).filter(ticketDetail.journeyDate<today) newTickets = ticketDetail.objects.all() newTickets = ticketDetail.objects.filter(userName=user_name).filter(ticketDetail.journeyDate>today) context = {'oldticket':oldTickets, 'newticket':newticket} return render(request, 'bookticket/myBookings.html', context) else: return redirect('/login') Can anyone guide me, how to solve this error? Thank You :)