Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django delete and then redirect
I have a case that I do not know how to resolve in django. The user is working in a form and then once the form is finished the user is able to generate a PDF from the data from the form. I would like to redirect the user to another page because once the document is generated there is no need to say in the form page. views.py response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = "attachment; filename=" + filename +'.pdf' response.write(pdf) return response -
Not changing Choose File label on button
I am using Django 2.2 with python 3.6. Also using crispy-forms. I create the form with crispy forms from model. In the model there is a field as below. photo = models.ImageField( upload_to="staff/", null=True, blank=True, verbose_name=_("Fotoğraf")) When i create the crispy form the file upload comes with a label "Choose File" and info "No file choosen" as below. As you can see it is English. But i want to change "Choose File" to "Dosya Seç" and "No file chosen" to "Dosya Seçilmedi". But they come with a default language. How can i change them as i am using crispy-forms. forms.py : class HorizontalRadioSelect(forms.RadioSelect): template_name = 'horizontal_select.html' class StaffForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput, required=False) re_password = forms.CharField( widget=forms.PasswordInput, label='Re-type Password', required=False) username = forms.CharField(max_length=50) class Meta: model = Staff widgets = { 'gender': HorizontalRadioSelect(), 'address': forms.Textarea(attrs={'rows': 3}), 'uuid': forms.HiddenInput(), 'photo': ImagePreviewWidget(), } exclude = ['uuid', 'user', ] template (personelkayit.html): {% extends 'base.html' %} {% load crispy_forms_tags %} {% load i18n %} {% load staticfiles %} {% block content %} <div class="block-area" id="basic"> <form role="form" enctype="multipart/form-data" method="post"> {% csrf_token %} {{ form|crispy }} <div > <br> <button style="background-color: #002266 !important; color: white !important" type="submit" class="btn btn-lg btn-alt"><span class="glyphicon glyphicon-floppy-disk pull-left"></span> &nbsp; {% trans … -
Django form is_valid() fails and add_error() takes 2 positional arguments but 3 were given
I am creating news site with stripe subscription. The following code is failing at the is_valid() check. But I do not understand why: The form should get its data filled from the POST-data or not? Model: class CustomUser(models.Model): full_name = models.CharField(max_length=255) email = models.EmailField() stripe_id = models.CharField(max_length=255) ModelForm: class CustomUserForm(ModelForm): class Meta: model = CustomUser fields = ("full_name", "email", "stripe_id") def add_error(self, message): # pylint: disable=E1101 self._errors[NON_FIELD_ERRORS] = self.error_class([message]) View function: def charge(request): if request.method == 'POST': form = CustomUserForm(request.POST) if form.is_valid(): try: charge = stripe.Charge.create( amount=10000, currency='usd', description=form.cleaned_data['email'], source=request.POST['stripeToken'], card=form.cleaned_data['stripe_id'], ) form.save() return redirect('home') except stripe.error.CardError: form.add_error("The card has been declined.") else: print("Form is not valid") else: form = CustomUserForm() args = {} args.update(csrf(request)) args['form'] = form args['publishable'] = settings.STRIPE_PUBLISHABLE_KEY args['months'] = range(1, 13) args['years'] = range(2013, 2038) args['soon'] = datetime.date.today() + datetime.timedelta(days=30) return render(request, 'accounts/charge.html', args) I found similar topics and tried a lot. However I am still stuck. When I run this, it returns add_error() takes 2 positional arguments but 3 were given and it highlights this form.is_valid() line. I also tried to run it without add_error, then I found that form is invalid. I am using python3.7 and Django 2.2.6. -
How to use Django filter's exclude argument with user input?
I'm trying to filter my query results in Django according to user input. I have my filter query working fine with something like Arecords.objects.select_related('b_id').filter(id=5) This works just fine. But what I ideally need is that the user inputs a value in the browser for "id" and I want to exclude those from the result. How would I do something like that? Is there a way I can just use an html form input in my filter() query in Django? Or can I use something else? I've tried using django_filters. It works for the other fields where I'm returning results that contain the user input etc, but I don't know how to deal with a "not in" or "not equal to" What I want is that user enters their own id and I want the query to be filtered so that it excludes the fields with that id. -
Django-autocompletelight Filter Queryset Used
I am using Django-autocomplete light, but I want to filter the queryset based on jobs belonging to a project. I can't find a way of passing the project or project ID as an argument. Can anyone advise how this is possible? My code looks like: class JobsAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): user = getuser(self.request) if user == None: #Set a blank queryset if the user is not logged in qs = Job.objects.none() else: qs = Job.object.all() if self.q: qs = qs.filter(job__istartswith=self.q) return qs Intead of "qs = Job.object.all()", I want to be able to filter the job objects as the user should only be able to select those related to the project. I need a way of running the query "qs = Job.object.filter(project_id=projid)", but there doesn't seem to be a way of getting the projid argument there. I have tried putting it in the URL, but have had no luck. -
python: print time & date with timezone information
I have a piece of code using django library to print a date/time with timezone in the following way: 2019-11-04 22:25:00.831219+00:00 I would like to get rid of django, since in this script it's only used to print date/time+timezone. How can I do this using standard python library? import datetime d = datetime.datetime.now() print(d) This gives the output as this: 2019-11-04 19:05:07.176493 So how do I specify timezone information? Thanks. -
How to pass exception to 500 error handler in Django
I have been learning Django and experimenting with custom error pages. However, to display these pages you have to set DEBUG = False in the settings which in turn prevents any information about server errors being displayed. Therefore, I wanted to setup a custom 500 handler that will display the exception that is raised. I setup the following error handlers: from django.shortcuts import redirect from django.http import HttpResponse def handler404(request, exception): # make a redirect to homepage return redirect('cookiecrumbsapp/cookieCrumbs') def handler500(request): #handle error messages for debugging - set to obscure error once tested return HttpResponse("500") And added the appropriate definitions in my urls file: handler404 = 'cookiecrumbs.views.handler404' handler500 = 'cookiecrumbs.views.handler500' These handlers work fine, but I cannot find a way of displaying the actual exception/error that causes a 500 error on the server. I know that in older versions of Django (<2.2 according to this thread) they had functionality for passing an exception parameter to the 500 handler, just like the 404 one, but that this was removed - is there any way to achieve similar functionality in new versions so that I can display error messages on my page? Django version is 2.2.7 if that helps -
How to render a data request from the database without refreshing the page in Django?
I am trying to display a User's name on top of a box where they enter their Employee # in a form, without having to refresh the page. For example, they enter their # and then after they click/tab onto the next field, it renders their name on top, which comes from the database, so the user knows they've entered the correct info. This name is stored in a separate model, so I try to retrieve it using the "id/number". I am not too familiar with AJAX but after reading a few similar questions it seems like an AJAX request would be the most appropriate way to achieve this. I tried to make a function get_employee_name that returns the name of the person based on the way I saw another ajax request worked, but I'm not sure how to implement this so it displays after the # is entered. models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False) station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return self.employee_number This is the model where the name is stored alldata/models.py class Salesman(models.Model): slsmn_name = models.CharField(max_length=25) id = models.IntegerField(db_column='number', primary_key=True) I was reading … -
How can I mock a ManyToMany Field?
I have these models to test: #models.py (simplified, name is a costum multilanguage field) class NameType(models.Model): name = models.CharField(_('nome'), max_length=25, unique=True) class NameLanguage(models.Model): name = models.CharField(_('nome'), max_length=25, unique=True) syntax = models.ManyToManyField( NameType, related_name='syntax_name', verbose_name=_('sintassi')) To isolate the tests I want to use mock() (I already tested NameType) #test_models.py class NameLanguageTest(TestCase): def test_language_created(self): self.name = Mock(spec=NameType) self.surname = Mock(spec=NameType) self.romans = NameLanguage.objects.create(name='Romans') self.romans.syntax.add(self.name) self.romans.syntax.add(self.surname) self.assertEqual(NameLanguage.objects.all().count(), 1) self.assertEqual( list(NameLanguage.objects.get(name='romans').syntax.all()), [name, surname] ) but when I try to add name and surname to M2M syntax it gives me this error: Traceback (most recent call last): File "E:\progetti\ElencoNomi\lists\tests\test_models.py", line 79, in test_language_created self.romani.syntax.add(nome) File "e:\progetti\envs\ElencoNomi\lib\site-packages\django\db\models\fields\related_descriptors.py", line 938, in add through_defaults=through_defaults, File "e:\progetti\envs\ElencoNomi\lib\site-packages\django\db\models\fields\related_descriptors.py", line 1039, in _add_items if not router.allow_relation(obj, self.instance): File "e:\progetti\envs\ElencoNomi\lib\site-packages\django\db\utils.py", line 280, in allow_relation return obj1._state.db == obj2._state.db File "E:\Python\Python37\lib\unittest\mock.py", line 593, in __getattr__ raise AttributeError("Mock object has no attribute %r" % name) AttributeError: Mock object has no attribute '_state' Also should I use self.name and self.surname or just name and surname? There is difference? Thank you -
How to change a URL that is configured inside a library?
Context: I need to configure OIDC using Django to allow my application to be accessed by users. Problem: I'm using a library called mozilla-django-oidc that is pretty straight-forward, but when I test the configuration, it keeps returning the following error: 400 - Invalid redirect_uri Cause: As I tested in Postman, this error occurs because the callback URL is wrong. When I searched more deeply mozilla-django-oidc, I've found it sets a standard URL path for callback (/oidc/callback/) which is not the URL allowed by the OIDC we need to access. Key Question #1: How can I modify the mozilla-django-oidc code so that the standard callback URL path is what I need it to be? Key Question #2: Is there anyway I can make these changes in my code, instead of mozilla-django-oidc? Below are some settings of my Django code: My Django - views.py # Mozila OIDC configuration settings OIDC_OP_AUTHORIZATION_ENDPOINT = "https://XXXXXXXXXXXXXXXXXXXXX" OIDC_OP_TOKEN_ENDPOINT = "https://XXXXXXXXXXXXXXXXXXXXX" OIDC_OP_USER_ENDPOINT = "https://XXXXXXXXXXXXXXXXXXXXX" OIDC_RP_CLIENT_ID = "XXXXXXXXXXXXXXXXXXXXXXX" OIDC_RP_CLIENT_SECRET = "XXXXXXXXXXXXXXXXXXXXXXX" LOGIN_REDIRECT_URL = "https://myurl.com" My Django - settings.py # Add 'mozilla_django_oidc' to INSTALLED_APPS INSTALLED_APPS = ( # ... 'django.contrib.auth', 'mozilla_django_oidc', # Load after auth # ... ) # Add 'mozilla_django_oidc' authentication backend AUTHENTICATION_BACKENDS = ( 'mozilla_django_oidc.auth.OIDCAuthenticationBackend', # ... ) … -
Get the output of SQL-server's sp_help in django?
SQL server has the prompt: sp_help table_name. I would like to access the output of this using django. I am using django 2.1. I expected the following code to work, but it only returns the first part of what SQL server returns. cursor = connection.cursor() cursor.execute("sp_help testTable") print(cursor.fetchall()) I expected the output to be: [('testTable', 'dbo', 'user table', datetime.datetime(2019, 10, 14, 16, 0, 46, 700000)), ('testCol', 'varchar', 'no', '50', '', '', 'no', 'no', 'no', 'SQL_Latin1_General_CP1_CI_AS'), ...more output data...] Instead I got: [('testTable', 'dbo', 'user table', datetime.datetime(2019, 10, 14, 16, 0, 46, 700000))] -
Object is not serializable for JSON Seriazable (ajax call)
I'm working on a project where ive to make a call of a conversation_id and get all the relevent user messages in that conversation. On click on a list item (conversation id) im making an ajax call where i get messages and send back messages to ajax and print them. But at the time of JsonResponse where i try to send back the serialized json data, it says Conversation object is not JSON Serializable and I get Error 500 in Ajax error box Tried to use SimpleJson but didnt help. views.py def convo(request): if request.method == 'GET': convuserid = request.GET.get('id') try: convid = Conversation.objects.get( Q(Q(user1_id=convuserid) & Q(user2_id=request.user.id) ) | Q(Q(user2_id=convuserid) & Q(user1_id=request.user.id) )) request.session['convid'] = convid except: convid = None request.session['convid'] = None convmsgs = Message.objects.filter(conversation_id=convid) convmsgs_list = list(convmsgs) convmsgs_list_s = serializers.serialize( format='json', queryset=convmsgs_list) return JsonResponse({'data': json.loads(convmsgs_list_s)}) #This is where i get error.. myscript.js $.ajax({ type: 'GET', dataType: 'json', url: '/chat/convo/', data: { id: id }, success: function (data) { alert('success here') }, error: function (XMLHttpRequest, textStatus, err) { alert('error here') } }); I'm expecting the json array to be available in success of ajax but i get to error block of ajax. -
Sync data between two django sites
I have a django(postgreSQL) site in multple environments Local, staging, production I've tried using the manage.py dumpdata > db.json script to export the db dump from staging, and load the json file to local site with manage.py loaddata db.json. It seems to work, however, the old blog posts that was in the local site still persist after I loaded the datadump. Should I empty my tables before loading in new data? What's the are the practices? Is there any django package out there that handles this nicely? -
Django searching empty value, validation
i am creating a search app where a user can look for ingredients by writting some in search field. But when there is empty field, so there is no input q=, i would like to that he would get information that the input is required and keep him on this website. I do not know how to write it correcly for now i have written only if query == '': , but this is not what i need. Here is my views: def drink_list(request): template = "drinks/drink_list.html" return render(request, template) def search_results(besos): query = besos.GET.get('q') if query == "": y = "please put input" return render(besos, y) else: q = Q() for queries in query.split(): q |= (Q(ingredients__ingredient_name__icontains=queries)) #why it look for 'sok z cytryny' and show as well sok z limonki results = Recipe.objects.filter(q) template = "drinks/search_results.html" context = { 'results' : results, } return render(besos, template, context) my template: {% if results %} {% for drink in results %} <div> <p>{{ drink.recipe_name }}</p> <p>Preparation: {{ drink.preparation }}</p> <p>Ingredients: {% for ingredient in drink.ingredients.all %} {{ingredient.ingredient_name}}{% if not forloop.last %},{% endif %} {% endfor %} </p> </div> {% endfor %} {% else %} <div>Such ingredients do not exist</div> {% … -
Protection against editing another user's profile in django
I have trouble with protection against editing another user's profile and I don't have any idea how to solve this issue. Ofcourse I know that I can do sth like this: <a class="nav-item nav-link" href="{% url 'profile_change' user.pk %}"> or something similar. But I don't know what i can do in situation when user write him/herself webadress. I mean situation when user with pk = 2, would write adress: "website address/profile/change/1" Here is my models, views and urls: #urls.py urlpatterns = [ path('profile/', views.profile, name='profile'), path('profile/list/', views.ProfileListView.as_view(), name='profile_changelist'), path('profile/add/', views.ProfileCreateView.as_view(), name='profile_add'), path('profile/change/<int:pk>/', views.ProfileUpdateView.as_view(), name='profile_change') ] #views.py class ProfileCreateView(CreateView): model = Profile form_class = ProfileForm success_url = reverse_lazy('profile_changelist') def form_valid(self, form, **kwargs): form.instance.user = self.request.user return super().form_valid(form) class ProfileUpdateView(UpdateView): model = Profile fields = ('first_name', 'last_name', 'year') success_url = reverse_lazy('profile_changelist') @login_required def profile(request): if Profile.objects.filter(user=request.user.id).count() == 1: return render(request, 'profiles/profile.html') else: return HttpResponseRedirect('add') #models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) first_name = models.CharField(max_length=100, null=True) last_name = models.CharField(max_length=100, null=True) year = models.IntegerField(choices=YEARS, default=1) -
Order QuerySet depends of ordering Many to Many Field
I have two models, one of them contain many to many field. I want to order all values in many to many field in ascending order. My data and expected result - IMG In first column are all my data. Second column show result after using ordering by many to many field - it's dublicate the data. The third column is expected result - for getting correct result I transform my queryset to pandas dataframe and make all ordering to get correct result. But such method is very slowly. Is there another way to order data as I need. models.py class Publication(models.Model): title = models.CharField(max_length=30) class Meta: ordering = ('title',) def __str__(self): return self.title class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication, related_name = 'publications') def __str__(self): return self.headline views.py - first two function I used to get correct result. from django.shortcuts import render from .models import Article, Publication import pandas as pd def get_value_from_list(value, iter=0, sort_direct=True): try: value = value[iter] except IndexError: # value = 999999 if sort_direct == True else 0 value = 0 return value def get_unique_val(qs, sort_direct): df = pd.DataFrame(columns = ['id', 'headline', 'name', 'count']) for numb, item in enumerate(qs): df.loc[numb, 'id'] = item.id df.loc[numb, 'headline'] … -
Django Fernet Fields and Data in Transit
Does django-fernetfields also encrypt the data in transit? Or does it only encrypt the data at rest? I am wondering if I also need to encrypt the database connection from the Django app to the database server. I do have https enabled for the site. Or is django fernet fields already sending and receiving encrypted data across the wire (app<---->db). -
Can I modify a widget/field so that it is filtered further in Django/Python?
I have a form with a field in my models called employee_number, which is tied to another model, called Salesman, which holds all the data with all the employee names, numbers, dept, etc. Currently it works by only allowing submission of the form if the employee number entered is is salesman. What I'm trying to do is also filter it so that only employees that are part of team "MM" and "OM" and whose employee_status is "A" are the only ones able to submit. forms.py class WarehouseForm(AppsModelForm): class Meta: model = EmployeeWorkAreaLog widgets = { 'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}), } fields = ('employee_number', 'work_area', 'station_number') models.py class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_name = models.CharField(max_length=25) employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False) station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True) def __str__(self): return self.employee_number alldata/models.py class Salesman(models.Model): id = models.IntegerField(db_column='number', primary_key=True) team = models.CharField(max_length=2) employee_status = models.CharField(max_length=1, blank=True) -
Create Subdomain for each user
I want to know, what is the best efficient way to give each user a subdomain? I've seen these topics: Link1 and Link2 but these are too old (10 years ago). Is there any better way? -
Writing Form Data To SQLLite Database
I am trying to write my data from my forms data and I'm getting the following error. FYI: Total noob on python and django. AttributeError at /forms/ 'NewStudentForm' object has no attribute 'save' From reading online its because I'm doing in my forms.py is (forms.Forms) and it doesn't use the .save() attribute. What is the easiest way to fix this ? Thank you! #forms.py from django import forms from .models import StudentCheck class NewStudentForm(forms.Form): startdate = forms.DateField(label = "Start Date", required= True) esy = forms.BooleanField(label = "ESY", required= False) ten_month_school_year = forms.BooleanField(label= "Ten Month School Year", required= False) other = forms.BooleanField(required= False) intakedate = forms.DateField(label = "Intake Date", required= True) grade = forms.CharField(label= "Grade",max_length=2) firstname = forms.CharField(label = "First Name", max_length=50) lastname = forms.CharField(label = "Last Name", max_length=60) address = forms.CharField(label = "Address", max_length=100) city = forms.CharField(label = "City", max_length=100) state = forms.CharField(label = "State", max_length=30) zipcode = forms.CharField(label = "Zip Code",max_length=5) parent_one_name = forms.CharField(label = "Parent 1",max_length=100) parent_one_phone = forms.CharField(label = "Phone",max_length=12) parent_one_email = forms.CharField(label = "Email",max_length=100) parent_two_name = forms.CharField(label= "Parent 2",max_length=100) parent_two_phone = forms.CharField(label= "Phone",max_length=12) parent_two_email = forms.CharField(label = "Email", max_length=100) #models.py from django.db import models from django.utils import timezone # Create your models here. class StudentCheck (models.Model): … -
django 404 error http://*********:8080/ciopsmenu/searchlit/
I am trying to navigate to an app from a link on a page(the ciopsmenu) which is a view located in the homepage app but I am getting a 404 error. I tried to adding the path(searchLit/urls.py) using the include module to my project level urls.py file and I also tried adding the same line to my homepage/urls.py file #ciopsdb/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('homepage.urls')), path('ciopsmenu/searchlit/', include('searchLit.urls')), ] #homepage/urls.py from django.urls import path, include from . import views urlpatterns = [ path('', views.index, name='index'), path('accounts/', include('django.contrib.auth.urls')), path('ciopsmenu/', views.ciopsMainMenu, name='ciopsMainMenu'), path('ciopsmenu/searchlit/',include('searchLit.urls')), ] #installed apps from settings.py INSTALLED_APPS = [ 'searchLit', 'homepage', 'base', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mod_wsgi.server', Page not found (404) Request Method: GET Request URL: http://*******:8080/ciopsmenu/searchlit/ Using the URLconf defined in ciopsdb.urls, Django tried these URL patterns, in this order: admin/ [name='index'] accounts/ ciopsmenu/ [name='ciopsMainMenu'] ciopsmenu/searchlit/ ciopsmenu/searchlit/ [name='searchLit'] ciopsmenu/searchlit/ ciopsmenu/searchlit/ [name='searchLit'] The current path, ciopsmenu/searchlit/, didn't match any of these. -
Formset validation not working - receiving KeyError
I am trying my first formset and stuck on validation. I have combined a normal form ProgramSelector with a formset. Everything works so far in terms of saving the data but validation is giving me a real headache. I am simply not understanding how this part works. How do I get this to display errors in the forms like it normally would? Right now I am getting KeyError 'headline' and the ProgramSelector clean() doesn't seem to be doing anything. I have searched every post I can find and nothing seems to working or helping me figure this out so here I am. Thanks! model: class PropertySubmission(models.Model): BANNER_CHOICES = ( ('NB', 'No Banner'), ('FL', 'For Lease'), ('FS', 'For Sale'), ('NL', 'New Listing'), ('SD', 'Sold'), ('LD', 'Leased'), ('RD', 'Reduced'), ('NP', 'New Price'), ('SC', 'Sold Conditionally'), ('CB', 'Custom Banner'), ) image = models.ImageField(upload_to=user_directory_path, blank=True) #image_thumbnail = ImageSpecField(source='image', processors=[ResizeToFill(300, 250)], format='JPEG', options={'quality':60}) mls_number = models.CharField(max_length=8, blank=True) headline = models.CharField(max_length=30) details = RichTextField() banner = models.CharField(max_length=2, choices=BANNER_CHOICES) author = models.ForeignKey(User, on_delete=models.CASCADE) date_posted = models.DateTimeField(default=timezone.now) date_modified = models.DateTimeField(default=timezone.now) program_code = models.ManyToManyField(Program) product = models.ForeignKey('Product', on_delete=models.SET_NULL, null=True) production_cycle = models.ManyToManyField('ProductionCycle', null=True, blank=True) shell = models.ForeignKey('Shell', on_delete=models.SET_NULL, null=True, blank=True) card_delivery_instructions = models.CharField(max_length=1000, blank=True) card_delivery_instructions_image = models.ImageField(upload_to=card_delivery_instructions_image_path, blank=True) forms: … -
Deploying Django on AWS Beanstalk Getting Erorr 500 WSGI Error
Been on this for hours. Trying to deploy a Django APP on AWS Elastic Beanstalk, but since been having errors. Logs: [Mon Nov 04 20:29:56.672898 2019] [:error] [pid 5877] [remote 172.31.27.176:8] raise RuntimeError("populate() isn't reentrant") [Mon Nov 04 20:29:56.672912 2019] [:error] [pid 5877] [remote 172.31.27.176:8] RuntimeError: populate() isn't reentrant [Mon Nov 04 20:29:57.139970 2019] [:error] [pid 5877] [remote 172.31.27.176:8] mod_wsgi (pid=5877): Target WSGI script '/opt/python/current/app/vendease/wsgi.py' cannot be loaded as Python module. [Mon Nov 04 20:29:57.140026 2019] [:error] [pid 5877] [remote 172.31.27.176:8] mod_wsgi (pid=5877): Exception occurred processing WSGI script '/opt/python/current/app/vendease/wsgi.py'. [Mon Nov 04 20:29:57.140136 2019] [:error] [pid 5877] [remote 172.31.27.176:8] Traceback (most recent call last): [Mon Nov 04 20:29:57.140169 2019] [:error] [pid 5877] [remote 172.31.27.176:8] File "/opt/python/current/app/vendease/wsgi.py", line 16, in <module> [Mon Nov 04 20:29:57.140174 2019] [:error] [pid 5877] [remote 172.31.27.176:8] application = get_wsgi_application() [Mon Nov 04 20:29:57.140180 2019] [:error] [pid 5877] [remote 172.31.27.176:8] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Mon Nov 04 20:29:57.140184 2019] [:error] [pid 5877] [remote 172.31.27.176:8] django.setup(set_prefix=False) [Mon Nov 04 20:29:57.140189 2019] [:error] [pid 5877] [remote 172.31.27.176:8] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup [Mon Nov 04 20:29:57.140193 2019] [:error] [pid 5877] [remote 172.31.27.176:8] apps.populate(settings.INSTALLED_APPS) [Mon Nov 04 20:29:57.140198 2019] [:error] [pid 5877] [remote 172.31.27.176:8] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/apps/registry.py", line … -
How to create a readonly field inside Django ModelForm from a value in the Model
I have the below code for a model in Django: from django.db import models from django.db.models.signals import pre_save from django.utils.text import slugify from django.conf import settings class Book(models.Model): added_by = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True, related_name='book_add', on_delete=models.CASCADE) last_edited_by = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, blank=True, related_name='book_edit', on_delete=models.CASCADE) title = models.CharField(max_length=120) description = models.TextField(null=True, blank=True) slug = models.SlugField() updated = models.DateTimeField(auto_now_add=False, auto_now=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) def __str__(self): return self.title def pre_save_book(sender, instance, *args, **kwargs): slug = slugify(instance.title) instance.slug = slug pre_save.connect(pre_save_book, sender=Book) My objective is to have two different kinds of forms one for changing a Book object and another one for adding a Book object. Hence i have the below code for admin.py and forms.py: admin.py: from django.contrib import admin from .models import Book from .forms import BookAddForm, BookChangeForm class BookAdmin(admin.ModelAdmin): readonly_fields = ["authorname"] def authorname(self, obj, *args, **kwargs): return obj.added_by.username def get_form(self, request, obj=None, **kwargs): if not obj: self.form = BookAddForm else: self.form = BookChangeForm return super().get_form(request, obj, **kwargs) def save_model(self, request, obj, form, change): obj.added_by = request.user super().save_model(request, obj, form, change) admin.site.register(Book, BookAdmin) forms.py: from django import forms from .models import Book class BookAddForm(forms.ModelForm): class Meta: model = Book fields = [ 'title', 'description' ] exclude = ['authorname'] class BookChangeForm(forms.ModelForm): … -
Is there a way to remove directories along with removing media files in Django?
As far as I know, it's quite simple to remove a media file when calling the delete() method. However, I'd like to ask if there's also a way to remove the path that the media file was located. (wait, is it even a good practice to remove all the empty directories?) def delete(request, post_pk): ... post = Post.objects.get(pk=post_pk) post.image.delete() # I want to delete the empty directories as well here post.delete() ...