Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When using Django's Default Storage should/can you close() an opened file?
When using Django's DefaultStorage it's possible to open and read a file something like this: from django.core.files.storage import default_storage file = default_storage.open("dir/file.txt", mode="rb") data = file.read() When using python's own open() method, it's best to close() the file afterwards, or use a with open("dir/file.txt") as file: construction. But reading the docs for Django's Storage classes, and browsing the source, I don't see a close() equivalent. So my questions are: Should a file opened with Django's Default Storage be closed? If so, how? If not, why isn't it necessary? -
formset django, problems saving a lot of data added to the click
Hi everyone I have a problem with django formset.I can create through js adding objects but at the moment of creation I only save the first object I created and not the others. I beg you for months that I have been on this thing without finding a real solution. below I put my code, I hope you are reading that you can help me, I will be grateful. HTML <section class="container mt-3"> <div class="d-flex align-items-center justify-content-between"> <h1 class="nome-scheda">TEST FORMSET</h1> <a href="{% url 'lista' %}" class="btn btn-outline-dark">LISTA</a> </div> <hr> <form method="post"> {% csrf_token %} {{ formset.management_form }} <div class="list-form"> {% for form in formset %} <div class="esercizio-box"> {{ form.as_p }} </div> {% endfor %} </div> <div id="form-vuoto" class="hidden"> <div class="esercizio-box"> {{ formset.empty_form.as_p }} </div> </div> <div class="text-end mt-2 mb-5"> <button id="add" type="button" class="btn btn-success">AGGIUNGI</button> </div> <input type="submit" class="btn btn-primary" style="width:100%;" value="crea"> </form> </section> SCRIPT <script> $('#add').click(function(){ var form_idx = $('#id_form-TOTAL_FORMS').val(); $('.list-form').append($('#form-vuoto').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); </script> VIEWS.PY from django.forms import formset_factory def testViews(request): testFormSet = formset_factory(testForm, extra=0) if request.method == "POST": formset = testFormSet(request.POST) if formset.is_valid(): for form in formset: form.save() return redirect('/lista/') else: formset = testFormSet() context = {'formset': formset} return render(request, "tests.html", context) -
Error __str__ returned non-string (type NoneType)
I know that this error is classic. But I'm facing a harder problem : This is my model. I've check all the topics about this common problem, try to resolve it but I don't achieved. I cannot add stafftimeslot in the admin panel. Can you help me ? Here is my models.py : from django.db import models from django.utils import timezone from staffs.models import Staff from students.models import Student TIMESLOT_LIST = ( (0, '09:00 – 09:30'), (1, '09:30 – 10:00'), (2, '10:00 – 10:30'), (3, '10:30 – 11:00'), ... ) class StaffTimeSlots(models.Model): staff = models.ForeignKey(Staff, null=True, on_delete=models.CASCADE) date = models.DateField(default=timezone.now) time_slot = models.CharField(max_length=2, choices=TIMESLOT_LIST) def get_absolute_url(self): return reverse('stafftimeslot_detail', kwargs={"pk": self.pk}) def __str__(self): return str(self.date) EDIT : When I delete ForeignKey, it works but when I reuse it, it does not work anymore. So I tried to replace with OnetoOneField and ManytoManyField and I have faced with the same problem. It seems that the model does not accept model relations. How can I do to relate this model with the Staff model with a foreign key ? -
Wie kann ich die Adminseite nochmal zeigen? [closed]
als ich mit mssql verbindet habe, kommt zu mir diese Fehle -
(Django) how to submit a form with empty fields?
I have a form with a drop down list with two options ("MCQ" and "SEQ") and some fields. Selecting "MCQ" would hide fields used by "SEQ" and vice versa. I want to submit this form but the "please filled out this field" notice pops up. What should I do to submit this form? I've searched around Stack overflow before looking possible solutions, some suggested placing "required" or "disabled" beforehand, however I would like a dynamic way of doing if possible but based it on which option the user selects since the user might leave everything empty and just submit if nothing is required. Additional Information: I'm using forms.ModelForm, the fields came from there. I'm using js to hide and show the relevant fields. I Appreciate any help/suggestions. :) -
django.core.exceptions.ImproperlyConfigured: Field name `operatives` is not valid for model `Operative`
field raise ImproperlyConfigured( [14/Sep/2021 10:46:30] "POST /operatives/ HTTP/1.1" 500 133558 -
Unable to override the pre-authenticate and authenticate methods in adapters
Unlike save_user and send_email in DefaultAccountAdapter, I am unable to override the pre_authenticate and authenticate methods. Please can someone explain why or how I can achieve these? class DefaultAccountAdapterCustom(DefaultAccountAdapter): def pre_authenticate(self, request, **credentials): # Do something before authenticating def authenticate(self, request, **credentials): # Do something after authenticating -
Can't use getList() with a MultiValueDict
I am uploading images using Axios/Next.JS/Django, and I am appending 4 images to form data. When I print(request.FILES) I get <MultiValueDict: {'images': [<InMemoryUploadedFile: HARRY-POTTER-HERMIONE-GRANGER-MAGIC-WAND__0082686381314-Z.JPG (image/jpeg)>, <InMemoryUploadedFile: harry-potter-wand-gringotts.jpeg (image/jpeg)>, <InMemoryUploadedFile: HarryPotterWandNN8415.jpeg (image/jpeg)>, <InMemoryUploadedFile: Hgwand.webp (image/webp)>]}> Which is correct, but when I go to loop through the data (request.FILES.getList('images')) to save it to an S3 bucket I get the error: AttributeError: 'MultiValueDict' object has no attribute 'getList'. Everything I've seen on SO and other places are telling me to use getList(). Am I missing something here? -
Django - How can my asgi websocket path be on my swagger
I am creating an api where two endpoints are using the ws(s) protocol. As my API is behind Google endpoint, Every endpoint needs to be defined onto an OpenApi2.0 file. To create this definition I use drf-yasg. I have a routing. py file like this: """ systems/routing.py""" from django.urls import path from .consumers.list_sessions_consumer import MyFirstConsumer from .consumers.session_consumer import MySecondConsumer urlpatterns = [ path(r'v1/ws/yo/<str:uuid>/sessions-sumpup', MyFirstConsumer.as_asgi()), path(r'v1/ws/yo/<str:uuid>/sessions', MySecondConsumer.as_asgi()), ] and I register it onto my asgi.py file like this: # pylint: skip-file """ main/asgi.py """ import os import django from django.core.asgi import get_asgi_application django_asgi_app = get_asgi_application() os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'main.settings') django.setup() from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from systems.websockets.routing import urlpatterns as system_websocket_url application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AuthMiddlewareStack( URLRouter( system_websocket_url ) ), }) Don't mind the import order this is due to this error: Django apps aren't loaded yet when using asgi So my socket works as expected, now, I want my command line: python3 manage.py generate_swagger swagger.yaml to add these new endpoint to my swagger file. I tried to directly add my url to the same object then all my other urls like so: urlpatterns = [ path(r'v1/toto/<str:uuid>', MyView.as_view()), ..., path(r'v1/ws/yo/<str:uuid>/sessions-sumpup', MyFirstConsumer.as_asgi()), path(r'v1/ws/yo/<str:uuid>/sessions', MySecondConsumer.as_asgi()), ] But nothing shows … -
Adding support for Alpine.js to a Django package
I'm using a package that adds an SVG template tag to inline my SVGs in my Django templates. I forked the project and added support for passing HTML attributes to SVG. So, right now I'm able to use it as the following: {% load svg %} <a class="font-semibold text-gray-850 href="#0"> {% svg 'icon-chevron-down' class="inline -mb-0.5 w-4 h-4 ml-0.5 transition-transform duration-200 transform fill-current text-gray-400" %} </a> But I'm encountering a problem when I want to use Alpine.js within the svg. I'd like to be able to do something like this: {% svg 'icon-chevron-down' :class="{'rotate-180': open, 'rotate-0': !open}" class="inline -mb-0.5 w-4 h-4 ml-0.5 transition-transform duration-200 transform fill-current text-gray-400" %} How can I make it work? The repo to my package: https://github.com/xshapira/django-simple-svg svg.py from __future__ import absolute_import import logging import os from django import template from django.conf import settings from django.contrib.staticfiles import finders from django.core.exceptions import ImproperlyConfigured from django.utils.safestring import mark_safe from simple_svg.exceptions import SVGNotFound logger = logging.getLogger(__name__) register = template.Library() @register.simple_tag def svg(filename, *args, **kwargs): SVG_DIRS = getattr(settings, "SVG_DIRS", []) if type(SVG_DIRS) != list: raise ImproperlyConfigured("SVG_DIRS setting must be a list") path = None if SVG_DIRS: for directory in SVG_DIRS: svg_path = os.path.join( directory, "{filename}.svg".format(filename=filename) ) if os.path.isfile(svg_path): path = svg_path else: … -
Is there a way to pass information between pages in Reactjs using navlink?
I am using a Django REST framework, storing data in a model. I am then using Reactjs to consume the API and make GET/POST requests. Inside the React frontend, I am using react-router-dom to navigate between pages. I want to be able to click on a specific link, but then also pass on information to the component towards which the link is routed. This is my index.js code import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; import { BrowserRouter } from 'react-router-dom'; ReactDOM.render( <BrowserRouter> <App/> </BrowserRouter>, document.getElementById('root') ); This is my App.js code import './App.css'; import Container from '@material-ui/core/Container'; import Navigation from './Components/ToolBar' import Main from './Components/Main' function App() { return ( <> <Container maxWidth='lg' className="App"> <Navigation/> <Main/> </Container> </> ) } export default App; This is my Main.js code import { Switch, Route } from 'react-router-dom'; import Projects from './Projects'; import Tickets from './Tickets'; const Main = () => ( <Switch> <Route exact path='/projects' component={Projects}></Route> <Route exact path='/tickets' component={Tickets}></Route> </Switch> ); export default Main; This is my Toolbar.js code, which is used for navigating to different pages import { Button } from '@material-ui/core' import AppBar from '@material-ui/core/AppBar' import Toolbar … -
Parameterised decorator returning an error
I'm writing a decorator to check a certain attribute of a user. I will use this decorator over POST of GET methods of some class based APIs. The attribute is stored in the request.session["user_status']. def decorator_func(func): def wrapper_func(class_reference, request): status = request.session["user_status"] if status != value1 or status != value2: return Response(data="A dictionary") return func(class_reference, request) return wrapper_func Whenever the if condition is not satisfied and the func is accessed, it works as expected. But when the condition is satisfied and the Response() is returned, I'm getting following error: TypeError at "api path on which the decorator is applied" Object of type "custom user model of this project" is not JSON serializable I'm guessing due to not writing the decorator in the correct way I'm getting some error and when it is trying to return the error, it's also trying to return the current user object which is not JSON serializable. The user object is also stored in request.session["user"]. What am I doing wrong in this parameterized decorator function? -
How to add custom django admin site and urls without the prefix in every pattern?
I am trying to include the urls of my custom admin site of one of my apps in a Django project. I would like the path to be foo-admin/.... I managed to do so by including this prefix in all urlpatterns in the app's urls.py. However if I try to add the prefix to the project's urls.py and have only the suffixes in the app's urls, it breaks. It's something like this: This works: Project's urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('my_app.urls')), ] my_app/urls.py: urlpatterns = [ path('foo-admin/', my_app_admin_site.urls), path('foo-admin/foo/', views.some_view), path('foo-admin/foo/<slug>/', views.MyGenericView.as_view()), ] This doesn't work: Project's urls.py urlpatterns = [ path('admin/', admin.site.urls), path('foo-admin/', include('my_app.urls')), ] my_app/urls.py urlpatterns = [ path('', my_app_admin_site.urls), path('foo/', views.some_view), path('foo/bar/<slug>/', views.MyGenericView.as_view()), ] The error I'm encountering is: NoReverseMatch at /foo-admin/ Reverse for 'app_list' with keyword arguments '{'app_label': 'my_app'}' not found. 1 pattern(s) tried: ['admin/(?P<app_label>auth|app1|app2|django_mfa|axes)/$'] -
I want to have multiple forms in django on the same page
I am creating a mad libs application. for ppl to create new mad libs I have a field model. this is my models.py: class story(models.Model): Name = models.CharField(max_length=255) Text = models.TextField() def __str__(self): return self.Name class type_of_input(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class field(models.Model): Name = models.CharField(max_length=255,null=True) Tag = models.CharField(max_length=255) story = models.ForeignKey(story, on_delete=models.CASCADE) type = models.ForeignKey(type_of_input, on_delete=models.CASCADE, null = True) def __str__(self): return self.Tag People enter stories in a format like: "Once upon a time in {kingdom_name}" here kingdom name is a tag. I am parsing this story to get tags. I want a form on the next page with all tags having 2 attributes, name and type. how do I achieve this -
Django caching - Get is not pulling updated value while a function is in a loop
I have process in django which is streaming prices. When my application runs or certain events occur on my Django server I would like to save some variables from the database and store them in memory to use later them in my streaming process as a variable. Based on the value of this variable in the while loop every time my process tries to get the value stored in the cache. But my problems is that when I use cache.get() the update values is not pulling from the cache. The process is running by a Django Q cluster. Can someone help me what is the best way to implement in the running process to fetch the value from memory instead of continously quering the database for the same or updated value ? -
Creating a alert functionality in django wagtail
I am trying to create a alert section for a menu (similar to the menu on this page https://metageeky.github.io/mega-menu/responsive-header.html) *Each alert should have an effective date (date alert is “posted” live) and resolved date (date alert is “removed” live). Each alert will also have a maximum of one to two sentences of text describing situation. The number of active/current alerts will appear in parenthesis following the icon and ALERT link text. The icon and text are Dark Orange. When you hover over the icon and text, an underline appears. When users click on the link, they are taken to a page that lists all active alerts. At bottom of page, message displays “If you are experiencing an issue, please contact us at....” If there are no Alerts: The number of alerts in parenthesis following the icon and link text will not appear. Both the icon and alert text will be Primary Blue. When Users click on the link, they are taken to a secondary alerts page that displays a message that says “There are currently no active alerts. If you are experiencing an issue, please contact us at...” How would i achieve this? Thank you. -
Django: how to check if a field has been modified by the user?
I have a model in models.py; like this: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to='static/images/account/avatar', default='/static/images/default-avatar.png') bio = models.CharField(max_length=300, blank=True, null=True) def __str__(self): return '@' + self.user.username in views.py i want to check if a filed (i mean avatar) from Profile model has changed or not in views.py: def editProfile(request): user = request.user.profile form = AuthorForm(instance=user) if request.method == 'POST': if ...: os.remove(request.user.profile.avatar.path) form = AuthorForm(request.POST, request.FILES, instance=user) if form.is_valid(): form.save() return redirect('dashboard') context = {'form': form} return render(request, 'account/edit.html', context) In fact, I want the default image (or any other photo) not to be deleted if the user does not change the avatar field. -
Get the object name in django admin
Hej! I want to have a category for turnovers in my admin area and in there I have a field with currency. It is a dropdown field with pre given currencies. My problem is, that there aren't the actual currencies shown rather their IDs. (like Object 123). Does anyone know how to solve this for an inline? # models.py class Currency(models.Model): code = models.CharField(max_length=3, unique=True) currency = models.CharField(max_length=150, unique=True) class Turnover(models.Model): currency = models.ForeignKey(Currency, on_delete=models.PROTECT) # admin.py class TurnoverInline(admin.TabularInline): model = Turnover extra = 1 classes = ["collapse"] class SomeAdmin(admin.ModelAdmin): form = SomeForm save_on_top = True inlines = [ TurnoverInline ] For a similar problem I created admin.ModelAdmins and integrated a code_str(self) and str(self) method in the model. But those aren't Inlines and in the SomeForm/SomeAdmin as fields/autocomplete_fields. -
Inheritance in Python models
Having a little misunderstanding with the inheritance in Python. I have one parent class: class BaseClass(models.Model): email = models.EmailField(blank=True) phone = models.CharField(max_length=32, blank=True) name = models.CharField( max_length=64, blank=True, verbose_name=_(u'name') ) surname = models.CharField( max_length=64, blank=True, verbose_name=_(u'surname') ) class Meta: abstract = True def __str__(self): if self.name: return self.name elif self.email: return self.email else: return self.phone And I would like to use these all data in child class named SecondClass, but I dont know what I must to insert in body section of this class: class SecondClass(BaseClass): -
Filter Django Models using lists of field parameters
I'd like to be able to pass any number of fields and values into a function to identify relevant rows: models.py class Player(models.Model): name = CharField(max_length = 50, default = 'Ronaldo') defender = BooleanField(default = False) midfielder = BooleanField(default = False) attacker = BooleanField(default = False) goalkeeper = BooleanField(default = False) views.py def find_player(**kwargs):#to be used in some view players = Player.objects.filters(kwargs).all() for player in players: #do something with player... find_player({defender:True, goalkeeper:True})#selects rows with players who defend and play in goal find_player({defender:True, attacker:False})#... find_player({defender:False}) What I'm trying to do above clearly doesn't work! I know that I could also use exec() to get what I want: def find_player(string_of_params): players = exec(Player.objects.filters(string_of_params).all()) for player in players: print(player) find_player('defender=True, goalkeeper=True')#prints rows with players who can defend and go in goal find_player('defender=True, attacker=False')#... find_player('defender=False'}) But I think there has to be a more natural way of unpacking the contents of a dictionary directly into filter(). Any guidance on this welcome. -
applying django forms to html template
i got a alrdy done html template , i'm trying to add register form to this template, idk hot to insert form fields. i tried to add {{ form.'fieldname' }} to input , but it doesn't effect. can't find any docs , sorry for silly question <section class="signup"> <div class="container"> <div class="signup-content"> <div class="signup-form"> <h2 class="form-title">Sign up</h2> <form method="POST" class="register-form" id="register-form" action=""> {% csrf_token %} <div class="form-group"> <label for="name"><i class="zmdi zmdi-account material-icons-name"></i></label> <input type="text" name="name" id="name" placeholder="Your Name"/> </div> <div class="form-group"> <label for="email"><i class="zmdi zmdi-email"></i></label> <input type="email" name="email" id="email" placeholder="Your Email"/> </div> <div class="form-group"> <label for="pass"><i class="zmdi zmdi-lock"></i></label> <input type="password" name="pass" id="pass" placeholder="Password"/> </div> <div class="form-group"> <label for="re-pass"><i class="zmdi zmdi-lock-outline"></i></label> <input type="password" name="re_pass" id="re_pass" placeholder="Repeat your password"/> </div> <div class="form-group form-button"> <input type="submit" name="signup" id="signup" class="form-submit" value="Register"/> </div> </form> -
django.core.exceptions.ImproperlyConfigured when trying to run a script with models
Okay so I have a Django project and I have model I want to get data from and do things with inside a python script. from django.db import models from metrics.models import Chart import django django.setup() p = Chart.objects.filter(dept_name="IT") print(p) anytime I try and run this I get the error django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I have tried setting a global variable for Django setting with the command set DJANGO_SETTINGS_MODULE=projectname.settings Any help would be greatly appreciated! Thanks in advance! -
Show only staff name in radio button and user can choose staff name, input price as well
I am trying to show only the staff lists on the radio button to the front end. Then the user can choose the staff name and then input the price and submit. So the system will take staff name (chosen by User) and price as input. So far I was trying to filter the staff name like staff = User.objects.filter(is_staff=True) but I am unable to pass the value to the front end. So I want to show a list of staff names and then the user chooses the staff name and inputs the price. As the views.py file is quite big, so I am sharing the gist file view.py Could anyone please help me out? Thank you -
how to send verification code to email and verify it in django rest framework
Please how can i send verification code to email before user's registration using django rest framework ? the idea is sending a code of 6 dgitis for example before transferring user to the registration's page, verify it if everything is okay then the user can continue the registration. Views.py class RegisterView(CreateAPIView): queryset = models.User.objects.all() serializer_class = RegisterSerializer Serializers.py class RegisterSerializer(serializers.ModelSerializer): photo = PhotoSerializer(read_only=True) announcements = AnnouncementSerializer(many=True, read_only=True) rating = SerializerMethodField('rating_avg') number_of_ratings = SerializerMethodField('rating_number') token = serializers.SerializerMethodField('get_token') class Meta: model = User fields = ['id', 'email', 'password','last_name', 'first_name', 'patronymic', 'type', 'date_joined', 'phone', 'photo', 'rating', 'number_of_ratings', 'announcements', 'token'] extra_kwargs ={ 'password':{'write_only':True} } def rating_avg(self, obj): rating = Review.objects.filter(user=obj.id).aggregate(Avg('rate')) return rating def rating_number(self, obj): number_of_ratings = Review.objects.filter(user=obj.id).count() return number_of_ratings def get_token(self, user): tokens = RefreshToken.for_user(user) refresh = text_type(tokens) access = text_type(tokens.access_token) token = { "refresh": refresh, "access": access } return token def create(self, validated_data): user = User( email=validated_data['email'] ) user.set_password(validated_data['password']) user.save() return user -
Django crontab automated setup issue in ubuntu development server
Am on a windows10 local development and has I can't use cron am testing in a development server. Am trying to setup django-crontab in a ubuntu 16.04 server and having a couple of issues. pip install django-crontab have it on my installed apps and requirements.txt INSTALLED_APPS = [ ... 'django_crontab', ... ] In the development.py settings that extend a base_settings.py have the cronjobs: Only trying to test a job that I already tested via command CRONJOBS = [ ('* * * * *', 'proregattaapi.cron.my_cron_job', '>> /var/log/django_cron_job.log'), ] then pushed to the server hosted by digital ocean. SSH into the server, activated the virtual environment and made the calls: python manage.py crontab add python manage.py crontab show python manage.py crontab run 3a55bd7591de350aa5d5d7be7758f17c in the above, got confirmation that the job was running with the crontab run command well but when I did: python manage.py runserver or left supervisior run the development server the job didn't start or logged anything Then I looked at: crontab -e and the output was: * * * * * /root/.python-virtual-environments/proregatta-django-development-new-virtualenv/bin/python /var/www/development.proregatta.com/manage.py crontab run 3a55bd7591de350aa5d5d7be7758f17c$ From my limited knowledge, I was thinking that with this crontab set activating the virtual env and running would be sufficient. Thank …