Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django rest framework defaultRouter without models
I am new to Python and Django (rest framework) and I love the DefaultRouter feature, by also giving an "API ROOT" page. But, I can only use the defaultrouter.register() method with viewsets. How to make a custom route without a model? For example I will have a "POST" route that multiplies 2 values from the body. (so body is something like {"value1":123, "value2":456} Is it good practice to use viewsets for everything? How should I implement a custom (multiply) function? I will have a serializer with the 2 params? And where to implement the code? Am I doing things right? -
Load data in memory during server startup in Django app
I am creating a Django app wherein I need to load and keep some data in memory when the server starts for quick access. To achieve this I am using Django's AppConfig class. The code looks something like this : from django.core.cache import cache class myAppConfig(AppConfig): name = 'myapp' def ready(self): data = myModel.objects.values('A','B','C') cache.set('mykey', data) The problem is that this data in cache will expire after sometime. One alternative is to increase the TIMEOUT value. But I want this to be available in memory all the time. Is there some other configuration or approach which I can use to achieve this ? -
Using Q object with variable
I'd like to use the django.db.models.Q object in a way that the query term is coming from a variable. What i'd like to achieve is identical to this: q = Q(some_field__icontains='sth') Obj.objects.filter(q) , but the some_field value should come from a variable: field_name='some_field' q = Q('%s__icontains=sth' % field_name) Obj.objects.filter(q) , but this solution does not give me the correct result of course. I also tried to use dictionary this way: dt = {'%s__icontains' % field_name: 'sth'} q = Q(**dt) Obj.objects.filter(q) , but this also fails on the result. How could I use the Q object using variables as query term? Thanks. -
Django edit form won't validate on form.save() with user field
I recently added a "user" field to my Game model. I can create a new game that works fine; it's when I want to allow a user to edit the instance of a game where I am running into problems. My view is calling the form = GameForm(request.POST, instance=game) where game = Game.objects.get(pk=id). The form is pre-populated with the correct data, but when it's submitted, whether there are updates or not, the form is not validating. It sees it as a POST, but cannot get inside the if form.is_valid() conditional. And this is ever since I added the user field. I am using the default Django User model, and the field name is called "owner." It is set up as a ManyToManyField(User, blank=True) as users can own many games, and games can be owned by many users. Django forms the Many-To-Many "through" table, but I don't want the user to be able to change who owns what. I have it as a hidden field in my forms.py so a user can't change it. Model class Game(models.Model): game_title = models.CharField(max_length=100, verbose_name='Game Title', db_column='game', blank=False, null=False, unique=True) game_developer = models.CharField(max_length=100, verbose_name='Developer', db_column='developer', blank=True, null=True) game_release = models.DateField(max_length=50, verbose_name='Release Date', db_column='release_date', blank=False, null=True) … -
Django: GenericInline combined with ModelMultipleChoiceField
Hi I'm working on an adminform which allows either selecting an existing object or add a new one in an inline of a GenericRelation. See the following example Models: from stdimage class Photograph(DeepZoom): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True) object_id = models.PositiveIntegerField(default=0) profile = GenericForeignKey("content_type", "object_id") img = JPEGField(...) img_alt = models.Charfield(max_lenght=300) ... and class MyProfile(models.Model): name = models.CharField(max_length=200, default="") photos = GenericRelation(Photograph, null=True) To achieve "select existing" I wrote a custom form for the admin site class SomeForm(forms.ModelForm): choose_img = forms.ModelMultipleChoiceField(queryset=Photograph.objects.all(), required=False) def __init__(self, *args, **kwargs): super(SomeForm, self).__init__(*args, **kwargs) self.initial.update({"choose_img": self.instance.photos.all()}) def save(self, commit=True): chosen_imgs = set(self.cleaned_data.pop("choose_img")) instance = super(SomeForm, self).save(False) if commit: instance.save() current_imgs = set(instance.photos.all()) for img in chosen_imgs - current_imgs: instance.photos.add(img) for old_img in current_imgs - chosen_imgs: old_img.profile = None old_img.object_id = 0 old_img.save() return instance and add it with the PhotographInline (basically just an instance of GenericTabularInline) to the admin site class MyProfileAdmin(admin.ModelAdmin): form = SomeForm inlines = [ PhotographInline, ] So far so good. The new save method does what i expect when selecting Photograph's in the choose_img field. If I deselect a Photograph it still works but it redirects me to the admin change form displaying "Please correct the errors below." and marking the … -
How to fix compatibility between libraries
Im trying to perform some actions with jwt token. Im working with Django-rest-jwt, wich requires PyJWT and jwt. The problem is - I made fork to PyJWT cause I need some code working another way, and when I try to use Django-rest-jwt, it says that he can't find jwt, also pip3 gives me this, when I install my fork. pic , btw fork works correctly. So, how can I make Django-rest-jwt use my fork instead of PyJWT? I tried to fork it and change requirements, but didn't find PyJWT at all -
Gunicorn "error: unrecognized arguments: --log-file--"
I am trying to deploy my django application to heroku, but every single time I try, I see this error in my logs: gunicorn: error: unrecognized arguments: --log-file-- But my Procfile looks like this (I haven't forgotten to save it or anything) web: gunicorn post_project.wsgi --log-file - I can't really put my eye on anything that may be a cause of that error except these few lines at Heroku This app is using free dynos web gunicorn post_project.wsgi --log-file-- -
Problem with sending a POST request with axios in reactjs
Hi every body I am using reactjs and redux for frontend and I want to create new articles so I created CreateArticle.js as below import { useDispatch, useSelector } from 'react-redux' import { unwrapResult } from '@reduxjs/toolkit' import { addNewArticle } from './managementSlice' import { selectAccessToken, selectUser } from '../authentications/authenticationsSlice' import './CreateArticle.scss'; import { selectAllSubjects, fetchSubjects } from '../subjects/subjectsSlice'; import { selectAllTags, fetchTags } from '../tags/tagsSlice'; export const CreateArticle = () => { const [title, setTitle] = useState('') const [body, setBody] = useState('') const [slug, setSlug] = useState('') const [subjectId, setSubjectId] = useState(0) const [tags, setTags] = useState([]) const [addRequestStatus, setAddRequestStatus] = useState('idle') const user = useSelector(selectUser); const subjects = useSelector(selectAllSubjects) const allTags = useSelector(selectAllTags) const subjectStatus = useSelector((state) => state.subjects.status) const tagStatus = useSelector( (state) => state.tags.status) const dispatch = useDispatch() // const onSubjectChanged = (e) => setSubjectId(parseInt(e.target.value)) const onSubjectChanged = (e) => setSubjectId(e.target.value) const onTitleChanged = (e) => { setTitle(e.target.value) setSlug(e.target.value.toLowerCase())} const onBodyChanged = (e) => { setBody(e.target.value) console.log(e.target.value); } const onTagsChanged = (e) => { const selectedOptions = [...e.target.selectedOptions].map(o => parseInt(o.value)) setTags(selectedOptions) } const onSaveArticleClicked = async () => { let article = { Subject:subjectId, Title: title, Body:body, Tags:tags, Slug:slug } if (user){ try { setAddRequestStatus('pending') console.log('addRequestStatus:', … -
How to import all the classes in a module as a list?
In django, to display models on admin page, we have to first register all the models in admin.py. If there are so many models to register, we have to write admin.site.register(model_name) so many times. Its kind of a boring task. So I was wondering if there is any way in python to import all the classes in module as list. for instance, admin.py, from django.contrib import admin from .models import * as list_name #like this is there any way we can get all things inside * in list ? for i in list_name: admin.site.register(i) #so that this way I have to write only one line of code to register all classes. Is there any way to save writing lot of lines here ? -
django - how to save form fields from multiple lines of input?
I want to add mutliple values from user input to a form field into one variable. These values are ManyToMany field in my model. User selects them from a list and adds into that field. I send {{form.product}} to template, I can gather one value from here but i want to add more lines (which i can with JS) and save those lines into same (forms.product) field. My model contains product,product_group. I want to add products with product group as well, which will be different in every line. E.g.: prod1,1 / prod1,2 / prod,3 etc. Second value will be that line index that i want to add. My template html looks like this: {{ form.product}} <ul>Products:</ul> <div id="productcon"> </div> <div id="add" onclick="add()">add interest</div> And my javascript is like this: function add(){ let index = $('#productcon')[0].childElementCount +1; $('#productcon').append(`<input type="text" name="product${index}" value="??"/> `); } This add new lines but I can't save them except my first value. This JS part confused me. Or i focused on JS and missing something else. I hope I could explain my problem. Thank you. -
get highest number of order on a single date
My model is like class Order(models.Model): user=models.ForeginKey(User) completion_date_time = models.DateTimeField(blank=True, null=True) I want to get date on which max number of order placed with count of order -
Return multiple user in Django
My tests are failing saying get() returned more than one permissions -- it returned 2! However I want to return more than one permission, but I could not get the list. I'm using ajax to display those list on modal. My problem is I want to display all usertype name base on idd below. If any expert could help please share some solution thanks in advance. returned more than one permissions -- it returned 2! views.py def ajax(request): idd = request.GET.get('id') app_permission_tbl_usid = permissions.objects.get(user_id=idd) app_permission_tbl_permid = app_permission_tbl_usid.permission_id datas = usertypes.objects.get(id=app_permission_tbl_permid) list_of_permission = datas.usertype return JsonResponse({"result": list_of_permission}) -
Render a different form inside view Django
I'd like to use the same page, but render a different form according to which button I press. Is there a way of doing it? Here it goes my HTML and VIEW code _adm.html <div class="btn-group btn-group-lg" role="group"> <div class="col-md-12 text-center"> <form action="" method="POST"> <a role="button" type="submit" href="{% url 'administrativo' user.username %}" name="senha" class="btn btn-green text-white">Alterar Senha</a> <a role="button" type="submit" href="{% url 'administrativo' user.username %}" name="nome" class="btn btn-green text-white">Alterar Nome</a> </form> </div> adm.html {% extends 'base.html' %} {% load static %} {% block content %} {% include 'partials/_header.html' %} {% include 'partials/_adm.html' %} <div class="container"> {{ form }} </div> {% include 'partials/_footer.html' %} {% endblock %} view.py def alterar_senha(request, user_username): usuario = User.objects.get(username=user_username) form = AlterarSenha(instance=usuario) context = { 'form': form } return render(request, 'usuarios/administrativo.html', context) def editar_usuario(request, user_username): usuario = User.objects.get(username=user_username) form = EditarUsuario(instance=usuario) context = { 'form': form } return render(request, 'usuarios/administrativo.html', context) def administrativo(request, user_username): if request.method == 'POST' and 'senha' in request.POST: return redirect('alterar_senha', user_username) elif request.method == 'POST' and 'nome' in request.POST: return redirect('editar_usuario', user_username) return render(request, 'usuarios/administrativo.html') I have no idea if it is possible to do such a thing. Otherwise, I'll have to render 3 different pages. -
How to change the default port of frontend and backend pages?
I have a front-end developed using react. I need this front-end page to run on port 1111. And also I have a back-end diango api which runs on a port 2222. the front-end receive data from the back-end. How can I configure the ports for both page. Note that for the back-end, i just added the following two lines from django.core.management.commands.runserver import Command as runserver runserver.default_port = "2222" to manage.py and now it is ok. But the frontend I get always localhost:3000 -
get item and its last reverse relationship item
How could i get joined results of item and only last reversed item using one query. for example class Blog: name = models.CharField() class Entry: blog = models.ForeignKey(Blog) how to get a list of distinct blog items with only last entry associated with it, thanks! -
is there way to create box for info or to be title in admin panel in django
is there way to create box for info or to be title in admin panel in django like photo for example when i add new record i want put box for info my admin.py : from django.contrib import admin from blog_app.models import Android # Register your models here. admin.site.register(Android) -
join() argument must be str, bytes, or os.PathLike object, not 'function' problem
I am currently working on my first website, but I am experiencing some issues such as this one: join() argument must be str, bytes, or os.PathLike object, not 'function'. I think it has something to do with views.py but I don't really know how to solve it. Here's the code: def translator_view(request): def translator(phrase): translation = "" for letter in phrase: if letter.lower() in "a": if letter.isupper: translation = translation + "U" else: translation = translation + "u" elif letter.lower() in "t": if letter.isupper: translation = translation + "A" else: translation = translation + "a" elif letter.lower() in "c": if letter.isupper: translation = translation + "G" else: translation = translation + "g" elif letter.lower() in "g": if letter.isupper: translation = translation + "C" else: translation = translation + "c" return translation return render(request, translator, 'main/translator.html') def translated_view(self, request): text = request.GET.get('text') print('text:', text) translator = self.translator dt = translator.detect(text) tr = self.translated.text context = { 'translated': tr } return render(request, context, 'main/translated.html') def home_view(request): return render(request,'main/home.html') -
how to add dynamic dropdown menu option in django
admin.py from django.contrib import admin from .models import ReportModel # Register your models here. @admin.register(ReportModel) class ReportAdmin(admin.ModelAdmin): list_display=('url', 'width', 'height', 'name') forms.py from django import forms from .models import ReportModel from django.db import models class ReportForm(forms.Form): width = forms.CharField(widget=forms.NumberInput(attrs={'class':' form-control'})) height = forms.CharField(widget=forms.NumberInput(attrs={'class':' form-control'})) url = forms.URLField(max_length=300) name = forms.CharField(max_length = 50) class Meta: model = ReportModel fields = [ "url","width","height","name"] urls.py from django.contrib import admin from django.urls import path, re_path from django.conf.urls import url from .import views app_name = 'report' urlpatterns = [ url(r'^reporttest/$', views.reporttest, name='reporttest'), url(r'^add/$', views.add, name='add'), ] view.py from .forms import ReportForm from .models import ReportModel from django.shortcuts import render, redirect def reporttest(request): form = ReportForm(request.POST) return render(request, 'report/add_report.html',{'form':form}) def add(request): report_items={} form = ReportForm(request.POST) url =request.POST['url'] width=request.POST['width'] height=request.POST['height'] name=request.POST['name'] if form.is_valid(): if ReportModel.objects.filter(url=url).exists(): return render(request, 'report/add_report.html', { 'form': form, 'error_message': 'URL already exists.' }) elif ReportModel.objects.filter(name=name).exists(): return render(request, 'report/add_report.html', { 'form':form, 'error_message': 'Report name already exists.' } ) else: report_models=ReportModel(url=url,width=width,height=height,name=name) report_models.save() print(report_models.name) report_items={'url':request.POST['url'], 'width':request.POST['width'], 'height':request.POST['height'], 'name':request.POST['name']} return render(request, 'report/report_one.html', report_items) else: return render(request, 'report/add_report.html',{'form':form}) report_one.html {% block content %} <body> <iframe src = "{{url}}" width= "{{width}}" height= "{{height}}" frameborder="0" allowfullscreen allowtransparency ></iframe> </body> {% endblock %} add_report.html {% extends "student/base2.html" %} {% block content %} … -
Can I link my customer model to my user model?
I'm working an a django e-commerce website where a user has to be a customer. But when I create a new user, it assigns it to the the superuser not the new user and get this error: Exception Value: User has no customer. But i can also go to my admin panel and re-assign the customer to the user. django admin panel How can I fix this please? My customer model class Customer(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=255, null=True) email = models.CharField(max_length=255, null=True) def __str__(self): return self.name members/views.py to create new user and customer from django.shortcuts import render from django.views import generic from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy from shop.models import Customer from django.views.generic import CreateView from .forms import CreateCustomerForm # Create your views here. class UserRegisterView(generic.CreateView): form_class = UserCreationForm template_name = 'registration/signup.html' success_url = reverse_lazy('customer') class CreateCustomerView(CreateView): form_class = CreateCustomerForm template_name = 'registration/customerProfile.html' success_url = reverse_lazy('login') def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) My shop view def shop(request): data = cartData(request) cartItems = data['cartItems'] products = Product.objects.all() context = {'products': products, 'cartItems': cartItems} return render(request, 'shop/shop.html', context) -
Django Middleware vs Django view
I have developed a Django view which takes in certain parameters as input and Creates an issue on JIRA My manager is now asking me to implement this view as middleware. I think that this is not necessary as we should invoke this view only when needed(like when user wants to create JIRA issue) in normal way instead of including this as middleware. I am new to the middleware concept and I want to understand if there is any added advantage of calling this view via middleware vs direct view call. Please suggest. -
Error Django polls app command makemigration polls
I am facing an error each time I run this command as django beginner when creating polls up I don't know if I am missing something please refer it back to me I really need help. py manage.py makemigrations polls Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\4488\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\4488\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\4488\AppData\Local\Programs\Python\Python38\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\4488\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\4488\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\Users\4488\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 970, in _find_and_load_unlocked ModuleNotFoundError: No module named 'polls.apps.PollsConfigdjango'; 'polls.apps' is not a package -
How to use ImportExportModelAdmin in django Admin page
I am trying to implement import and export in Django admin.i am getting below error. admin.site.register(ShiftChange,ShiftChangeAdmin) File "/Users/shaileshyadaav/PycharmProjects/first/venv/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 117, in register raise AlreadyRegistered(msg) django.contrib.admin.sites.AlreadyRegistered: The model ShiftChange is already registered with 'apple.ShiftChangeAdmin'. I have referred(https://stackoverflow.com/a/13709239)but don't know how to unregister.Please find the below admin.py file. from django.contrib import admin from apple.models import ShiftChange,RMSI from import_export.admin import ImportExportModelAdmin # Register your models here. @admin.register(ShiftChange) class ShiftChangeAdmin(ImportExportModelAdmin): pass @admin.register(RMSI) class RMSIAdmin(ImportExportModelAdmin): pass class ShiftChangeAdmin(admin.ModelAdmin): list_display=['ldap_id','Vendor_Company','EmailID','Shift_timing','Reason','last_updated_time'] ###Adding this line so that we Can Search/filter user result in case of any changes or to Check last time when he updated####### search_fields = ('ldap_id', 'EmailID','Shift_timing') admin.site.register(ShiftChange,ShiftChangeAdmin) class RMSIAdmin(admin.ModelAdmin): list_display=['ldap_id','Vendor_Company','EmailID','Shift_timing','Reason','last_updated_time'] ###Adding this line so that we Can Search/filter user result in case of any changes or to Check last time when he updated####### search_fields = ('ldap_id', 'EmailID','Shift_timing') admin.site.register(RMSI,RMSIAdmin) Any help on this will be highly appreciated. -
Why did my Django not add a pk to my model?
from django.db import models class User(models.Model): username = models.CharField('Username', max_length=240) avatar_url = models.CharField(max_length=2000, null=True, blank=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) def __str__(self): return self.username I made a Django app that uses this simple model and it should have auto added pk hovewer when I inspect it in my api I don't see it. (avatar url is there because I intend to use Facebook api to get the user) -
How to write urls in static format in django
I am unable to upload style="background-image:url(images/home_slider.jpg)" file in django. I have made two changes in settings .That is as follows: STATIC_URL = '/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static')] STATIC_ROOT=os.path.join(BASE_DIR,'assets') I also tried this style=" {% static'background-image:url(images/home_slider.jpg)' %}" But unable to remove error. -
Feature-testing a REST API with unittest in Django
In our Django project, we have some API views that are defined in urls.py like this: path('api/calendar/calendar_data', calendar_api.serve_data), and our calendar_api is an instance of CalendarAPI, which is instantiated above: from main.calendar_api import CalendarAPI from caldav import DAVClient ... calendar_api = CalendarAPI(client=DAVClient(...)) In the CalendarAPI class we have a method that fetches data from a remote CalDAV calendar using the caldav library like so: class CalendarAPI(ApiEndpoint): ... def __init__(self, client): self.caldav_client = client def _get_event_list(self): return self.caldav_client.principal().calendars()[0].events() We wish to mock this method in a way such that _get_event_list returns a predefined array. Our test case looks like this: from unittest.mock import patch from django.test import SimpleTestCase class TestCalendar(SimpleTestCase): @patch('main.urls.CalendarAPI') def test_response_format(self, calendarapi_mock): calendarapi_mock._get_event_list.return_value = mocked_calendar_events response = self.client.get('/api/calendar/calendar_data', format='json') # fails test if response does not match mocked_calendar_events self._compareResponse(response, mocked_calendar_events) No matter what we try, we can't get mocking to work. If anyone knows of a better way to instantiate classes in urls.py in light of mocking, please let us know!