Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Catch 401 exception in django
I'm trying to catch exception via try-catch in Django for unauthorized users i.e status code of 401. I tried: try: result = Users_Details.objects.get(auth_token=auth_token) result.password = password result.save() except Users_Details.DoesNotExist as e: error = {"status": "failure", "reason": str(e)} return JsonResponse(error, status=status.HTTP_401_UNAUTHORIZED) But it's not working. what am I doing wrong here ? -
Django Jinja2 how to convert things like {% load tawkto_tags %}?
How do I make the jump with Jinja to load things like my tags at the top of the html? {% load tawkto_tags %} I am using django-jinja with Cookiecutter. Is changing to Jinja really worth the speed??? Thanks! -
form validation errors in django
Every time I'm facing field validation error for datetime field in django. Actually I didn't know how this field works. Here is my model. and also I'm using crispy forms enter image description here class Customer(TimeStampWithCreatorMixin): check_in = models.DateTimeField(_("Check In"), auto_now=False, auto_now_add=False) and here is my forms.py code class CustomerCreateForm(forms.ModelForm): class Meta: model = Customer exclude = ('updated_by',) widgets = { 'check_in': forms.TextInput(attrs={ 'class': "form-control datetimepicker-input", 'id': "check_in", 'data-toggle': "datetimepicker", 'data-target': "#check_in", 'autocomplete': 'off', }) } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Row( Column('check_in', css_class='form-group col-md-6 mb-0'), ) ....... Submit('submit', 'Add Customer') ) I'm also using https://tempusdominus.github.io/bootstrap-4/ for date and time picker. -
Enabling SSO across several domains that consume the same service based backend
The most obvious solution here will allow session based authentication which is considered a bad practice in Django shomehow. So I have worked out a simple way to play the token in a cookie and then try to read it from the cookie if it is absent in the headers (like in the case of moving between 2 different domains that consume our API). The request returns the following data in the 'Cookies' sections under 'Network' However, under 'Application' I cannot see the cookie at all This is the code I have written middleware.py class WhiteLabelSessionMiddleware(MiddlewareMixin): def process_request(self, request): request_token = request.META.get('HTTP_AUTHORIZATION') cookie_token = request.COOKIES.get(settings.WHITE_LABEL_COOKIE_NAME) if cookie_token: print(cookie_token) if cookie_token and not request_token: # must be assigned by reference request.request.META['HTTP_AUTHORIZATION'] = cookie_token def process_response(self, request, response): request_token = request.META.get('HTTP_AUTHORIZATION') cookie_token = request.COOKIES.get(settings.WHITE_LABEL_COOKIE_NAME) if not cookie_token and request_token: response.set_cookie(settings.WHITE_LABEL_COOKIE_NAME, request_token, max_age=settings.SESSION_COOKIE_AGE, expires=settings.SESSION_COOKIE_AGE, domain=settings.SESSION_COOKIE_DOMAIN, secure=settings.SESSION_COOKIE_SECURE) return response settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'session_security.middleware.SessionSecurityMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'core.middleware.WhiteLabelSessionMiddleware', 'core.middleware.TimezoneMiddleware', 'core.middleware.LastSeenMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django_otp.middleware.OTPMiddleware', 'referrals.middleware.ReferralMiddleWare', 'audit_log.middleware.UserLoggingMiddleware', 'axes.middleware.AxesMiddleware', ] WHITE_LABEL_COOKIE_NAME = 'nex_token' SESSION_COOKIE_AGE = 60 * 60 * 24 * 30 * 12 _COOKIE_EXPIRES = datetime.datetime.utcnow() + \ datetime.timedelta(seconds=SESSION_COOKIE_AGE) SESSION_COOKIE_EXPIRES = \ datetime.datetime.strftime(_COOKIE_EXPIRES, "%a, %d-%b-%Y %H:%M:%S GMT") SESSION_COOKIE_DOMAIN = '.n.exchange' … -
Database Engine for PyODBC
So django currenty only provide 4 backend database engine which is : 'django.db.backends.postgresql' 'django.db.backends.mysql' 'django.db.backends.sqlite3' 'django.db.backends.oracle' If I use MySQL, all I have to do is just fill the Engine with 'django.db.backends.mysql'. But now, because my main Database is DB2, I'm having some issues to connect it with pyodbc. A help would be appreciate. Thanks! DATABASES = { 'default': { 'ENGINE': '', #some pyodbc backend database 'NAME': 'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD': 'mypassword', 'HOST': '127.0.0.1', 'PORT': '5432', } } -
Field 'id' expected a number but got 'on'
I am doing a project included in Django Documentation.When i enter URL-http://localhost:8000/polls/1/vote/ i get the Error at below line, ` selected_choice = question.choice_set.get(pk=request.POST['choice']) -
I want to restrict the user from adding the duplicate value in 'type' field
class Device(models.Model): # name of the table type = models.CharField(max_length=100, blank=False) price = models.IntegerField() choices = ( ('AVAILABLE', 'Item ready to be purchased'), ('SOLD', 'Item Sold'), ('RESTOCKING', 'Item restocking in few days') ) status = models.CharField(max_length=10, choices=choices, default="Sold") # Available, Sold, Restocking issue = models.CharField(max_length=100, default='No Issue') -
Alter or override Device model from Django-push-notifications
I just started using Django-Push-Notifications but I find it concerning that the built in "Device" model uses the standard USER_AUTH table for its user field. I have my own custom user table and would like to change the 'user' foreign key in the "Device" table to point to my custom user table. In addition, I would like to add a couple fields to the "Device" table. How can I override or add fields to the Django-Push-Notifications "Device" model? -
Adding the row to another table after clicking "Add New Row" button
I'm an apprentice in Django, javascript, and HTML. I am developing a website that actually helps in filling shift handover(If a company works in shifts, then the associates in the current shift should handover the shift to next person by explaining pending tasks to be completed, scheduled tasks/activities in his/her shift.. etc). During this, I have encountered a problem. I had written 6 HTML files for 6 tables separately. And I had written Add new row, edit, save, and delete functionalities for 6 tables using one jquery script. Now I need to include all 6 tables in one HTML file and should link that one jquery script such that all functionalities(add, delete, edit and save) should work individually for 6 tables. But here if I click on add new row button on one table, the row is getting added on another table. Kindly help on this. -
What if I return None in django views and handle it in middleware?
We always return HttpResponse in Django views, but now I want to do this pack stuff in middleware. That is, I can return a dict (or something else) or raise an error in view, and my middleware will detect it: If it returns a dict (body), the middleware will pack dict like {error: None, code: 0, body: bodydict} and use JSON.dumps to get a string as response content (with code 0 for example); If it raise an error, the middleware will stringify the error and pack it like {error: "Some Error", code: 500, body: []} If the view returns None, the middleware will pack as {error: None, code: 0, body: None} But the problem is, django will detect the return of view. If it returns None, it will log an Error: The view xxxView didn't return an HttpResponse object. It returned None instead. Now I want to remove this log. What should I do? -
How do I create a method in django models that returns the sum of a field in that same model?
I'm new to Django and I have two models set up like this currently. I want to calculate, in the Climber model, that returns the total points that climber has earned by accessing the climbs_completed field. How can I go about doing this? In other words, how do I sum up the points for each Climb in climbs_completed? Is there a better way to do this besides writing a method? Thank you in advance! class Climb(models.Model): name = models.CharField(max_length=20, default='') grades = [('v'+str(i),'v'+str(i))for i in range(0,13)] grade = models.CharField(max_length=3, choices=grades, default='v-1') weeks = [(i,i)for i in range(1,13)] week = models.IntegerField(choices=weeks, default=0) points = models.IntegerField(default=0) def __str__(self): return self.name class Climber(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) grades = [('v'+str(i),'v'+str(i))for i in range(0,13)] highest_grade = models.CharField(max_length=3, choices=grades, default='v0') team = models.ForeignKey(Team, null=True, on_delete=models.SET_NULL) climbs_completed = models.ManyToManyField(Climb, blank=True) def __str__(self): return self.user.username # for each climbs_completed, sum up the points def total_score(self): pass -
ModuleNotFoundError: No module named 'encodings' after broken pipenv Django install in Win 10?
So I'm very much out of my element here, I attempted to search this but none of the other questions appeared to be quite similar to the situation with mine (either that or I'm too unfamiliar to parse out the necessary info). I tried to install Django with a 32 bit Python 3.8 install (Windows 10) and something went wrong along the way, it wasn't appearing to run correctly after installing in pipenv and so I uninstalled python through the provided windows uninstaller within the control panel. I downloaded and installed the 64 bit python 3.8 installer and ran throught the install. I installed pipenv with: python -m pip install pipenv which appeared to work fine. I then proceeded to run: pipenv install This appeared to work as well, and then I activated the pipenv environment with "pipenv shell". It seemed okay, a new shell was opened and it looks like it IS inside of the virtual environment, but when I ran "pip freeze" to confirm everything was fine, I got the following return instead of a blank line as I would expect to be returned from a fresh environment: Is there some sort of issue with the path here? … -
Django Dynamic Forms with add and delete button. Python/Django
i am new to Django, and i am working in a project, i got a question, in my app i want to show up a form to populate the database called patients, this form is based in a model, and this model is linked with a foreign key to another model Relatives(Family), i would like to create a Dynamic Form where i could add as many members as i want, for example, I am filling a patients info, so when getting to the relatives section it would appear a form for adding one family member but what about if i want to add another member, i've seen there are Django Form Sets, but they dont seem to have any methods to add add or delete buttons, so what approach should i take, any solutions or recommendations? Thanks! -
How do I communicate with a websocket within a Django API GET request?
I'm trying to get a response from a websocket server (implemented with websockets and asyncio) from within a Django REST API method. Something of the following structure: Django App (This does not work, but illustrates the idea) class AnAPI(views.APIView): async def get(self, request): try: timeout = 5 try: ws_conn = await asyncio.wait_for(websockets.connect(WS_STRING), timeout) except ConnectionTimeoutError as e: <.....> await ws_conn.send(...) response = await ws_conn.recv() ws_conn.close() return Response(...) except Exception as e: print(e) return Response(...) WS Server ws_server = websockets.serve(...) asyncio.get_event_loop().run_until_complete(ws_server) asyncio.get_event_loop().run_forever() Apparently, this makes the Django GET method return a <class 'coroutine'> AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'coroutine'>` Any pointers would be much appreciated! -
Django ORM pass model method value in aggregate
This is my models: class Bill(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='user_bill' ) flat_rent = models.DecimalField( max_digits=6, decimal_places=2, default=0.00 ) gas_bill = models.DecimalField( max_digits=6, decimal_places=2, default=0.00 ) # Also i have many such decimalField here that calculated in get_total =========================================== def get_total(self): total = self.flat_rent + self.gas_bill return total I am trying to pass this get_total mehtod value here: user_wise = User.objects.filter( id=request.user.id ).aggregate( get_total=Sum('user_bill__get_total') ) in my case, i have to query everything from user with related_name, that is why i am aggregate the model method here. Can anyone help how can i pass this get_total method in aggrigate? I dont want to pass like this. Bill.objects.get(user__id=request.user.id).get_total Can anyone help to achieve this? Thanks for your help -
Django- 2nd App within project, page not found
I can not figure out what I am doing wrong within the second app my project called 'weather'. The first part, 'home', works fine. I made it so that an empty url '' and a url with '/home/' both map to the home page. Even the link I created in my navigation bar to the home page works, but the same is not true for the weather link. I end up getting 'Page not found 404' Error. Here is an overview: Project structure I included the app 'weather' in the settings installed apps. Here urls.py file in the main project folder: from django.contrib import admin from django.urls import path, include from weather import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path('', include('weather.urls')), ] The urls.py file for my weather app: from weather import views from django.urls import path urlpatterns = [ path('', views.GetWeather.as_view(), name='weather'), ] The views.py for the weather app: from django.views import generic import requests from django.shortcuts import render from .models import City from .forms import CityForm class GetWeather(generic.ListView): queryset = City.objects.order_by('-requested') template_name = 'weather.html' def index(request): url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=c5a079de62bccff63d64ac8989f87e37' form = CityForm() cities = City.objects.all() weather_data = [] for city in cities: r = requests.get(url.format(city)).json() city_weather … -
Django: Saving instance only if it does not exist already
I only want to save an instance of Location if the address does not exist already. Currently when you try to save with an address that already exists you receive a BAD REQUEST. How can I override the save function to achieve this? And would this be the right way to do it? current model: class Location(models.Model): latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True) longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True) address = models.CharField(max_length=150, unique=True) field_quality = models.DecimalField( max_digits=3, decimal_places=1, null=True,) field_availability = models.DecimalField( max_digits=3, decimal_places=1, null=True,) place_id = models.CharField(max_length=200, null=True) def save(self, *args, **kwargs): if self.objects.filter(address=[self.address]).exists(): pass else: super().save(*args, **kwargs) -
REST API ?? Django?
I have a following requirement and was looking for some direction. Purpose - Create a website framework where suppliers can enter the information about material characteristics for every order they supply. I store that information in SQL and attach it to the physical order. I trace the material usage and adjust the process according to the characteristics associated with the Order. I am familiar with SQL, python and bit of java. I started learning Django and thought that It might could be something workable but just wanted to make sure I choose the right direction. Any leads will be much appreciated. -
My friends can't send video files from chrome. 403 error occured
Recently I made a video converting application, and deployed to nginx. And there's a problem that my friends can't send video files(axios form-data type) from chrome browser. (403 INCOMPLETE_CHUNKED_FILE error) But In my computer, I can send a video file from chrome to nginx deployed django application, and send back the converted video file url. I tried 1. chmod 777 web application contained directory 2. change uwsgi chmod-socket 660 -> 666 3. client_max_body_size 1M -> 50M 4. set ec2 80port //uwsgi.ini [uwsgi] uid=django base=/var/www/fileconvert home=%(base)/venv chdir=%(base) module=config.wsgi:application env=DJANGO_SETTINGS_MODULE=config.settings master=true processes=5 socket=%(base)/run/uwsgi.sock logto=%(base)/logs/uwsgi.log chown-socket=%(uid):www-data chmod-socket=666 vacuum=true //uwsgi.service [Unit] Description=uWSGI Emperor service [Service] ExecStart=/var/www/fileconvert/venv/bin/uwsgi --emperor /var/www/fileconvert/run User=django Group=www-data Restart=on-failure KillSignal=SIGQUIT Type=notify NotifyAccess=all StandardError=syslog [Install] WantedBy=multi-user.target // sites-available/fileconvert upstream django{ server unix:/var/www/fileconvert/run/uwsgi.sock; } server { listen 80; server_name ec2_public_domain; charset utf-8; client_max_body_size 50M; location / { include /etc/nginx/uwsgi_params; uwsgi_pass django; } } I want to know how to get data from another computer without error 403. Thanks! -
TypeError: expected str, bytes or os.PathLike object, not method
I'm trying to upload a file uploaded from HTML form via POST to Google Drive. I was able to get the file name, file temp path, but it throws this error and the file is eventually not uploaded to Google Drive. @method_decorator(csrf_exempt, name='dispatch') class Submit(MissionSubmission): def get(self, request, mission_id): mission = MissionDetail.objects.all().filter(id=mission_id)[0] mission = newline_aware(mission) return render(request, 'home/submit.html', {'mission': mission}) def post(self, request, mission_id): request.upload_handlers = [TemporaryFileUploadHandler(request=request)] return self._post(request, mission_id) @method_decorator(csrf_protect) def _post(self, request, mission_id): uploaded_file = request.FILES['filename'] print(uploaded_file.name) print(uploaded_file.size) print(uploaded_file.temporary_file_path()) print(uploaded_file.content_type) file_metadata = {'name': uploaded_file.name} media = MediaFileUpload(uploaded_file.temporary_file_path, mimetype=uploaded_file.content_type) file = drive.files().create(body=file_metadata, media_body=media, fields='id').execute() print('File ID: %s' % file.get('id')) return HttpResponse("Hi") Anyone knows what's wrong? -
How can I restore the database contents
I back up the database by below command: docker exec -it kiwi_web /Kiwi/manage.py dumpdata --all --indent 2 > database.json then, upgrade running Kiwi TCMS containers and restore the database by executing the following commands: [1.cd Kiwi/ 2.git pull 3.docker-compose down 4.docker pull kiwitcms/kiwi 5.docker pull centos/mariadb 6.docker volume rm kiwi_db_data 7.docker exec -it kiwi_web /Kiwi/manage.py migrate 8.docker-compose up -d ] until now, it's fine. when I delete data from all tables [docker exec -it kiwi_web /bin/bash -c '/Kiwi/manage.py sqlflush | /Kiwi/manage.py dbshell'] it shows "CommandError: You appear not to have the 'mysql' program installed or on your path." I don't know how to fix it. If I restore database command directly, it shows "django.db.utils.IntegrityError: Problem installing fixture '-': Could not load contenttypes.ContentType(pk=1): (1062, "Duplicate entry 'admin-logentry' for key 'django_content_type_app_label_model_76bd3d3b_uniq'")". So, what should I do to restore the database contents ? -
Is it okay to use Function Based Views and Class Based Views Combined in a Django Project?
I am actually working in a project in Django, let's say i want to add a new patient to my database, we are collecting all its data but there is a field in that patient model which requires to insert their relatives info, Parents, sons and so on, for that i want to show two forms in that view, one to create the patient own info and other to create their relatives and link those relatives to the patient, i've been looking for how to show two forms in a class based view but i can not find an answer is there any way or its impossible to do so? and my next question is... is correct to use a function based view to show my forms and use detail views, to show info, updateview to update a patient for example, a deleteview? -
Django Object Sorting Changer
I am working on a project so that I can learn django. I have a model with an image, name field, and birthday field and I am just displaying them as 'cards'. I have them displayed properly now and can sort them with the dictsort in my view template. How can I add functionality to switch sorting methods (name, birthday..). I'm wanting to use some radio buttons at the top of my page that will allow the user to change sorting methods. Would I implement this with django forms? Here's the code that sorts my cards {% for villager in villager_list|dictsort:"birthday" %} -
Slicing a object_list in Django template
I want to slice object_list to display the result which I have attached. layout I'm not sure where I have to write a slice. This is the code I wrote. in list_html {% include "layout.html" with object_list=object_list number_of_columns=4 %} layout.html <div class="flex"> {% for object in object_list %} {% if forloop.counter0|divisibleby:number_of_columns and not forloop.first %} </div> <div class="flex"> {% endif %} <div class="grid grid-cols{% widthratio 12 number_of_columns 1 %}"> {% getattribute object attribute %} </div> {% endfor %} </div> What should I do? Can anyone help me? Thank you very much -
Why Django makes 2 inner joins with AND clauses instead or a single inner join with OR?
Good evening to all, I'm following the django docs on making queries, and this example showed up: Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008) I was hoping that the corresponding SQL query to this involved only one inner join and a OR clause, since the corresponding results are entries that either satisfy one or both of the conditions. Nevertheless, this is what an inspection to the queryset's query returned: >>> qs = Blog.objects.filter(entry__headline__contains='Hello').filter(entry__pub_date__year=2008) >>> print(qs.query) SELECT "blog_blog"."id", "blog_blog"."name", "blog_blog"."tagline" FROM "blog_blog" INNER JOIN "blog_entry" ON ("blog_blog"."id" = "blog_entry"."blog_id") INNER JOIN "blog_entry" T3 ON ("blog_blog"."id" = T3."blog_id") WHERE ("blog_entry"."headline" LIKE %Hello% ESCAPE '\' AND T3."pub_date" BETWEEN 2008-01-01 AND 2008-12-31) You can see that it makes TWO inner joins. Wouldn't the result be the same as: SELECT "blog_blog"."id", "blog_blog"."name", "blog_blog"."tagline" FROM "blog_blog" INNER JOIN "blog_entry" ON ("blog_blog"."id" = "blog_entry"."blog_id") WHERE ("blog_entry"."headline" LIKE %Lennon% ESCAPE '\' OR "blog_entry"."pub_date" BETWEEN 2008-01-01 AND 2008-12-31) ? And this later query AFAIK is faster. (added line breaks for readability)