Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I don't know how to fix module 'adoptme.views' has no attribute 'addfriends'
from django.conf.urls import url from django.contrib import admin from adoptme import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^addfriends', views.addfriends, name='friends'), url('', views.home, name='home'), ] This is the code that has the problem -
Receiving POST data in Django from Vue
Doing post request from vue. And trying to collect the data in Django view then save() it into mysql table. But it's not working as expected. in views.py from ..models import project def insertProjects(request): projectModel = project.Project() if request.method == "POST": projectModel.project_id = request.POST.get("project_id") projectModel.project_name = request.POST.get("project_name") projectModel.company_name = request.POST.get("company_name") projectModel.save() return HttpResponse(True) in Vue.js postProjects(projects){ projects.data.forEach(project => { let payload = { project_id: project.gid, project_name: project.name, company_name: "" } axios.post(API_HANDLER.database_api+"v2/insert_projects", payload) .then(response => { console.log(response); }) .catch(err => { console.log(err); }) }); }, Let me make it clear about Vue side. The POST code is working without a doubt. I used it in .php backend. I think the problem is receiving and saving the data in Django's views. -
How to link index to signup page?
I want to open the signup page through a button which I have made in index.html and I have given a link of signup but it is showing me that page is not found. Where is the problem? views.py def signup(request): return render(request, 'users/signup.html'); main url page urlpatterns = [ path('', include('app1.urls')), path('admin/', admin.site.urls), path('users/', include('users.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) app url page urlpatterns = [ path('signup', views.signup, name='signup') ] index.html <p><a href="{% static 'signup' %}" class="btn btn-primary">Signup</a></p> Folder structure -
How to get data from another model in Detailview?
I want to get data in another model in detailview. I have two models is classroom model and student model. My model class Classroom(models.Model): roomname = models.CharField(max_length=255) number = models.IntegerField(default=0) roomlogo = models.ImageField() def preview(self, request): return render_to_string( "classroom /classroom_preview.html", {"classroom": self} ) def __str__(self): return self.roomname class Student(models.Model): studentname = models.CharField(max_length=255) number = models.CharField(max_length=255) picture = models.ImageField(blank=True) classroom= models.ForeignKey(ClassRoom, on_delete=models.SET_NULL, null=True) def __str__(self): return self.studentname My urls.py urlpatterns = [ path("", ClassroomListView.as_view(), name="class"), path("<str:slug>", ClassroomDetailView.as_view(), name="classroom"), ] My view.py class ClassroomListView(ListView): model = Classroom class ClassroomDetailView(DetailView): model = Classroom def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["student_in_room"] = Student.objects.all() return context My classroom_preview.html <a href="{% url 'classroom' classroom.slug %}" class="link-wrapper"> <div style="padding: 0.5rem;" class="center"> <h5>{{ classroom.name }}</h5> </div> </a> My classroom_detail.html {{ object.roomname }} // name classroom // {% for student in student_in_room %} <h4>name : {{ student.studentname }}</h4> <h4>number : {{ student.number }}</h4> {% endfor %} My problem is Every classroom is show Duplicate student. exam is show // When clicked science room SCIENCE ROOM [ this picture ] name : nanny number : 1 [ this picture ] name : lily number : 2 [ this picture ] name : john number : 1 [ this picture ] … -
'<' not supported between instances of 'int' and 'str'
I'm sorry. This error is driving me crazy. I just updated from Django's 1.11 to 2.0 and I'm unable to trace this simple casting error. The traceback does not mention any part of my code... I know what the error means. I'm just unable to find where is the issue in my code. This error occurs when creating or editing the entry. Thru shell I can create the object just fine. Traceback: File "/home/rodrigo/Workspace/VirtualEnvs/firetail/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/home/rodrigo/Workspace/VirtualEnvs/firetail/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/home/rodrigo/Workspace/VirtualEnvs/firetail/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/rodrigo/Workspace/VirtualEnvs/firetail/lib/python3.7/site-packages/django/contrib/admin/options.py" in wrapper 574. return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/rodrigo/Workspace/VirtualEnvs/firetail/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/home/rodrigo/Workspace/VirtualEnvs/firetail/lib/python3.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/home/rodrigo/Workspace/VirtualEnvs/firetail/lib/python3.7/site-packages/django/contrib/admin/sites.py" in inner 223. return view(request, *args, **kwargs) File "/home/rodrigo/Workspace/VirtualEnvs/firetail/lib/python3.7/site-packages/django/contrib/admin/options.py" in change_view 1556. return self.changeform_view(request, object_id, form_url, extra_context) File "/home/rodrigo/Workspace/VirtualEnvs/firetail/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapper 62. return bound_func(*args, **kwargs) File "/home/rodrigo/Workspace/VirtualEnvs/firetail/lib/python3.7/site-packages/django/utils/decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "/home/rodrigo/Workspace/VirtualEnvs/firetail/lib/python3.7/site-packages/django/utils/decorators.py" in bound_func 58. return func.__get__(self, type(self))(*args2, **kwargs2) File "/home/rodrigo/Workspace/VirtualEnvs/firetail/lib/python3.7/site-packages/django/contrib/admin/options.py" in changeform_view 1450. return self._changeform_view(request, object_id, form_url, extra_context) File "/home/rodrigo/Workspace/VirtualEnvs/firetail/lib/python3.7/site-packages/django/contrib/admin/options.py" in _changeform_view 1498. return self.response_change(request, new_object) File "/home/rodrigo/Workspace/VirtualEnvs/firetail/lib/python3.7/site-packages/django/contrib/admin/options.py" in response_change 1239. self.message_user(request, msg, messages.SUCCESS) File … -
Confusion with reactjs,django & graphql api architecture
I had spent sometime reading about ReactJS, Django, Django REST, Graphql. I planned to use ReactJS as frontend, Django as backend, but i have some interest in using GraphQL too. Should i mixing RestAPI (Authentication) & GraphQL (Data) or purely GraphQL? This is what i think React http request to Django via RestAPI (React form) RestAPI to authenticate? JWT? Everytime request pass the JWT to check authentication and Graphql response?? I got a lot of confusion here. Thanks in advanced -
Save function not working with my model in django
NameError at /admin/todo/todomodel/add/ name 'unicode' is not defined Request Method: POST Request URL: http://127.0.0.1:8000/admin/todo/todomodel/add/ Django Version: 2.2 Exception Type: NameError Exception Value: name 'unicode' is not defined Exception Location: C:\Users\PEE TEE\Desktop\ToDoApp\lib\site-packages\slugify.py in slugify, line 24 Python Executable: C:\Users\PEE TEE\Desktop\ToDoApp\Scripts\python.exe Python Version: 3.7.6 Python Path: ['C:\\Users\\PEE TEE\\Desktop\\ToDoApp\\src', 'C:\\Users\\PEE TEE\\Desktop\\ToDoApp\\Scripts\\python37.zip', 'C:\\Users\\PEE TEE\\Desktop\\ToDoApp\\DLLs', 'C:\\Users\\PEE TEE\\Desktop\\ToDoApp\\lib', 'C:\\Users\\PEE TEE\\Desktop\\ToDoApp\\Scripts', 'c:\\users\\pee tee\\appdata\\local\\programs\\python\\python37\\Lib', 'c:\\users\\pee tee\\appdata\\local\\programs\\python\\python37\\DLLs', 'C:\\Users\\PEE TEE\\Desktop\\ToDoApp', 'C:\\Users\\PEE TEE\\Desktop\\ToDoApp\\lib\\site-packages'] Server time: Tue, 4 Feb 2020 03:03:37 +0000 And this is my model: from django.db import models from django.db.models.signals import post_save from slugify import slugify # Create your models here. def save(self, *args, **kwargs): if self.what_todo and not self.slug: self.slug = slugify(self.what_todo) return super(ToDoModel, self).save(*args, **kwargs) def __str__(self): return str(self.what_todo) -
django.db.utils.OperationalError: unable to open database file error
I am new to Django. I've installed in virtual env in ubuntu. Whenever i am trying to run python3 manage.py runserver i am getting the following error File "/home/aashish/Python/Django/project_env/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 199, in get_new_connection conn = Database.connect(**conn_params) django.db.utils.OperationalError: unable to open database file This is my database code in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } How to debug this? Thank you in advance! -
How to perform conditional column update in Django Tastypie
I want to update count conditionally, if count = 1, update count = 10. class HelloModel(Model): count = models.IntegerField() class HelloModelResource(Resource) def obj_update(self, bundle, request=None, **kwargs): Is obj_update() right place to update? How to update? -
Preloader loads behind block content and navbar
I have a preloader in which is loading in front of the <body> but not in front of the site navbar or the {% block content %}. #preloader{z-index:999;} <header> <div class="flex-center" id="preloader"> <div class="preloader-wrapper active"> <div class="spinner-grow text-warning" role="status"> <span class="sr-only">Loading...</span> </div> </div> </div> </header> How do I get it to show up above everything on the site? -
Add filters to a Child of a Parent within the View.py
I have a Parent (companies) with many children (charges); with this data, I am listing individual companies with associated charges on a table. All works well (see code below) However, I want to add filters to the charges in view.py; I know I can do this via the template using template conditions, but am finding this limited and cumbersome. For example, I can't find a distinct template condition, and I have to pile through several if conditions for other things, making everything a tad cumbersome when it would be easier if I could do so in view.py Is there a way of adding a filter to the child records as associated with its parent. So Company A has 5 associated charges which I want to filter by date (as an example) - again, I know this can be done via template conditions, but I'm wondering if it can be done in the view Hope that makes sense! from django.shortcuts import render from companies.models import Company, Charge, Filing from django.http import HttpResponse def watch_list(request): companies = Company.objects.order_by('-data_date') return render(request,'company_watch/watch_list.html',{'companies':companies}) {% for company in companies %} <tr> <td>{{company.name}}</td> <td> <ul> {% for charge in company.charge_set.all %} <li>{{charge.charge_id}}</li> {% endfor %} </ul> </td> … -
Django - How to create a shopping list that a family(Group of users) can add and remove items from
I'm fairly new to Django and I am currently trying to make a web app that is for family's to stay in touch and communicate. Currently i'm working on a shopping list that a group of users (Family) can add to. So my question is how would I would I go about creating and adding users to a group of family members and allow them to create a shopping list to add and remove items. Any help would be appreciated. -
python django get data from form
I have form class ReviewForm(forms.ModelForm): title = forms.CharField(max_length=50) review = forms.CharField(widget=forms.Textarea) file = forms.ImageField(widget=widgets.FileInput()) class Meta: model = ReviewModel fields = ['title', 'review', 'file'] if I render it like this(template) - everything is ok, form can be validate and I get data from form. <div class="row justify-content-center"> <div class="col-6"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-success" > Send</button> </form> </div> </div> but I wanna change forms field. If I do like this for example <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% for f in form %} <div class="form-group"> <label for={{ f.label}}>{{ f.label}}</label> <textarea class="form-control" id={{ f.label}}" rows="3"></textarea> </div> {% endfor %} <button class="btn btn-success" > Send</button> </form> form can be render but I couldn't get data from it. This is my piece in view.py def get_review(request): user = request.user if request.method == 'POST': form = ReviewForm(request.POST, request.FILES) if form.is_valid(): r = form.save(commit=False) r.created_by = request.user r.save() return redirect('success') else: form = ReviewForm() return render (request, 'review.html', {'form': form}) End I have extra question: if webpage fils not full(less one page) - everything is ok, but if webpage fils more 1 page(you should scroll it), then every elements a little move. Thanks. -
How to filter Django's foreignKey form dropdown
I have a form that is used to edit (update) a record, and the Author field is automatically a dropdown, which is great, but how do you filter this list? For example, the dropdown is populated with the entire user list. How can I filter this list so that it only shows the items where isDevice == True? accounts/models.py from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): isDevice = models.BooleanField(default = False) ... builds/models.py class BuildQueue(models.Model): Author = models.ForeignKey(CustomUser,blank=True, null= True, on_delete=models.CASCADE) ... forms.py class BuildQueueEditForm(forms.ModelForm): class Meta: model = BuildQueue fields = ['Author','project', 'customer',] views.py class buildQueueEdit(LoginRequiredMixin,UpdateView): model = BuildQueue form_class = BuildQueueEditForm template_name = 'buildQueue_edit.html' -
Django display formated string with tuple data (called only once)
I want to display tuple data in a django template. I want to use a syntax like the Python formated string : print("I have %d referrers and %f cashbacks" % request.user.get_referrer_data()) In this case, request.user.get_referrer_data() is an expensive method, so I want called it only once in my template (despite the fact that I cache its result). Do you know a template syntax that let me inject a tuple in a string ? A code like that would be great : {{ "I have %d referrers and %f cashbacks" | formated_string request.user.get_referrer_data() }} -
Django Model: Bulk create
I have a history model that has a text field, datetime field and user foriegnkey field. Often times I need to bulk create history objects where the text and datetime is the same but for different users. Is there a way to bulk create these objects without using a for loop? class NotificationHistory(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(blank=True, null=True, upload_to='notification/image/') text = models.CharField(max_length=100) seen = models.BooleanField(default=False) -
Is django.utils.timezone.activate() async-safe?
I'm writing an async websocket server using starlette, that uses Django for the database stuff. To ensure Django is aware of the user's timezone in this context, I thought I could write a starlette middleware, similar to this one in Django docs, but I'm not sure if this can cause a race condition, given that concurrent requests get may be served in a single thread. So, is it safe to use activate() from an async context? If not, what should I use instead? -
The *****.objects.all() below are not recognized by python they don't show up in the suggestions when typing. I've tried them both on IDE and console
import datetime from django.db import models from django.utils import timezone class Question(models.Model): def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) def str(self): return self.question_text question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): def str(self): return self.choice_text question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) obj = Question.objects.all() obj2 = models.Model.objects.all() -
Cannot download file from Django under local dev mode
I'm trying to download a file from Django under local development mode. I tried to follow lots of Stackoverflow posts and here is my code of doing so. class AutoPushView(View): def get(self, request, eventId): fileName = '/Users/lbc/DjangoProject/mysite/static/python.png' mimeType, _ = mimetypes.guess_type(fileName) response = HttpResponse(open(fileName, 'rb'), content_type=mimeType) response['Content-Disposition'] = "attachment; filename=%s" % os.path.basename(fileName) return response And I have my urls.py and settings.py as following # urls.py urlpatterns = [ path('<str:eventId>/autopush', views.AutoPushView.as_view(), name='autopush'), ] # settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), '/Users/lbc/DjangoProject/mysite/static/', ] When I invoke the view from a browser (press a HTML button), there's no error shown but the download action is not triggered. What am I missing here? -
Django - Getting a list of fields in a queryset
I need help in getting a list of fields in a Queryset. I am using Django shell to test, but I haven't had any luck. If I do .values like below abc = PrescribedMedsSchedule.objects.filter(medication_date=scheduled_date_obj, medication_time__time=scheduled_time_obj) \ .select_related('prescribed_meds_id') \ .select_related('prescribed_meds_id__childno') \ .values( 'prescribed_meds_id', 'medication_date', 'medication_time', 'quantity', 'form', 'prescribed_meds_id__name_of_medication', 'prescribed_meds_id__childno__child_name', 'prescribed_meds_id__childno__group', 'prescribed_meds_id__childno__line_no' ).order_by('prescribed_meds_id__name_of_medication') I get the exact column names that I can use in the template, when I type abc in shell. Ex: But if I use .only instead of .values, I get a .... How can I retrieve/display the fields/columns in this queryset? The reason I am asking is that the fields in the "select_related" tables no longer appears in the HTML template when I use .only. -
Django - Extending models with multi role users and multiple requirement types
I am new to Django only 2 weeks and I am stuck with scenario I need help with. This is kind of core concept and I apologize in advance for my lack of knowledge. I've extended the base user model like below with multiple roles. Now each role has distinct requirements for their profiles. I need help to understand that how to extend Students or Staff further. There are two scenario I need to extend them. Both can have similar extended models like addresses below. Both can have different extended models like Students have CurrentCourse and Staff does not. Staff has Salary model and Students does not. class User(AbstractUser): is_student = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) dob = models.CharField(max_length=30, blank=True) location = models.CharField(max_length=30, blank=True) class CurrentCourse(models.Model): student = models.OneToOneField(Student, on_delete=model.CASCADE) .... class Staff(models.Model): ROLES = (('Teacher', 'Teacher'), ('Professor', 'Professor'), ('Administration', 'Administration')) user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) role = models.CharField(max_length=100, choices=ROLES) website = models.CharField(max_length=100, blank=True) Both types of Users can have multiple addresses and both Students and Staff needs addressess, not sure how to extend this with ForeignKey. class Address(models.Model): user = ? street = models.CharField(max_length=200) city = models.CharField(max_length=50) country = models.CharField(max_length=50) class Salary(models.Model): staff … -
Return Django Model ChoiceField label in a queryset
The queryset of a model which includes ChoiceField returns the 'value' of the ChoiceField. But I want the 'Label' of the ChoiceField. The queryset is for an ajax request to render a DataTable table. So I'm not able to use the form template get_FOO_display(). class MainBase(models.Model): class MainBaseChoices(models.TextChoices): ACTIVE = '1', 'Active' DEFUNCT = '2', 'Defunct' DUPE = '3', 'Duplicate' INVALID = '4', 'Invalid' user_id = models.AutoField(primary_key=True) user_name = models.CharField(max_length=200, null=False, blank=False) user_status = models.CharField(max_length=10, null=False, blank=False, choices=MainBaseChoices.choices, default=MainBaseChoices.ACTIVE) .... -
Django "Singleton model" to store user settings
I am building a web app with Django. I would like to be able to store final user settings for my app. For now I am using a model Settings that contains all what I need for the app. It seems ok but I don't think that's the right way to do it because I could have a second row in my database and I don't want it. I though about using a file but it is not as easy to manage as a table in a database. Could someone help me with that please ? Thank you ! :) Louison -
Parallel serialization in Django REST Framework? Or other methods of speeding up model serialization?
The app I'm developing needs to deliver a list of ORM objects to the user via a REST endpoint. The list of objects is large - up to 500 or 600 at a time (pagination is not an option). The model looks something like this: class PositionItem(models.Model): account = models.ForeignKey(core_models.Portfolio, on_delete=models.CASCADE) macro_category = models.ForeignKey(MacroCategory, on_delete=models.SET_NULL, null=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) sub_category = models.ForeignKey(SubCategory, on_delete=models.SET_NULL, null=True) I started using a standard ModelSerializer with many=True set, but it was very slow - taking up to 12 seconds to serialize all the objects. I decreased the run time by a few seconds by pre-fetching/caching foreign keys needed for the endpoint with the .select_related() method, and another couple seconds by replacing the ModelSerializer with a custom serializer function that just maps the fields to a dictionary with none of the validation overhead. However, it's still slow (6-7 seconds) and I'd like to optimize further. I thought about trying to parallelize the serializer instead, but am having some problems implementing. My custom serializer looks like this: def serialize_position_record(record): account = record.account macro_category = record.macro_category category = record.category sub_category = record.sub_category return { 'account': account.portfolio_id, 'macro_category': macro_category.macro_category, 'category': category.category, 'sub_category': sub_category.sub_category, 'sorting': { 'macro_category': macro_category.sort_order, … -
Django static files not coming through when deployed to Heroku
My static files are not coming through when I am deploying to Heroku. It works fine when I running on my local. Its not a 404 error, on the network tab it seems like its not even requesting the static files at all. I looked at other solutions and I am already using WhiteNoise. Here is the relevant code from my settings.py import os import environ import django_heroku env = environ.Env( # set casting, default value DEBUG=(bool, False) ) environ.Env.read_env() BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__)) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = (env('DEBUG_VALUE') == "True") # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #my own apps 'corsheaders', 'rest_framework', 'paintings', 'storages', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', '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', ] CORS_ORIGIN_ALLOW_ALL = True ROOT_URLCONF = 't_and_b_website.urls' WSGI_APPLICATION = 't_and_b_website.wsgi.application' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'staticfiles'), ] # STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' #MEDIA_ROOT is for directory for any media that our users upload MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media_cdn') MEDIA_URL = '/media_cdn/' CORS_URLS_REGEX = r'^/api.*' CORS_ORIGIN_ALLOW_ALL = True …