Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Migrate issue: after successful miration, my table is not showing up
I created a new table in my models.py file: class Member_Assessment(models.Model): assessment = models.ForeignKey('Assessment', on_delete=models.SET_NULL, null=True, blank=True) date_submitted = models.DateTimeField(auto_now=True) submitted = models.BooleanField() I then run makemigrations and migrate: Migrations for 'app': app/migrations/0011_auto_20200106_2008.py - Remove field date_submitted from member_response - Remove field submitted from member_response - Alter field response on member_response - Create model Member_Assessment (env) api $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, app, sessions Running migrations: Applying app.0011_auto_20200106_2008... OK Nothing complains but the table does not show up. I check the sqlite file and I see the create table entry when i do a ".fullschema, " but when I try to import I get a: ImportError: cannot import name 'Member_Assessment' from 'app.models' Not sure where to go from here. I did some searching on the issue, but nothing really relevant came back. Anyone have any ideas? EDITED: fixed formatting mistake -
Why user.is_superuser returns string in Django template?
Hello I am working with a template in which I want to display or hide a block of html depending if the user is superUser or not. The code is the following: <h1> What user.is_superuser returns: {{ user.is_superuser }}</h1> {% if user.is_superuser %} <h1>Superuser</h1> {% else %} <h1>Mindundi</h1> {% endif %} The idea is to show "Superuser" to the superusers or "mMindundi" otherwise. But here is the output I am getting: I have been pulling my hair out and can't find a solution. I know the problems come with the ```"0"````being a string instead a int, so everything get parsed to True... Why is this happening??? I know a fix would be parsing it to int... but I want to fix it other way if possible. For reference, I am using these packages: asgiref==3.2.3 certifi==2019.6.16 chardet==3.0.4 defusedxml==0.6.0 Django==2.2.3 django-markdownx==2.0.28 django-model-utils==3.2.0 docxtpl==0.6.3 idna==2.8 Jinja2==2.10.1 lxml==4.3.4 Markdown==3.1.1 MarkupSafe==1.1.1 oauthlib==3.0.2 Pillow==6.1.0 PyJWT==1.7.1 python-docx==0.8.7 python-social-auth==0.3.6 python3-openid==3.1.0 pytz==2019.1 requests==2.22.0 requests-oauthlib==1.2.0 six==1.12.0 social-auth-app-django==3.1.0 social-auth-core==3.2.0 sqlparse==0.3.0 urllib3==1.25.3 xlrd==1.2.0 -
Limit List Display Results in Django-Admin Changelist to certain users
Currently in my web application using Django, I am building an application for internal employees to submit forms with data elements. Each form is one record. In the Model Admin Changelist, I've enabled the below fields in admin.py to be shown in a table and allow filtering: list_display=( 'week_ending_date', 'ba_name', 'entered_date', 'category_id', 'activity_description', 'estimated_time', 'actual_time', 'unplanned_time', 'total_time_worked', 'jira_number', ) list_filter=( ('week_ending_date', DateRangeFilter), ('entered_date', DateRangeFilter), ('ba_name'), I am trying to limit the results that appear to an end user inside the Django Admin Changelist. Currently, the functionality works if the current user is the one making the request. i.e. if I'm the current user, I only see my records that I've submitted. How would I go about making it so that ANY user can see ALL records in the changelist EXCEPT those of a super user? class BurndownFormAdmin(admin.ModelAdmin, CsvExport): def save_model(self, request, obj, form, change): obj.user = request.user super(BurndownFormAdmin, self).save_model(request, obj, form, change) def get_queryset(self, request): query_set = super(BurndownFormAdmin, self).get_queryset(request) if request.user.is_superuser: return query_set return query_set.filter(ba_name=request.user) -
All errors appear as ImproperlyConfigured exception in Pycharm run console
I've had a problem which I think is a configuration issue with my Pycharm installation or environment, but I've re-downloaded pycharm with different versions and it doesn't work. My problem is, that every error I get (any exception) is not properly informed to me in the run console. So, for example, if I have faulty code like: value = 5 print(value) The run console wouldn't display the correct error (ValueError), but instead, this: The console displays that error whenever I get any error. When there is no error, the code runs perfectly fine, and I know the error is not on my urls.py being misconfigured, I checked many times, and it runs fine on my co-workers machines. I haven't been able to find any information on this issue, which I find very strange. I can work on the project, but whenever there's an error, I have trouble finding it and therefore fixing it. Any help would be appreciated, I'm a bit lost here. I'm using Python 3.6, PyCharm version 2019.3.1, and Windows 10. -
Django view doesn't receive Json data?
Using a simple Python script, i want to send a request, with Python-Requests, to a Django view. The Django view should receive the json data inside the request and should print it to my console; here is what i tried: This is how i send the request: url = 'http://127.0.0.1:8000/myview/view' client = requests.session() csrftoken = requests.get(url).cookies['csrftoken'] data = json.dumps({'data': 'test-value'}) header = {'X-CSRFToken': csrftoken} cookies = {'csrftoken': csrftoken} resp = requests.post(url, data=data, headers=header, cookies=cookies) And this is how the Django view receives it: def myview(request): if request.method == 'POST': data = request.POST.get('data') print(data) print('received.') response = HttpResponse(get_token(request)) return response The problem with my current code is that print(data) will throw the following output: None received. [06/Jan/2020 21:23:57] "POST /myview/view HTTP/1.1" 200 64 So, instead of printing test-value, it prints nothing. I don't understand whether the error is in my Django view or in how i'm sending the request. Any advice is appreciated! -
ConnectionError deploying django app heroku
I'm having this Connection error deploying my django app on Heroku: ConnectionError at /admin/login/ HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /authentication/login/ (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 111] Connection refused',)) Exception Value: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /authentication/login/ (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 111] Connection refused',)) It seems that the app doesn't find the url where the login must be done but the file setings.py is correct: """ Django settings for decide project. Generated by 'django-admin startproject' using Django 2.0. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.0/ref/settings/ """ import os import django_heroku # 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/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '^##ydkswfu0+=ofw0l#$kv^8n)0$i(qd&d&ol#p9!b$8*5%j1+' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'django_filters', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_swagger', 'gateway', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.QueryParameterVersioning' … -
Multi-tenancy Django in Production
I'm looking at building a new SaaS in Django but I feel I need a bit of extra information on this. So I understand majority of the multi-tenant information via stack and google but what i'm looking to find out if its indeed possible to build a SaaS hosting platform. I have my main project folder, once i've built this, I understand that I will need to put this into production / build and get it up. The issue that i'm wondering is, if its possible to create a unique instance then from this app e.g client wants a website, domain name, additional features that will easily automate the website and from what i've seen online, it appears that if i wanted to add a new client every time that i would need to edit a file in the dns server which to be honest I can't be doing, this side needs to be on the frontend. if anyone can be kindful enough to point me in the right direction, it would be greatly appreciated. -
Cannot load static files in django
I add the following line in settings.py file STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR,"static"), ] STATIC_ROOT = os.path.join(BASE_DIR,"static") then I edited my html file use({% load static %}) and but still I am not able to see my ABC pic on my webpageScreenshots of .py files -
Django - runserver - [Errno 111] Connection refused
I am not sure what happened to my project. I left it for a couple of months, then when I come back and I runserver I get this error: Exception in thread django-main-thread: Traceback (most recent call last): File "/home/safaltaya/Proyectos/blockchain_python/lib/python3.6/site-packages/urllib3/connection.py", line 157, in _new_conn (self._dns_host, self.port), self.timeout, **extra_kw File "/home/safaltaya/Proyectos/blockchain_python/lib/python3.6/site-packages/urllib3/util/connection.py", line 84, in create_connection raise err File "/home/safaltaya/Proyectos/blockchain_python/lib/python3.6/site-packages/urllib3/util/connection.py", line 74, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused I tried running the server in different ports, didn't work. -
Testing Django View Functions
I am currently trying to create unittests for the functions that I have written inside views.py. However, I have not been able to find the proper way to do so. Here is what I have so far for example: views.py: class SalesListView(LoginRequiredMixin, TemplateView): def get_month(self): if self.request.GET.get('month'): d = datetime.strptime(self.request.GET.get('month'), '%Y-%m') else: d = datetime.today() return d and I am attempting to test it like so: tests.py: class ViewFunctionsTests(TestCase): def test_saleslistview(self): self.request = Mock(session={'month': '2019-11'}, method='GET') view = SalesListView() self.assertEqual(view.get_month(), '2019-11') However this returns an AttributeError stating: AttributeError: 'SalesListView' object has no attribute 'request' Would anybody have any suggestions on the correct way to test view functions such as the one above? Thank you ahead of time. -
*** AttributeError: 'Class Name' object has no attribute 'request' from web app request
I'm using an endpoint where I added pagination, so in the DRF API View works good but when I call it from the web App it returns me *** AttributeError: 'Class Name' object has no attribute 'request' I explain details below. This is my api.py class StandardResultsSetPagination(PageNumberPagination): page_size = 10 class SearchViewSet(viewsets.ModelViewSet): ''' Class related with the Search Model, that is a tracking model where you could find recently search by user. ''' queryset = Search.objects.filter( is_active=True, is_deleted=False ).order_by('id') permission_classes = [ permissions.AllowAny ] pagination_class = StandardResultsSetPagination def __init__(self,*args, **kwargs): self.response_data = {'error': [], 'data': []} self.data = {} self.code = 0 def get_serializer_class(self): if self.action in ['recent_search']: return RecentSearchAPISerializer return SearchSerializer @validate_type_of_request @action(methods=['post'], detail=False) def recent_search(self, request, *args, **kwargs): ''' - POST method (recent_search): get user recent search - Mandatory: user, social_network_id ''' try: serializer = SearchSerializer( data=kwargs['data'], fields=['social_network','user']) if serializer.is_valid(): queryset = Search.objects.filter( is_active=True, is_deleted=False, social_network=kwargs['data']['social_network'], user_id=kwargs['data']['user']).order_by('id').reverse() page = self.paginate_queryset(queryset) if page is not None: serializer = SearchSerializer(page, many=True, fields=( 'id','word','polarity','liked','shared','searched_date')) self.data['recently_search'] = json.loads(json.dumps(serializer.data)) self.code = status.HTTP_200_OK self.response_data['data'].append(self.data) return self.get_paginated_response(serializer.data) serializer = SearchSerializer(queryset, many=True, fields=( 'id','word','polarity','liked','shared','searched_date')) self.data['recently_search'] = json.loads(json.dumps(serializer.data)) self.code = status.HTTP_200_OK self.response_data['data'].append(self.data) else: return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) except Exception as e: logging.getLogger('error_logger').exception("[API - RecentSearchTwitterView] - Error: " + str(e)) … -
How to make a django user inactive and invalidate all their sessions
To make a user inactive I usually do: User.objects.get(pk=X).update(is_active=False) However, this doesn't log out the user or do anything session-related. Is there a built-in in django to make a user immediately inactive, or what would be the best way to accomplish this? One similar answer is this: https://stackoverflow.com/a/954318/651174, but that doesn't work great if there are millions of sessions (it's a brute force way iterating over all sessions). Though this is from 2009, so hopefully there's a better way as of today. -
Using dot env file in django. It throws the error even though i have installed package?
django.core.exceptions.ImproperlyConfigured: Set the db_password environment variable How to create dot env file I did install pip install django-environ -
Django - Filter when Case is false
I have a model Article. That should be filtered. Here's the condition: If the request is NOT an author, all articles with pub_date lte now will be visible. If the request is an author, all articles with pub_date lte now will be visible PLUS articles from the authors (regardless of pub_date). In simple language: Everyone should only see the articles, which hasn't been published, but authors can also see their articles. I thought I could annotate the articles and then somehow filter on them, but I have no idea how to continue or how to do it. authors is a m2m field. articles = articles.annotate( can_see=Case( When(authors__id__in=[request.user.id], then=Value(True)), default=False, output_field=BooleanField() ) ) -
How to pass javascript variable to a django template tag
I have created a template tag and that will accept 2 arguments, returns a text. Currently, I am not able to pass a javascript variable value to django template tag. can you help me over here? javascript code with template tag function formatState (state) { if (!state.id) { return state.text; } console.log(state.text); var x = "{% get_data state.text 'account' %}"; var $state = $('<span class="badge">' + x + '</span>'); return $state; } Template Tag @register.simple_tag def get_data(value, module): ***** x = "hello" return x -
How to create a list with dynamic variables
I have a standard urlpatterns that I use for every model I want to provide CRUD for: E.g. for the model Company this is: urlpatterns = [ path('company/create', CompanyCreate.as_view(), name='company_create'), path('company/list', CompanyList.as_view(), name='company_list'), path('company/detail/<int:pk>/', CompanyDetail.as_view(), name='company_detail'), path('company/update/<int:pk>/', CompanyUpdate.as_view(), name='company_update'), ] For the model Person this is: urlpatterns = [ path('person/create', PersonCreate.as_view(), name='person_create'), path('person/list', PersonList.as_view(), name='person_list'), path('person/detail/<int:pk>/', PersonDetail.as_view(), name='person_detail'), path('person/update/<int:pk>/', PersonUpdate.as_view(), name='person_update'), ] Is there a way I can shortcut building URL patterns like this by just providing a model_name input? E.g. model_list = ['company','person','car'] for model in model_list: urlpatterns = [ path('%s/create', %sCreate.as_view(), name='%s_create' %model), path('%s/list', %sList.as_view(), name='%s_list' %model), path('%s/detail/<int:pk>/', %sDetail.as_view(), name='%s_detail' %model), path('%s/update/<int:pk>/', %sUpdate.as_view(), name='%s_update', %model), ] -
How can i sign in c# with my django data?
I wrote a website with django, it has users with Usernames and Passwords I want sign in to my c# windows forms application with using this data. I am beginner. Which way should I follow. I've researched these issues but I don't understand anything: json restapi restframework -
Celery beat runs every minute instead of every 15 minutes
I'm setting my celery to have the schedule CELERYBEAT_SCHEDULE = { 'update_some_info': { 'task': 'myapp.somepath.update_some_info', 'schedule': crontab(minute='15/*'), }, } when checking what's actually written in crontab, it's indeed <crontab: */15 * * * * (m/h/d/dM/MY)> but my celery log indicates that the task is running every minute INFO 2020-01-06 13:21:00,004 beat 29534 139876219189056 Scheduler: Sending due task update_some_info (myapp.somepath.update_some_info) INFO 2020-01-06 13:22:00,003 beat 29534 139876219189056 Scheduler: Sending due task update_some_info (myapp.somepath.update_some_info) INFO 2020-01-06 13:23:00,004 beat 29534 139876219189056 Scheduler: Sending due task update_some_info (myapp.somepath.update_some_info) INFO 2020-01-06 13:24:28,255 beat 29534 139876219189056 Scheduler: Sending due task update_some_info (myapp.somepath.update_some_info) Why isn't celery beat picking up my schedule? -
Error in Django Password Reset: Not getting the NorReverseMatch Error
I am working with Django 3.0, and I am using Atom as my editor, to do password reset in django i am not getting the error NoReverseMatch when i did not pass the password_reset_confirm route in urlpattern. Instead after going to password-reset template I am getting redirect to password-reset/done template with no error, and i am not receiving any mail, can anyone tell why am i not getting that error even though i did not mention the path for password_reset_confirm route. my urlpattern =[ ............... ............... path('password-reset/', auth_views.PasswordResetView.as_view(template_name="users/password_reset.html"), name="password_reset"), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name="users/password_reset_done.html"), name="password_reset_done"), ] Can anyone please tell why am I not getting the error? -
Linking a model to two models with primary key in Django
I'm trying to create a model that has a kind of either type relation to two models. Assume we have a Book and Article models: Class Book(models.Model): book_name = models.CharField(max_length=50) Class Article(models.Model): article_name = models.CharField(max_length=50) Now what we have in a portfolio is either a book or an article. How should I define this relationship in the model? Class Portfolio(models.Model): book = models.ForeignKey(Book, on_delete=models.PROTECT) article = models.ForeignKey(Article, on_delete=models.PROTECT) This obviously doesn't satisfy what I'm looking for. -
Django Dynamic Formset UpdateView Not Updating
I used this tutorial to successfully set up a dynamic inline formset using Django. The CreateView works great, but I cannot get the UpdateView to actually update the related fields. There are no errors thrown, but the items will not update. I believe I have isolated the error to the form_valid function. The code is as follows. Thank you for any assistance. class ApplicantCreate(CreateView): model = Applicant success_message = 'Your application was submitted successfully.' form_class = forms.ApplicantForm template_name = 'careers/add_applicant.html' success_url = reverse_lazy('careers:thanks') def get_context_data(self, **kwargs): data = super(ApplicantCreate, self).get_context_data(**kwargs) positions = super(ApplicantCreate, self).get_context_data(**kwargs) if self.request.POST: data['employer'] = forms.ApplicantEmployerFormSet( self.request.POST, prefix='employer') data['education'] = forms.ApplicantEducationFormSet( self.request.POST, prefix='education') else: data['employer'] = forms.ApplicantEmployerFormSet(prefix='employer') data['education'] = forms.ApplicantEducationFormSet(prefix='education') return data context['unfilled_positions'] = Position.objects.filter(filled=False) return positions def form_valid(self, form): context = self.get_context_data() employer = context['employer'] education = context['education'] with transaction.atomic(): form.instance.created_by = self.request.user self.object = form.save() if employer.is_valid(): employer.instance = self.object employer.save() if education.is_valid(): education.instance = self.object education.save() return super(ApplicantCreate, self).form_valid(form) def get_success_url(self): return reverse_lazy('careers:thanks') class ApplicantUpdate(SuccessMessageMixin,LoginRequiredMixin,GroupRequiredMixin,UpdateView): group_required = [u'careers-admin',u'careers'] model = Applicant success_message = '%(first_name)s %(last_name)s was updated successfully.' form_class = forms.ApplicantUpdateForm template_name = 'careers/edit_applicant.html' def get_context_data(self, **kwargs): data = super(ApplicantUpdate, self).get_context_data(**kwargs) positions = super(ApplicantUpdate, self).get_context_data(**kwargs) if self.request.POST: data['employer'] = forms.ApplicantEmployerFormSet( self.request.POST, instance=self.object, prefix='employer') data['education'] … -
Mapping Existing Database Objects in Python
I have an existing database, I would like to use some kind of mapping library that will allow me to represent Objects dynamically in python and have the database functionality built in to them. I'm imagining it would work like this: class Car(ORM_Thing): def __init__(self, color): self.color = color c = Car("Red", <connection string>) c.commit() print(c) >>> Red Car with ID 255 I hope this is making sense -
How to run django files in another virtualenv environment on another server?
I am in the process of moving a site created in django to another server. I have packed all files into a zip package, created a new virtualenv environment on a second server, and dumpdate into a .json file. I already have all the files on the destination server, but unfortunately I don't know what to do next. How to run django in the new virtualenv environment? Should I extract the files to a folder with the new virtualenv? If so, do I have to activate virtualenv first? I will also add that migration takes place from two different systems. From windows on ubuntu. -
Map certain data to models in Django
Say I have a movie database. I want to map films of Quentin Tarantino to Quentin Tarantino. But given that Quentin only makes Historical Dramas (consider this a genre), I should only be able to map Historical Dramas to Quentin. How do I achieve this without creating a special model just for that genre? Consider you have a singular Genre model. -
GORM's 'Has Many' association not creating a foreign key?
Following an example in GORM's documentation (http://gorm.io/docs/has_many.html#Has-Many), I attempted to make a User and CreditCard model with a one-to-many relation: package main import ( "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/sqlite" "github.com/sirupsen/logrus" ) type User struct { gorm.Model CreditCards []CreditCard } type CreditCard struct { gorm.Model Number string UserID uint } func main() { db, err := gorm.Open("sqlite3", "examplegorm.db") if err != nil { logrus.Fatalf("open db: %v", err) } defer db.Close() db.LogMode(true) db.AutoMigrate(&User{}) db.AutoMigrate(&CreditCard{}) } However, in resulting logged SQL statements I don't see something like CREATE TABLE credit_cards( ... FOREIGN KEY(user_id) REFERENCES users(id) ) as I would expect from SQLite's documentation (https://www.sqlite.org/foreignkeys.html). What I see is > go run gorm_has_many.go (/Users/kurt/Documents/Scratch/gorm_has_many.go:28) [2020-01-06 09:05:58] [0.82ms] CREATE TABLE "users" ("id" integer primary key autoincrement,"created_at" datetime,"updated_at" datetime,"deleted_at" datetime ) [0 rows affected or returned ] (/Users/kurt/Documents/Scratch/gorm_has_many.go:28) [2020-01-06 09:05:58] [0.55ms] CREATE INDEX idx_users_deleted_at ON "users"(deleted_at) [0 rows affected or returned ] (/Users/kurt/Documents/Scratch/gorm_has_many.go:29) [2020-01-06 09:05:58] [0.52ms] CREATE TABLE "credit_cards" ("id" integer primary key autoincrement,"created_at" datetime,"updated_at" datetime,"deleted_at" datetime,"number" varchar(255),"user_id" integer ) [0 rows affected or returned ] (/Users/kurt/Documents/Scratch/gorm_has_many.go:29) [2020-01-06 09:05:58] [0.50ms] CREATE INDEX idx_credit_cards_deleted_at ON "credit_cards"(deleted_at) [0 rows affected or returned ] By contrast, in an example Django project in a djangoapp app, if I have the following models.py: …