Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot connect to django rest api with react native network error
I'm new with django and react native. I try to make an app that sends data to django back end with axios but I have a network error. I tried to change my localhost ip in 192.168.xxx but nothing change. So I don't understand hy I don't have any request. Here is my code: Django : CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http://localhost:8081', 'http://localhost:19006', 'http://localhost:19002', 'http://192.168.101.6:19000', ) Axios: import axios from "axios"; export default axios.create({ baseURL: "http://192.168.101.6:8080/api", headers: { "Content-type": "application/json" } }); requests : import http from "../http-common"; const getAll = () => { return http.get("/tutorials"); }; const get = id => { return http.get(`/tutorials/${id}`); }; const create = data => { return http.post("/tutorials", data); }; -
Django set timezone into Postgres SQL view date
In my Django app and Postgress: I'ved got a view, model, orm code as below. I want to be able to set 'Asia/Tokyo' timezone as parameter so that in the django ORM code it can be configured dynamically. For example, on different occassion, it is set to 'America/Chicago' or 'Australia/Sydney'. How can I modify the sql view, model and orm to accept timezone parameters postgres sql view DROP VIEW IF EXISTS view_attendance_dates; CREATE OR replace view view_dates as <-- the name of the view SELECT created_at::date AT TIME ZONE 'Asia/Tokyo' as created_date, employee_id FROM mydb_attendance model.py class DateAttendanceModel(models.Model): created_date = models.DateField() employee = models.ForeignKey(Employee,on_delete=models.DO_NOTHING,null=True) class Meta: managed = False db_table = "view_attendance_dates" <-- here is where I put the view Django ORM (is it possible to put in the timezone somewhere here ? 'America/Chicago' or 'Australia/Sydney') from railercomapp.utils import convert_to_date filterdate_start = convert_to_date('2020-11-18') filterdate_end = convert_to_date(2020-11-30) employee_attendance_reports = DateAttendanceModel.objects.filter( Q(created_date__range=(filterdate_start,filterdate_end)) ) -
I can submit data but won't go to new page -or- go to new page and data doesn't get saved in Django
So the title kind of says it all. I have a form based on a model. The goal is to have the specific data entered, user presses submit, data gets saved to a Postgresql DB, user sees complete.html. However this is not the case. I can either get the data to save without changing pages, or the page will change but the data will not submit. I have put details on the specifics of I tried below. urls.py from django.urls import path, include from . import views urlpatterns = [ path('', views.index, name='index-page'), path('feedback/', views.feedback_view, name = 'feedback'), path('complete/', views.complete, name = 'complete') ] models.py from django.db import models from django.utils import timezone from django.core.validators import RegexValidator class feedback(models.Model): RECENT_GROUND = [ ('PVT','Private'), ('INS','Instrument'), ('COM','Commercial'), ('MEL','Multi-Engine'), ] RATING = [ (1,'Poor'), (2,'Below Average'), (3,'Average'), (4,'Above Average'), (5,'Excellent'), ] id_field = models.AutoField(primary_key = True, serialize = True) added = models.DateTimeField(default = timezone.now) spid = models.CharField(primary_key = False, max_length=5, verbose_name = 'Enter the students FSA ID number:') recent_ground = models.CharField(max_length = 3, choices = RECENT_GROUND, verbose_name = 'Most recently completed ground school:') question1 = models.IntegerField(choices = RATING, verbose_name = 'This is question 1') question2 = models.IntegerField(choices = RATING, verbose_name = 'This is … -
How to fix heroku connection error when deploying my Django app
could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? The following error is what I get when I open up my site on heroku. I'm not sure what is going on, but my settings are as follows... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('DB_NAME'), } } pushing to heroku master works fine but just when opening up my app heroku open I get that error and I am not sure how to fix it. -
Get a 'Session matching query does not exist' error when users auto login via chrome
Error page The website gets a 'Session matching query does not exist' error when users auto login via chrome. The error happens in the middleware that makes sure users can't login in different browsers. from django.contrib.sessions.models import Session class OneSessionPerUser: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. if request.user.is_authenticated: current_session_key = request.user.logged_in_user.session_key if current_session_key and current_session_key != request.session.session_key: Session.objects.get(session_key=current_session_key).delete() request.user.logged_in_user.session_key = request.session.session_key request.user.logged_in_user.save() response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response Does anybody know what might be the problem here or does anybody know how to disable the chrome auto login? -
Django TemplateDoesnotExist / blog/home.html, blog/post_list.html
So I am trying to have my server uploaded using LinuxNode and I been following Corey Schaffer's tutorial. The server will run, but it produces an error. It runs when I am using the python3 manage.py runserver command in my regular linux terminal environment. When I ssh into my server and have it run, it comes up with an error. : global _loop if _loop is None: _loop = asyncio.new_event_loop() threading.Thread(target=_loop.run_forever, daemon=True).start() _loop.call_soon_threadsafe(asyncio.create_task, coro) test function class TestEmails(TestCase): def setUp(self): create_mock_data(self) def test_send_mail(self): fire_and_forget(send_mail(self.order)) self.assertEqual(len(mail.outbox), 2) self.assertEqual(mail.outbox[0].to, [TEST_EMAIL]) self.assertEqual(mail.outbox[1].to, [DEFAULT_EMAIL]) is it possible to wait for the thread? furthermore when the test Destroying test database Im getting following error: Task exception was never retrieved sqlite3.OperationalError: database table is locked: In the send_mail its retrieving data from database... -
Django Page Restriction (Admin and Members could be able to see it)
Thanks for your help I got a question : I want to make accessible only for two type of people: admin (ForeignKey) and friends (ManyToMany). All belongs to the same model. The issue is user who belongs to friends are redirected to '/' and can not see the page self.object.user -> user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) self.object.friends -> friends = models.ManyToManyField(User,blank=True,related_name='friends_reservation') def get(self,request,*args,**kwargs): self.object = self.get_object() if not (request.user == self.object.user or request.user == self.object.friends): return HttpResponseRedirect('/') -
Get object attribute value after query - DJango
class item (models.Model): ITEMS = [ ("ELEC", "ELECTRICIDAD" ), ("CERR", "CERRAJERÍA"), ("REFR", "REFRIGERACIÓN"), ("PLOM", "PLOMERÍA"), ("HERE", "HERRERÍA"), ("CARP", "CARPINTERÍA"), ("TRON", "ELECTRÓNICA"), ] DAYS_OF_WORKS = [ ("LV", "LUNES A VIERNES"), ("LL", "LUNES A LUNES"), ] items = models.CharField(max_length=4, choices = ITEMS) certificate=models.ImageField(default=None) provider = models.ForeignKey(serviceProvider, on_delete=models.CASCADE, null=True) radius = models.FloatField(default=None) description= models.TextField(blank = True) days_of_works = models.CharField(max_length=2,choices= DAYS_OF_WORKS,default= "LV") hour_init = models.TimeField() hour_end = models.TimeField() This is the search for the object I do. Those with a radius equal to 50. Now how can I access another attribute of the model? response=item.objects.filter(radius=data) response.hour_end for example how can I acces to: hour_end atribute? because if I write response.hour_end gives me error -
is this a Django bug?
I created a project and within the project an app call myusers. I then created a model with the class name AllUsers. I then populated the model with data from faker. When I go to 127.0.0.1/admin under authorization I have groups and users. Under myusers I have ‘All userss’ which is a link to http://127.0.0.1:8000/admin/myusers/allusers/ so, I’m just wondering if this is a minor bug. Shouldn’t it say ‘AllUsers’ and not ‘All userss’? Or did I corrupt something along the way? -
display multiple models in one view and get slug url for each post - django
i am trying to show data from multiple models in one single view and one single template and i succeed with that but i have problem , the problem is posts from android model keep show at first because i have added android first in html page but what i want to do is show posts by date published what should i do models.py : class android(models.Model): name = models.CharField(max_length=50,default="") slug = models.SlugField(max_length=250,default="") post_date = models.DateTimeField(auto_now_add=True, null=True, blank=True) def get_image(self): if self.app_image and hasattr(self.app_image, 'url'): return self.app_image.url else: return '/path/to/default/image' def __str__(self): return self.name class Meta: ordering = ('-post_date',) class PCgames(models.Model): name = models.CharField(max_length=50,default="") slug = models.SlugField(max_length=250,default="") post_date = models.DateTimeField(auto_now_add=True, null=True, blank=True) def get_image(self): if self.app_image and hasattr(self.app_image, 'url'): return self.app_image.url else: return '/path/to/default/image' def __str__(self): return self.name class Meta: ordering = ('-post_date',) views.py : def home_page(request): pcgamesforhome = PCgames.objects.all() androidforhome = Android.objects.all() context = {'pcgamesforhome' : pcgamesforhome,'androidforhome' : androidforhome} return render(request,'html_file/home.html',context=context) home.html : <div class="container"> <div class='row'> {% for android in androidforhome %} <div class='col-xs-12 col-sm-6 col-md-4 website-thumb'> <a href="{{ android.slug }}"> <img src="{{ android.get_image }}" class='image_control_for_home_page_pc_games' alt=''> </a> <h3><a href="{{ home_page.slug }}" class="font_control_for_home_page_pc_games_name">{{ android.name }}</a></h3> </div> {% endfor %} </div> <div class="container"> <div class='row'> {% for home_page in … -
Related Object Does Not Exist at /account_settings/ plz help me to resolve this
Here is the code of my project that contains the files models.py, views.py and urls.py. it showing me the error that object does not exist. Exception Type: RelatedObjectDoesNotExist Exception Value: User has no student. now where I was mistaking. please guide me I m a newbie. I searched a lot but unable to resolve it. explain me what is the right code for it. ''' Create your models here. class School(models.Model): schoolid = models.AutoField(primary_key=True) schoolname = models.CharField(max_length=50, null= True) # schoolimage = models.ImageField() schoolcontactno = models.CharField(max_length=13, null= True) schooladdress = models.CharField(max_length=500) createddate = models.DateTimeField(null= True) schoolemail = models.EmailField(null= True) password = models.CharField(max_length=13,null= True) def __str__(self): return self.schoolname class Section(models.Model): sectionid = models.AutoField(primary_key=True) sectionname = models.CharField(max_length=500,null= True) schoolid = models.ForeignKey(School,null= True,on_delete=models.SET_NULL) class Status(models.Model): statusid = models.AutoField(primary_key=True) statustype = models.CharField(max_length=50,null=True) class Client(models.Model): userid = models.AutoField(primary_key=True) username = models.CharField(max_length=50,null = True) ceratedon = models.DateTimeField(null = True) email = models.CharField(max_length=50,null = True) password = models.CharField(max_length=13) certificatetypename = models.CharField(max_length=100,null = True) cnic = models.CharField(max_length=50,null = True) contactnumber = models.CharField(max_length=13,null = True) # image = models.CharField(max_length='',null = True) status = models.ForeignKey(Status, null=True,on_delete=models.DO_NOTHING) confirmpassword = models.CharField(max_length=13,null = True) class TblClass(models.Model): classid = models.AutoField(primary_key=True) # name = models.CharField(max_length=50,null= True) schoolid = models.ForeignKey(School,null= True,on_delete=models.SET_NULL) class RoleName(models.Model): roleid = models.AutoField(primary_key=True) … -
403 Error trying to do a post request in django
I keep getting 403 errors when I try to do a post request in Django. I disabled django.middleware.csrf.CsrfViewMiddleware and i still have this line url(r"viewing_room_capture", csrf_exempt(EmailCapture.as_view()), name="email_capture_endpoint",) Why am I getting a 403? It doesn't even look like my view executes, the request short-circuits before the view runs. And yes I do want to disable the csrf protection on my forms. I seem to remember this working a week ago but I've since rebuilt my local environment from scratch (docker-compose app) and it no longer works. I had 5 working API endpoints before this and now none of them work, I haven't touched this app in 1.5 weeks before coming back to it today and finding everything broken. In fact, I have a development deployment using the same application code running right now in the cloud and I'm not getting 403 errors on my API endpoints (i checked the commit history already, nothing that could have caused this was added since my last deploy). My middleware is: MIDDLEWARE = [ "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "app.site_translation.middleware.TranslationMiddleware", "django.middleware.common.CommonMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "django.middleware.security.SecurityMiddleware", "app.base.middleware.AdditionalSecurityHeadersMiddleware", "app.base.middleware.CookieMiddleware", "app.base.middleware.DomainRedirectMiddleware", "app.base.middleware.CustomRedirectMiddleware", "app.base.middleware.LegacyURLsMiddleware", # Can be used instead if wagtail#4491 is merged: # 'wagtail.contrib.redirects.middleware.RedirectMiddleware', "debug_toolbar.middleware.DebugToolbarMiddleware", ] -
Getting filtered list of another class within the DetailView which is looping through some other class
views.py class UserPublicShell(DetailView): model = User template_name = 'users/public_shell.html' urls.py: urlpatterns = [ path('<int:pk>/public_shell/', UserPublicShell.as_view(), name='public_shell'), The view is showing the public page of a user.This user is not the logged in user in my app. My problem is that I can't give my view only the posts which this user(the user whom the logged -in user is seeing) has written. -
Django: Send data (pandas dataframe) to another app using html link
I have the app: index and I'm using a pandas dataframe named data wich I must send to another app (clean_data) index view: context ={'data' : Data } return render(request,'index.html',context) in my index html template I have a link <a href="{% url 'clean_data:clean_data_v' %}">Clean Data</a> Finally I want to pass "data" from index to clean_data how can I do it? -
How to create two users for same sub category
I have 4 Users(2 X CP_USER, 2 X CP_SCRNS) and two subgroups(Login stats and Application stats) but two of then belong to one group and another 2 belong to another group. Here is the screenshot. Database How to separate two group and display in the html page in the same box.Here is the referenceHere is the reference how the index page shouls look like. . Here is my models page: from django.db import models from datetime import datetime Create your models here. class Kpi_Data(models.Model): kpi_key = models.CharField(max_length=200,default="") kpi_date = models.DateField(blank=True,null=True) kpi_value = models.CharField(max_length=200,default="") kpi_Group = models.CharField(max_length=200,default="") kpi_subgroup = models.CharField(max_length=200,default="") kpi_delta_ind = models.CharField(max_length=200,default="") Here is my views.py file from django.shortcuts import render from django.http import HttpResponse from .models import Kpi_Data from django.template import loader Create your views here. def home(request): return render(request,"myApp/index.html") def info(request): ac = Kpi_Data.objects.all() template = loader.get_template('myApp/info.html') Context = { 'ac': ac, } return HttpResponse(template.render(Context, request)) Thanks in advance. -
How Django search for the module/apps in project folder
This question is related to the following questions. How to import urls from apps in django main urls file Actually I have the following project structure. I want to ask why I have to use complete path link to point the apps in INSTALLED_APPS or even anywhere in the django files. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'climemanage.clients', ] Why I can't use just import climemanage.clients (or any other import statement) and use clients in INSTALLED_APPS ? Same for the urls.py file I have to use the complete path as climemanage.clients.urls the following. from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('clients/', include('climemanage.clients.urls')), ] Why not just clients.urls ? -
i have problem creating to different user authentication for two different apps in django
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'db_app1': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite1', }, 'db_app2': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite2' } } i want to create two database set for app1 and app2 where they should have a different authentication database for app1 and app2 -
How do you get libfaketime to work from inside of a Django server?
I am trying to use libfaketime to trick a program (tbl2asn) from expiring. This program is called within a Django view. The Django server sits within a docker container and the following environment variables are set through docker-compose: environment: LD_PRELOAD: "/path/to/libfaketime.so.1" DONT_FAKE_MONOTONIC: 1 FAKETIME_DID_REEXEC: "true" When I use docker exec to get into the container and run python from the command-line, libfaketime works perfectly. However, when it is called from the Django view it does not change the date and the program fails to execute. The code being called from within the view: import os from libfaketime import fake_time import subprocess with fake_time('2018-01-01 00:00:01'): print(datetime.datetime.now()) print(os.environ) subprocess.run([command]) This produces the following output: 2020-12-01 14:00:18.037169 environ({'PATH': ..., 'HOSTNAME': ..., 'LD_PRELOAD': '/path/to/libfaketime.so.1', 'DONT_FAKE_MONOTONIC': 1, 'FAKETIME_DID_REEXEC': 'true', 'HTTPD_PREFIX': '/usr/local/apache2', 'HTTPD_VERSION': '2.4.46', 'HTTPD_SHA256': ..., 'HTTPD_PATCHES': '', 'HOME': '/root', 'LC_CTYPE': 'C.UTF-8', 'TZ': 'America/New_York', , 'RUN_MAIN': 'true'}) And also produces an error when running the subprocess command ([tbl2asn] This copy of tbl2asn is more than a year old. Please download the current version.) -
not able to access organisation's LDAP server through python-ldap
The actual requirement is that I have to achieve LDAP authentication for my organisation's internal web application which is being built on Django but not able to do so by far. Therefore, I have decided to check if i'm able to establish the connection using the python-ldap module. the details of the ldap server that I have: server1 = dc3.something-software.com server2 = dc5.something-software.com domain = SOMETHING and the python code: def main(server="ldap://something.dc5.something-software.com", who="", cred=""): try: l = ldap.initialize(server) l.simple_bind_s(who, cred) if l: print("Successfully connected") except Exception as e: print(e) return True and the error is {'result': -1, 'desc': "Can't contact LDAP server", 'ctrls': []} Im working on a windows operating system and I have tried the answers suggested for other similar questions though they've been mostly addressed for *NIX operating systems. Thanks. -
React: Production build looks different from development build
I have a React/Django app that's behaving differently when built for production that it does when run on the development server. The development version is how I want it to look. There are a number of issues with the CSS. Text is a different font, and a some Bootstrap/Reactstrap features are ignored. See example screenshots below. I think the issue has to do with the order in which css files are processed by the dev server, versus how Django serves the built app, by collecting the files in the /build dir created by the build script into the Django /staticfiles dir. I'm mystified how this would selectively apply classes to the same component, however. (See below - the offset of the jumbotron text is different, while the column size is the same) Here's a screenshot of the home page in the production build, either served locally by Django or remotely on Heroku. (npm run build or npm run build-local - see package.json file below) And here is how it looks on the local dev server: (npm run start) In particular, the offset-md-5 class is ignored on the production build, while the rest of the classes aren't, col-md-5 for example applies … -
How to receive POST data asynchronously in a view?
I am pretty new to django and I am struggling to find a solution to my problem. I am currently working on implementing a third-party payment system on my django website. The problem occurs while trying to get POST data from the payment site. After succesful test-payment, by clicking "Return to seller's site" button I am getting redirected back to my own page with POST request "status=ok". After that, I should receive POST request to url I've added on the payment's site user profile (the same url that I'm getting redirected to). I've been trying to print that data with: @csrf_exempt def payment_result(request): print(request.POST) return render(request, "payment_result.html") but I am getting only: <QueryDict: {'status': ['OK']}> Which is POSTed along with clicking "Return to seller's site" button. The other POST request (with necessary payment data) is not related to the button - it executes asynchronously. I've checked that the payment website is properly sending data with POST request by adding https://webhook.site/ url to seller user profile. What should I do to make it work? Thank you for all the answers. -
How to extract base64 extension without using lib imghdr
I have a view that works perfectly for receiving base64 images. My problem is that in some rare cases it doesn't recognize the sent jpg image. It looks like None. Looking on the internet I saw that the problem is the lib imghdr. I tried to use OS lib to extract the extension and even use the lib pillow, but I couldn't. Does anyone have any tips? Here is an example of how I use imghdr: def get_file_extension(self, file_name, decoded_file): import imghdr extension = imghdr.what(file_name, decoded_file) if extension == "jpeg": extension = "jpg" return extension -
Django Payfast API Errors - Cancelling Subscription (GET/PUT Request)
I am attempting to cancel subscriptions with the payfast api through a website. I have read through this question but as you can see, no solution is provided and it is not Django specific. That answer does mention that you should not use CORS which I took to mean that the server itself should send the request and so I am using the following Django view: def cancel_payfast(request, token): timestamp = datetime.now().astimezone().isoformat() signable_fields = {"merchant_id":str(conf.MERCHANT_ID), "version":"v1", "timestamp":timestamp,} text = urlencode(signable_fields, encoding='utf-8', errors='strict') signature = md5(text.encode('ascii')).hexdigest() r = requests.put('https://api.payfast.co.za/subscriptions/%s/cancel?testing=true'%token, data = {'merchant_id':conf.MERCHANT_ID,'version':"v1",'timestamp':timestamp,'signature':signature}) return HttpResponse(r) The return provided by Payfast is {"code":401,"status":"failed","data":{"response":"Merchant not found.","message":false}} but I have confirmed that the Merchant ID I am using is correct (Payfast sandbox). I decided to try the perhaps simpler task of getting a ping to work, using the same code but replacing "requests.put" with "requests.get" and "cancel" with "ping" but then I get an error from Google(?) saying: "400. That’s an error. Your client has issued a malformed or illegal request. That’s all we know." I will continue to try to fix this, any help is appreciated. -
Is there any way to exclude some field of InlineModel in django admin?
I have two models Gift and Checkout, each Gift has Checkout_id as a foreign key. In the Checkout section of my Django admin, I want to show Checkout properties and related Gifts. Here's what I did: class GiftInline(admin.TabularInline): model = Gift exclude = ('sender_session_token') class CheckoutAdmin(admin.ModelAdmin): list_display = ('id', 'amount', 'retailer_id', 'is_paid', 'requested_at', 'paid_at') inlines = [GiftInline,] admin.site.register(Checkout, CheckoutAdmin) But I want to exclude some fields in the inline view. what can I do?