Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Server error 500 when I test django-admin
Probabily I shouldn't test django-admin but it's an excercise. If I go manually all works like expected but when I use Selenium to test I have problems. This is my test.py: class StudentTestCase(LiveServerTestCase): def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(10) self.admin_user =\ get_user_model().objects.create_superuser( username='bill', email='bill@example.com', password='password' ) def tearDown(self): self.browser.quit() def test_staff_can_add_content(self): """ Tests that a 'staff' user can access the admin and add Albums, Tracks, and Solos """ # Bill would like to add a record and a number of # solos to JMAD. He visits the admin site admin_root = self.browser.get( self.live_server_url + '/admin/') # He enters his username and password and submits the # form to log in login_form = self.browser.find_element_by_id( 'login-form') login_form.find_element_by_name('username').\ send_keys('bill') login_form.find_element_by_name('password').\ send_keys('password') login_form.find_element_by_css_selector( '.submit-row input').click() # He go to Albums page albums_links = self.browser.find_elements_by_xpath( '//a[contains(@href, "albums")]') albums_links[1].click() # He add a new album self.browser.find_element_by_link_text('ADD ALBUM').click() album_form = self.browser.find_element_by_id('album_form') album_form.find_element_by_name('name').send_keys('Liberi liberi') album_form.find_element_by_name('artist').send_keys('Vasco Rossi') album_form.find_element_by_name('slug').send_keys('liberi-liberi') breakpoint() # the form is rightly compilated album_form.find_element_by_css_selector('.submit-row input').click() breakpoint() # the page gives server error (500) instead to be redirected to the albums list page self.assertEqual( self.browser.find_elements_by_css_selector( '#result_list tr')[1].text, 'Liberi liberi') breakpoint() # the test never arrive so far because the server error page doesn't have a #result_list So the … -
Save Username with models in database
something=models.ForeignKey(User,related_name='something', on_delete=models.CASCADE) Hi when i'm using ForeignKey that model will save in database like : something_id how i can change it to username or ...? -
getting error 503 with django on litespeed
I created a django project on litespeed and did collectstatic and migrate . but when i requeset, it return 503 error. this is .hataccess file: # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN PassengerAppRoot "/home/hyperele/shop" PassengerBaseURI "/" PassengerPython "/home/hyperele/virtualenv/shop/3.7/bin/python" # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END and this is settings.py file: . . DEBUG = True ALLOWED_HOSTS = ['www.hyperelectrode.ir','hyperelectrode.ir'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'shop.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR+'/tmp'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'shop.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'assets'), ] STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR+'/public' MEDIA_URL = '/media/' it worked for once, but after that I don't know what happened... I'm using django==2.0 and python3.7. and also i can't access server as … -
How to Use OuterRef for ManyToManyField?
I am trying to query a list of rooms. There can be many participants in the rooms. I want to exclude rooms where there are participants a user blocked or got blocked from. The below code works if participants are simple ForeignKey(User) fields. However, the thing is participants are ManyToManyField field. It is written like participants = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='participants') And the below code does not work. get_blocked = Exists(users_models.Relationship.objects.filter( from_user=OuterRef('participants'), to_user=info.context.user, status='BLOCK')) blocking = Exists(users_models.Relationship.objects.filter( from_user=info.context.user, to_user=OuterRef('participants'), status='BLOCK')) models.Room.objects.annotate(get_blocked=get_blocked, blocking=blocking ).filter(participants=info.context.user, get_blocked=False, blocking=False ).distinct() Again, the same logic works when the participants are simple ForeignKey(User). I am wondering if there is any way to resolve this issue. -
Django-filter using dropdown instead of form
I'm trying to use django-filter to act like a nav bar, and want it as a dropdown that filters when the dropdown is selected. So far, I can get a search form working where a button has to be pressed, how can I do this with just the dropdown so the button doesn't have to be used. here is my filter: from django.contrib.auth.models import User import django_filters from .models import Project class ProjectFilter(django_filters.FilterSet): class Meta: model = Project fields = ['area', ] view.py: class ProjectListView(ListView): model = Project Here is the html I have been trying to work with. There are two bits here, first is the form version that works well, but not quite what I am after, then below was my attempt at just the dropdown. As it is, the dropdown will be on a base.html and the actual list of projects will be on an extended html page. <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Search</title> </head> <body> <form method="GET"> {{ filter.form.as_p }} <button type="submit">Search</button> </form> <ul> {% for project in filter.qs %} <li>{{ project.title }}</li> {% endfor %} </ul> <fieldset> <p> <label>Area</label> {{ filter.form.as_p }} <select> <option value="{{ project.area }}">{{ project.area}}</option> … -
How to upload files from React-native to S3 and store filename via REST API
I have dilemma in how to architect my React-native app in the best way using Amazon AWS S3 as image/file storage and Django backend using REST API. My react-native app has to be able to collect information from user together with couple of images and signatures. I am saving all information as props in redux and I can successfully transfer that to the database using Rest API in Django that I use as backend system. I can also send images to Amazon AWS S3 bucket, but that is a separate operation. My dilemma is if it is good practice to send images to S3 first and then send filename in the REST API call together with other info that is collected from the user in app? In this way, I have files in the place on S3 and I can use them in the creation of a PDF file that is going to be done by Django backend system. -
I am trying to get the InfoMessage from SQL server mangemnt using ADO and win32com
I trying to get the message that appears in the SQL server management using ADO and win32com, I know that there is a question like this, but I didn't know how to use so I will post my code here hoping that anyone can help. from django.shortcuts import render from .models import Router , InterfaceType , TransportServices , Rfde2003Syd0827 ,WhCdc from django.http import HttpResponse from django.db.models import Count from django.db import connections import win32com import pythoncom import adodbapi import time import win32gui from win32com.client import gencache gencache.EnsureModule('{2A75196C-D9EB-4129-B803-931327F72D5C}', 0, 2, 8) defaultNamedOptArg=pythoncom.Empty defaultNamedNotOptArg=pythoncom.Empty defaultUnnamedArg=pythoncom.Empty class events(): def OnInfoMessage(self, pError, adStatus, pConnection): print ('Info Message') a = pError.QueryInterface(pythoncom.IID_IDispatch) a = win32com.client.Dispatch(a) print (a.Description) print (a.Number) print (a.Source) #print 'B', adStatus c = pConnection.QueryInterface(pythoncom.IID_IDispatch) c = win32com.client.Dispatch(c) print (c.Errors.Count) print (c.Errors.Item(0).Description) print (c.Errors.Clear()) print ('c', adStatus) def preStepBtn1(request): sourcePE = request.GET.get('sourcePE') targetPE =request.GET.get('targetPE') sourceInterFace =request.GET.get('sourceInterFace') targetInterFace =request.GET.get('targetInterFace') print(sourcePE) print(targetPE) print("Target:") print(targetInterFace) #empty_DTARFDE2003SYD0827(sourcePE) #insert_DTARFDE2003SYD0827(sourcePE,sourceInterFace,targetPE,targetInterFace) pythoncom.CoInitialize() conn = win32com.client.DispatchWithEvents("ADODB.Connection", events) print (dir(conn)) with connections['DataAdmin'].cursor() as cursor: cursor.execute("SELECT * FROM [Data_Admin].[DTA].[RFDE2003SYD0827] ") print ("Done Execute") events.OnInfoMessage() return render(request,'posts/preStepBtn1.html') I want to print the message that appears in sql server mangemnt example: "Command(s) completed successfully." "Cannot drop the table 'my_table', because it does not exist or you … -
Modify variable in django template by rendering middle of variable
i have variable key.links.self (from json output) in template which is an url: https://ahostnamea.net:666/api/v1/ Now what i would like to do is render in template only ahostnamea from this variable. I know there is possibility to cut letters but when first letters always have same count (https:// = 8 letters), the rest is not that simple and it gets different. Is there any way to split/cut string from / to . ? Or any other way? -
How to use an count function as a condition in case statement in django orm
`SELECT id,(case WHEN (status<>"COM" AND ( SELECT COUNT(*) FROM BAC WHERE BAC.code="blablabla" AND (BAC.status<>"AM" AND CURDATE() > BAC.deadline) )>0 )THEN 6) as status FROM RestInterface_activity ACT) `I am facing the problem of converting a MySQL query to Django ORM. I am trying to assign a value to a field when the count of some values in another field increases than a certain value. -
Django, Django Rest Framwork, React and active directory
Context For a client I build a React app (app.client.com) using a Django app with the django-rest-framework (DRF) as a backend server under another domain (api.client.com). Right now the end users are logged in with djoser , meaning they swap their login credentials for a JSON web token. The client uses Active Directory and right now he wants the endusers to connect with Active Directory. If I had just created a Django app i could use django-microsoft-auth. If i just created an React app but didn't need the DRF i could use Auth0.com library Question How can i let the users log in with their microsoft account and at the same time use the same logged in state/credentials/access token to authenticate requests at the Django (DRF) backend. Can i pass the acces token from the fronend to the backend and use it to query say the profile of the user ? I found a similar question here. However it is unclear and not answered yet. -
Django cant Cast DateTime
I've tried cast string to datetime in orm. self.annotate(from_date=Cast(from_date, DateField())) .annotate(end_date=Cast(end_date, DateField())) .filter(from_date__lte=datetime.datetime.now()) .filter(end_date__gte=datetime.datetime.now() But i got error when i use 'd.m.y' format like "13.01.1999". Error django.db.utils.DataError: date/time field value out of range: "20.01.2018" HINT: Perhaps you need a different "datestyle" setting. -
it's doesn't go inside if form.is_valid()
It is doesn't go inside if form.is_valid() I tried in Stack overfull solution it's not resolve view.py def userCreate(request): if request.method == 'POST': form = userCreateForm(request.POST) if form.is_valid(): print("hello") try: form.save() return redirect("/show") except: pass else: form = userCreateForm() return render(request,'userPost.html',{'form':form}) userPostform.py class userCreateForm(forms.ModelForm): class Meta: model = userBasicDetails fields = '__all__' it no enter the if form.is_valid() -
why TimedRotatingFileHandler logs gets empty after midnight?
I have a Django website and I need to create separate logs for each day on separate file so I'm using TimedRotatingFileHandler. But when its midnight my default_logs.log get renamed to default_logs.log.2019-09-3 which should contain yesterdays log(since it's pass 12 o'clock), but its always empty. Here is my logging config LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "standard": { "format": "%(asctime)s:[%(levelname)s]:%(name)s:%(funcName)s():%(lineno)d:%(message)s" }, }, "filters": {"development": {"()": "django.utils.log.RequireDebugTrue"}}, "handlers": { "default": { "level": "INFO", "class": "logging.handlers.TimedRotatingFileHandler", "when": "midnight", "formatter": "standard", "filename": "/home/user/myapp/logs/default_logs.log", }, "error_log": { "level": "ERROR", "class": "logging.handlers.TimedRotatingFileHandler", "when": "midnight", "formatter": "standard", "filename": "/home/user/myapp/logs/error_logs.log", }, }, "loggers": { # ? [EMPTY-KEY-FOR-LOGGER] represents overall logging "": { "handlers": ["default", "error_log"], "level": "NOTSET", "propagate": True, }, "django": {"handlers": ["django_log"], "propagate": True}, "django.db.backends": {"handlers": ["sql_development_log"]}, }, } Is this problem happening because of multiple gunicorn workers? -
ValueError at /settings/email/ too many values to unpack (expected 2)
for receiver in self._live_receivers(sender) File "C:\Users\HP\dev\tridjango\djangoproject\marketing\models.py", line 19, in marketing_pref_create_receiver status_code, response_data = Mailchimp().subscribe(instance.user.email) ValueError: too many values to unpack (expected 2) status_code, response_data = Mailchimp().subscribe(instance.user.email) -
How to display 2 views in one template
i am doing attendance system. So the homepage will display a table of class group. And the class name is a link to go to the respective class list to display the names. I managed to transfer the information of the class from the table in homepage, but unable to display the student's name of respective class. Been stuck in this prob fr days. i already tried to put 2 views in one template, already tried to pass two parameters to the URLs but failed. Already try to retrieve two models under one template, failed. The code that i have now is the code that is able to retrieve the the group info from the table. the group info is one table in database, and the student name is another table in table. classGrp is the fk in student table. def class_Details(request,id=None): context={} try: disp = GroupInfo.objects.get(id=id) except: raise Http404 context['disp'] = disp #context['names'] = names return render(request,'namelist.html',context) eg: i have one class named FEP2, day: tues and time 1030. When i clicked on FEP2, it should bring me to the name list page which will pass over that 3 information as well as the list of student name. Right … -
Adjusted clean function in form template does not pass errors to the form
I have a custom search form with 3 input fields (last_name, first_name and client_id) for searching a client and if successful redirect to client page or show a list of multiple clients if the client is not unique. Basic functionality: either use one or both name fields OR the client_id field for retrieving client(s) information (via AJAX call from database) if client_id field is used: the result is always unique and redirection to page of the client if name fields are used: the result can be unique (followed by redirection to the page of the client) or can be a list of clients (show a modal with list of the clients so we can choose one and redirect) The form works with the AJAX call, but the error handling does not work. The errors are not shown in the html form, except for the error.message. form in html: <form class="p-3" id="client_selection"> {% csrf_token %} {% if form.non_field_errors %} <div class="alert alert-danger" role="alert"> {% for error in form.non_field_errors %} {{ error }} {% endfor %} </div> {% endif %} <div class="form-group row justify-content-md-center"> <label for="last_name" class="col-2 col-form-label text-left">Name:</label> <div class="col-4"> <input type="text" class="form-control" id="last_name" placeholder="Eingabe des Namen"> </div> {{ form.last_name.errors }} … -
Django: how to query parent model based on a filter of a child model?
I have those classes (simplified for sake of clarity): class Entity(models.Model): adresses = models.ManyToManyField(Address, related_name='persons', through='EntityAddress') class EntityAddress(models.Model): entity = models.ForeignKey(Entity, on_delete=models.CASCADE, blank=False, null=False) address_type = models.ForeignKey(AddressType, models.CASCADE, blank=False, null=False) address = models.ForeignKey(Address, on_delete=models.CASCADE, blank=False, null=False) class Address(models.Model): summary = models.CharField(max_length=250, blank=True, null=True) way = PolygonField(default=None, blank=True, null=True) class Person(Entity): user = models.OneToOneField(User, blank=False, null=False, on_delete=models.CASCADE) I want to have all Person's whose addresses have a "not null" way. I do it like this: for p in Person.objects.all(): for e_a in EntityAddress.objects.filter(entity=p, address__way__isnull=False,): # do whatever here: pass This is way too slow! Is there a way to make only one request? -
Auto backup postgres db on django 2
I want make a function for making auto backup for specific database in postgresql , I can do that manually by terminal commend, but that is not a good way for backing up for long term, after thinking about this issue I found 2 solutions : execute postgres backup commend from a function in terminal Backup postgres code for django 2 I search for both of theme in google and stackoverflow but unfortunately I didn't find any code or guide for solve this problem I hope from exporters of django & python telling me which way is more convention and better and if you have any example or guide line, please share it for the beginners developers like me -
How can I automaticly concatenate Html files clientside?
I trying to build a website that serves mostly static content, aside from raw data. Which means that instead of having the web server create the raw HTML code from data from the database, I want the server to send an initial static frame website that contains js code which then loads the data and posts and such from a REST API on the server and builds the posts on the website from that. The ultimate goal of this approach is that the browser ultimately caches the site after the first download and from then on only has to load raw data from the server, thus easing the strain on the server. The problem with this approach is theres no elegant way to serve the basic framework elements of the page (header, body, footer, etc ) piecemeal without using some form of autoconcatenation, like djangos templates for example, which I am purposefully trying to avoid for the above reasons. I know a while ago chrome introduced <link href="extern.html" rel="import" /> which would be absolutely perfect, but unfortunately I doesn't work on most browsers (even chrome without config changes). So basicly the question is, how do elegantly serve exclusively static web … -
Django Admin - 'bool' object is not callable
When I try and delete records within Django Admin, for some records, I am getting 'bool' object is not callable I cannot work out where the error is based on this Traceback. Traceback: File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/contrib/admin/options.py" in wrapper 575. return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/contrib/admin/sites.py" in inner 223. return view(request, *args, **kwargs) File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 62. return bound_func(*args, **kwargs) File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func 58. return func.__get__(self, type(self))(*args2, **kwargs2) File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/contrib/admin/options.py" in delete_view 1736. return self._delete_view(request, object_id, extra_context) File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/contrib/admin/options.py" in _delete_view 1760. [obj], opts, request.user, self.admin_site, using) File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/contrib/admin/utils.py" in get_deleted_objects 131. collector.collect(objs) File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/contrib/admin/utils.py" in collect 195. return super().collect(objs, source_attr=source_attr, **kwargs) File "/home/henry/Documents/Sites/Development/django-authenticjobs/env/lib/python3.6/site-packages/django/db/models/deletion.py" in collect 222. field.remote_field.on_delete(self, field, sub_objs, self.using) Exception Type: TypeError at /admin/jobboard/job/155/delete/ Exception Value: 'bool' object is not callable Can anyone suggest where to look? Thank you -
Is there a way to get the 100 maximum values of all keys in JSON field using Django ORM?
Let's say, I have a JSON field with historical data in the format: {'04-Sep-19': 56456, '03-Sep-19': 12551, '02-Sep-19': 1616, '01-Sep-19': 0, '31-Aug-19': 16161, } Is there an elegant way to query the database with Django ORM to get the 100 maximum values from this JSON field of any key length? -
Django Tables 2: showing week row and grouping items?
I'm using Django Tables 2 to build a simple table with my items, which have a start and end date. Now I would love to group my items by the week they start and show a row above every group which spans the whole table and displays a text like "Week 1 from xx.xx.xxxx to xx.xx.xxxx" So that it would look something like this: My code looks like this so far: Tables.py class ItemTable(AdminTable): class Meta(AdminTable.Meta): model = Discount fields = ('id', 'category', 'start', 'end') order_by = ('end',) The AdminTable class itself does nothing fancy, it inherts from tables.Table and sets every thead of all my tables to a bootstrap css class. Views.py class ItemIndex(SingleTableMixin, FilterView): model = Item table_class = ItemTable template_name = 'accounting/item/item_index.html' Would that even be possible to do with django tables 2? If so, how can I add this custom row to my table? Thanks for all answers! -
How to use prepopulated_field with email without omitting special characters in django admin
I'm trying to prepopulate username with email in django admin but it escapes '@' and '.' Admin.py class UserAdmin(UserAdmin, ImportExportModelAdmin): add_form = UserCreateForm prepopulated_fields = {'username': ('email',)} inlines = [SitePermissionInline] add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('first_name', 'last_name', 'email','username', 'password1', 'password2', ), }), ) In admin form if email is test@test.com, username returns testtestcom. I want username to prepopulate the email as it is i.e username - test@test.com -
How can you replace Redux by the react ContextAPI in a Django App
I recently learned how to mimic the redux behavior with the use of createContext(). I know how to use the react contextAPI and react hooks. But now, I try to connect both django and react, but every tutorials are mentioning Redux. How can I replace Redux by createContext + react hooks ? -
Getting key error while setting and getting cookie
I'm getting a weird exception while setting and getting the cookie in Django. I'm getting key error while trying to print the cookie value. Could someone please tell me the reason by looking at the stack trace http://dpaste.com/3M3ZKXW def sessionHandler(request): userName = request.GET.get('uname') response = HttpResponse("Setting the cookie now") response.set_cookie('cookie_user_name', userName) return JsonResponse({'Response': 'success'}) def login(request): cookie_user = request.COOKIES['cookie_user_name'] print("################################") print(cookie_user) UserName = {"Name": global_user_name} return render(request, 'login/login.html', UserName) Exception Type: KeyError at /NewHandBook/welcome Exception Value: 'cookie_user_name'