Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django staticfiles not found
Help me please! I feel like bad wizard, my kind of magic ...doesn't work... Python 2.7.13 , django.VERSION (1, 8, 0, 'final', 0) &: INSTALLED_APPS = ( [...] 'django.contrib.staticfiles', &: STATIC_URL = '/static/' STATIC_ROOT = '' STATICFILES_DIRS = ( ('static', os.path.join(os.path.dirname(BASE_DIR), 'static')), ('node_modules', os.path.join(os.path.dirname(BASE_DIR), 'node_modules')), ) &: $ python manage.py findstatic rarrow.png --verbosity 2 No matching file found for 'rarrow.png'. Looking in the following locations: /home/user/Pulpit/geoHP/static <-- here IS this file !!!!!!! for sure! /home/user/Pulpit/geoHP/node_modules /usr/local/lib/python2.7/dist-packages/django/contrib/admin/static /usr/lib/python2.7/dist-packages/django_tables2/static /usr/local/lib/python2.7/dist-packages/djng/static More over, on web content is properly url for files and css and js, but of course doesn't work... The static dir and files privileges are '777'. I have no idea what should I check or do more... somebody helps? -
Submit search query along with another form
I have a Web page where there is a form with filters. On submitting this form a table with the results is displayed. Now I want to add a search field in a second form above the table , which, when submitted, further eliminates the results. How can the search query be submitted along with the filters' values simultaneously and vice versa? Is there a non js way as well? -
Not able to display the Content of Table
models.py has class Question(models.Model): Question_Id = models.AutoField(primary_key=True) Question_Text = models.TextField(max_length=1000) def __str__(self): return self.Question_Text def __int__(self): return self.Question_Id class QuestionChoices(models.Model): Choice_Id = models.AutoField(primary_key=True) Question_Choices_Question_Id = models.ForeignKey("Question", on_delete=models.CASCADE) Choice = models.TextField(max_length=500) Is_Right_Choice = models.BooleanField(default=False) views.py file has the below def QuestionDisplay(request): retrieved_questions_id = Question.objects.values("Question_Id") retrieved_questions = Question.objects.filter(Question_Id = retrieved_questions_id) display_content = {retrieved_questions_id: retrieved_questions} return render(request, 'cgkapp/Question_page.html', context=display_content) templates folder questions.html has {% block body_block %} <table> <thead> <th>Questions</th> </thead> {% for quest in display_content %} <tr> <td>{{quest.Question_Text}</td> </tr> {% endfor %} </table> {% endblock %} The page displays the Questions as the Table header but not the actual questions from the models. What could be the reason? -
Glitch in dynamically generated formset using JQuery
I have a form created with dynamic child forms create using this plugin - https://github.com/elo80ka/django-dynamic-formset. Everything works fine. It's just that when a validation error comes up the button to generate new form line dynamically gets repeated. Ideally, this button should only be present once at the end. Please look at the image below. Can someone advise how to fix this issue? Relevant codes: forms.py class POHeaderForm(forms.ModelForm): class Meta: model = POHeaderModel fields = '__all__' def __init__(self, *args, **kwargs): super(POHeaderForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs = {'class': 'form-control form-control-sm'} class POBodyForm(forms.ModelForm): item_number = forms.ModelChoiceField(queryset=InventoryModel.objects.all(), required=False) class Meta: model = POBodyModel fields = '__all__' def __init__(self, *args, **kwargs): super(POBodyForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs = {'class': 'form-control form-control-sm'} self.empty_permitted = False def clean(self): item = self.cleaned_data.get('item_number') description = self.cleaned_data.get('description') if item is None and description is None: raise forms.ValidationError("Please fill either item number or description") POFormSet = forms.inlineformset_factory(POHeaderModel, POBodyModel,form=POBodyForm, extra=1) Models.py alphanumeric = RegexValidator(r'^[0-9a-zA-Z .-]*$', 'No special characters are allowed.') # Create your models here. class POHeaderModel(models.Model): date = models.DateTimeField(blank=False, default=timezone.now) reference = models.CharField(validators=[alphanumeric], max_length=25, blank=True, null=True) supplier = models.ForeignKey(SuppliersModel, on_delete=models.PROTECT) note = models.CharField(validators=[alphanumeric], max_length=300, blank=True, null=True) total = models.DecimalField(decimal_places=2, max_digits=10, validators=[MinValueValidator(0)]) class POBodyModel(models.Model): PO = models.ForeignKey(POHeaderModel, … -
Django : How to add/remove/update translation phrases (in po files) in django admin area?
How can we manage translation phrases stored in local\fa\LC_MESSAGES\django.po files by Django Admin area ? I am looking for a package which able to update and compile django translation files like updating models in django Admin area I am using Django 1.10 -
How to restrict foreign key objects for autocomplete search results in django ModelAdmin.autocomplete_fields?
Following this answer, I was able to filter foreign keys choices to select: But when I mark spm as autocomplete_field:autocomplete_fields = ['spm'], the spm field becomes from select field to autocomplete search field: But the foreign key choices are not restricted as configured in "formfield_for_foreignkey" any more. Even when I am attaching the widget inside formfield_for_foreignkey method, spm autocomplete options are getting restricted: @admin.register(CustomModel) class CustomModelAdmin(admin.ModelAdmin): #autocomplete_fields = ['spm'] search_fields = ['name'] def get_form(self, request, obj=None, **kwargs): request.current_object = obj return super(CustomModelAdmin, self).get_form(request, obj, **kwargs) def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'spm': instance = request.current_object if instance.brand and instance.memory_size: filtered_qs=StandardProductWithMemorySize.objects.filter( product__brand=instance.brand, memory_size=instance.memory_size ) kwargs['queryset'] = filtered_qs db = kwargs.get('using') kwargs['widget'] = AutocompleteSelect(db_field.remote_field, self.admin_site) return super( CustomModelAdmin, self ).formfield_for_foreignkey(db_field, request, **kwargs) -
getting values of QuerySet in django
how can I get value of course_code in this QuerySet ? <QuerySet [{'course_code': 11}]> -
The field polls.UserProfile.user was declared with a lazy reference to 'polls.user', but app 'polls' doesn't provide model 'user'
So I've been using the website: https://www.fomfus.com/articles/how-to-use-email-as-username-for-django-authentication-removing-the-username To build a section of my project, but I keep getting the error ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'polls.user', but app 'polls' doesn't provide model 'user'. The field calendarium.Event.created_by was declared with a lazy reference to 'polls.user', but app 'polls' doesn't provide model 'user'. The field calendarium.Occurrence.created_by was declared with a lazy reference to 'polls.user', but app 'polls' doesn't provide model 'user'. The field filer.Clipboard.user was declared with a lazy reference to 'polls.user', but app 'polls' doesn't provide model 'user'. The field filer.File.owner was declared with a lazy reference to 'polls.user', but app 'polls' doesn't provide model 'user'. The field filer.Folder.owner was declared with a lazy reference to 'polls.user', but app 'polls' doesn't provide model 'user'. The field filer.FolderPermission.user was declared with a lazy reference to 'polls.user', but app 'polls' doesn't provide model 'user'. The field polls.UserProfile.user was declared with a lazy reference to 'polls.user', but app 'polls' doesn't provide model 'user'. My App name is called polls, I've made sure that 'polls' is installed in my settings and AUTH_USER_MODEL = 'polls.User' To tell Django that this is the model I want to use. My models.py looks … -
django only allowing super user for authentication
I am getting problem with django authentication, Only superuser is able to authenticate. Here is my Model #models.py class UserManager(BaseUserManager): def create_user(self, username, email, password): if not email: raise ValueError('Users must have an email address') elif not username: raise ValueError('Users must have an username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuse.................. class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField( verbose_name='username', max_length=30, unique=True, ) phonenumber = PhoneNumberField(verbose_name="phonenumber",max_length=13, null=True,unique=True) name = models.CharField(max_length=30, blank=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' ............. In my setting I added this. #settings.py AUTH_USER_MODEL = 'accounts.User' AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'accounts.backends.MyPhonenumberBackend', ) This is my backend #backends.py from django.contrib.auth import get_user_model class MyPhonenumberBackend(object): def authenticate(self, username=None, password=None): my_user_model = get_user_model() try: user = my_user_model.objects.get(phonenumber=username) if user.check_password(password): return user except my_user_model.DoesNotExist: return None except: return None def get_user(self, user_id): my_user_model = get_user_model() try: return my_user_model.objects.get(pk=user_id) except my_user_model.DoesNotExist: return None My views #views.py def seller_login_view(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username,password=password) if user: if user.is_active: login(request,user) return HttpResponseRedirect(reverse('home')) else: return HttpReponse('Account is not active') else: print('Someone tries to login and failed') print('username: {} and password {}'.format(username,password)) return … -
How to use pdfsizeopt in Django python
I am using pdfsizeopt to reduce pdf sizes. it is working fine when I run it in windows CMD but not working Django Python code. Flow : I am uploading a file and then trying to resize it code is following def sizeofpdfs(request,uploaded_file_name): try: fs = FileSystemStorage() uploaded_file_url = fs.url(uploaded_file_name) new_filename = fs.url(uploaded_file_name.split(".")[0]+"_new.pdf") command = "pdfsizeopt "+ uploaded_file_url +" smallsize.pdf" p = subprocess.call(command, shell=True) if p==0: return new_filename except subprocess.CalledProcessError as e: print('CalledProcessError', e) File get uploaded when it try to resize it throws the following error. It is a path error. Can someone suggest me the correct way to use it. -
Django: Can I use objects.filter() for generic foreignkey?
symbol.py class Symbol(BaseModel): name = models.CharField(max_length=30,) class Meta: abstract = True class StockSymbol(Symbol): market = models.CharField(max_length=10,) my_daily_price = GenericRelation(MyDailyPrice) daily_price.py class DailyPrice(BaseModel): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') class Meta: abstract = True class MyDailyPrice(DailyPrice): open = models.DecimalField( max_digits=15, decimal_places=2, ) What I want to do is, symbol = StockSymbol.objects.first() MyDailyPrice.objects.filter(content_object=symbol) But it occured errors: FieldError: Field 'content_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. StockSymbol already has GenericRelation. What's wrong with it? Or do I have to override ojbect manager? -
How do I remove default whitespace in template?
I'd like to list a series of items separated by commas. But if an item after the first doesnt exist, I don't want the comma or item to appear. So I've implemented this: <em>{{object.item1|default_if_none:""}}</em> {% if object.item2 %} <em>, {{object.item2|default_if_none:""}},</em> {% endif %} <em>{{object.item3|default_if_none:""}}</em> If object.item2 exists, it'll put a whitespace after item1--before the comma. When it displays, it'll look something like: "I_am_item_one , I_am_item_two, Item_three" What's the best way to fix this? -
How to make django register users with emails instead of username
I am trying to make a website that registers users with first name, last name, email, and password. I have tried writing this form and using it in the views from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class RegisterationForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ( 'first_name', 'last_name', 'email', 'password1', 'password2', ) def save(self, commit=True): user = super(RegisterationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user and using it in the views from django.shortcuts import render, redirect from Users.forms import RegisterationForm from django.contrib.auth import authenticate, login def home(request): return render(request, 'Users/index.html') def map_page(request): return render(request, 'Users/map_page.html') def register (request): if request.method == 'POST': form = RegisterationForm(request.POST) if form.is_valid(): form.save() return redirect('/LoginPage/') else: form = RegisterationForm() args = {'form': form} return render(request, 'Users/index.html', args) However when I do it this way and I fill it in I get an error of UNIQUE constraint failed: auth_user.username I was wondering if there is a way to not use a username and have them signup and login with password and email. I have tried making a backend and included it in the settings and that did not work. … -
Creating Single-Page Application in Python
So I have an application that is written in Python and I want to create a single-page application that allows others to use it. One possible solution is to use Django but I don't want to keep persistent databases on the server. The application is small enough for it to work in-browser on the client's side but the only SPA frameworks I can see seem to use Javascript client-side which would be a problem for me. Is there any way to create an app that meets these requirements? -
Nested serialization Django Rest Framework
Hello guys i'm back again i have a little trouble about my problem. I want to create Account in my Django Project. I extend user model using OneToOneField. here is my mode.py class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone_number = models.CharField(max_length=15, unique=True, null=False, blank=False) birth_date = models.DateField() address = models.TextField() district = models.ForeignKey(District, on_delete=models.CASCADE, related_name='district') created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created_at', ] def __str__(self): return self.user.username and here is my serializers.py class UserSerializer(serializers.ModelSerializer): id = serializers.IntegerField(source='account.id', read_only=True) phone_number = serializers.CharField(source='account.phone_number') birth_date = serializers.DateField(source='account.birth_date') address = serializers.CharField(source='account.address') class Meta: model = User fields = ( 'id', 'first_name', 'last_name', 'username', 'email', 'password', 'phone_number', 'birth_date', 'address' ) def update_or_create_account(self, user, account_data): Account.objects.update_or_create(user=user, defaults=account_data) def create(self, validated_data): account_data = validated_data.pop('account', None) user = super(UserSerializer, self).create(validated_data) self.update_or_create_account(user, account_data) return user def update(self, instance, validated_data): account_data = validated_data.pop('account', None) self.update_or_create_account(instance, account_data) user = super(UserSerializer, self).update(instance, validated_data) return user class AccountSerializer(serializers.ModelSerializer): user = UserSerializer(required=True) created_at = serializers.DateTimeField(read_only=True) class Meta: model = Account fields = ( 'user', 'district', 'created_at' ) and here for views.py class AccountList(APIView): def get(self, format=None): account = Account.objects.all() serializer = AccountSerializer(account, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = AccountSerializer(data=request.data) if User.objects.filter(email=request.data['user']['email']).exists(): return Response(data={'email': 'Email already taken, use another email'}, status=status.HTTP_400_BAD_REQUEST) … -
how to construct this Django ORM queryset query?
I'm trying to determine how to construct a query. I have two models from an external database that I"m trying to import into a different schema. The source data has two tables: - Group (basically, a musical band.) - Membership (a list of those in the band through time) In the Memberships, I have fields representing the person and band, with create dates and update dates, as well as other relevant data. Here's the problem: the Membership rows don't have any field that represents which is the canonical record, and they mix and match persons and dates and other data. What I'm doing currently is taking all the Memberships for a given band, running distinct on them for the combination of band and person and using those results to query the Memberships again for the latest instance of each particular combination. While this works, as you might imagine is is unspeakably slow and I know there must be a better way. So I'm looking for how to use some of the advanced django query expressions (Window? Over, F-expressions?) to get this done as much as possible on the database. Here is the code that is getting me the records I … -
creating models inctances from button click
I am new to django and I build an online restaurant website as a task . I have a problem in getting orders into data base . here are the codes models.py from django.db import models from django.contrib import admin from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): user = models.OneToOneField(User) phone = models.IntegerField() address = models.CharField(max_length=500) def create_profile(sender , **kwargs): if kwargs['created'] : user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile , sender=User) class Category(models.Model): category_title = models.CharField(max_length=100 , unique=True) def __str__(self): return self.category_title class Order (models.Model): time = models.DateTimeField(auto_now_add=True) total = models.IntegerField() created_by = models.ForeignKey(User, related_name='orders') class Item (models.Model): name = models.CharField(max_length=100 ,unique=True) details = models.CharField(max_length=1000) price = models.IntegerField() item_logo = models.FileField() category = models.ForeignKey(Category, related_name="items" ,on_delete= models.CASCADE) order = models.ForeignKey(Order, related_name="orderItems", null=True, blank=True) def __str__(self): return self.name class ItemInline(admin.TabularInline): model = Item class CategoryAdmin(admin.ModelAdmin): inlines = [ ItemInline, ] views.py from django.http import Http404 from .models import Category, Item , Order from django.shortcuts import render, redirect from django.core.urlresolvers import reverse_lazy from django.contrib.auth import authenticate , login from django.views import generic from django.views.generic import View from .forms import UsrForm class IndexView(generic.ListView) : template_name = 'res/base.html' context_object_name = 'all_categories' def get_queryset(self): return Category.objects.all() def detail(request, category_name): try: category = Category.objects.get(category_title = … -
Override Django Handler404 with JSON type handler
I'm using Django 2.0.1 and I'm trying to override Django 404 page with another response. Instead of returning a regular template, I want to return a JSON response. here is my project/urls.py from django.conf.urls import include from django.contrib import admin from django.urls import path from django.conf.urls import handler404 from django.http import JsonResponse urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('accounts.urls')) ] def response(status=200, message='Not Found', data=None): data = {'status': 404, 'message': message, 'data': data} return JsonResponse(data=data, status=status) handler404 = response(status=404) but by it 404 returns it still return me the basic Django 404 page even if I change Debug option to True in settings.py file -
AngularJs: ng-click is not calling the method.
I am just learning AngularJS and I started working with it in Django. I created an array that I would display as a list and provide an Input field for the user to add more items to it. {% verbatim %} <div ng-controller="ScrumBoardController"> <div ng-repeat="list in data"> <h3>{{ list.name }}</h3> <ul> <li ng-repeat="card in list.cards">{{ card.title }}</li> </ul> <input type="text" ng-model="new_title"></input>{{ new_title }} <button ng-click="addition(list, new_title">ADD</button> </div> </div> {% endverbatim %} The above HTML code is going through all the data and displaying it properly, but whenever I try to call the ng-click to add a user argument to the card it's not working. The only thing I could think of was changing the name of the function and that didn't work either. (function () { 'use strict'; angular.module('scrumboard.demo', []) .controller('ScrumBoardController', ['$scope', ScrumBoardController]); function ScrumBoardController($scope){ $scope.addition = function (list, title){ var card = { title: title }; list.cards.push(card); }; $scope.data = [ { name: 'django demo', cards: [ { title: 'Create Models' }, { title: 'Create View' }, { title: 'Migrate Database' } ] }, { name: 'Angular Demo', cards: [ { title: 'Write Html' }, { title: 'Cry' }, { title: 'repeat' } ] } ]; } })(); -
Django: Grouping of records
Apologies if the title of question is not correct. Please someone correct it if the detail here gives you idea what I am asking for. I am not English speaker so may make a mistake in wording the title. I have this model: class ClinicDoctor(models.Model): doctor = models.ForeignKey('User', related_name='doctorsF') # single quotes (') because User table is defined down the code. clinic = models.ForeignKey(Clinic, related_name='clinicsF') I am trying to fetch all doctor records and their clinics. Some doctors may have multiple clinics. In my template I loop over the below query set: doctorsQuerySet = ClinicDoctor.objects.filter(doctor__groups__name='Doctor') This returns records BUT I wanted to show records in a table like this: DoctorHeader-------------ClinicsHeader Doctor 1 ----------------Clinic 1, Clinic 2. Doctor 2 ---------------- Clinic 3 Doctor 3 ---------------- Clinic 4, Clinic 5, clinic 7 The idea is that I want to show every Doctor only once and then put all his related clinics in that single row of that Doctor. Right now I am looping over the query set in the template but that is going to show same doctor record multiple times(as many as associated clinics). Is there any way in which I can modify that Query above to achieve the grouping or … -
How to handle favicon request in Django rest framework?
I am coming from nodejs and i have a nextjs frontend that communicate with a django rest Api. However, each time i make a request to my django api, the app do an additional request : GET /favicon.ico I've tried to add favicon route in urls.py favicon_view = RedirectView.as_view(url='/static/images/favicon.ico', permanent=True) url(r'^favicon$',favicon_view) but it doesn't works Any suggestion ? -
Custom ManyToManyfield ordering
Is there a way to use user-defined ordering on a ManyToManyField without killing performance / cluttering the database? EX: I have a model: class MyModel: myfield = models.ManyToManyField(other_model, ...) And I have a form which allows adding multiple other_model objects and I want to allow the user to sort / order these (say using jquery-ui sortable or another method).. However, this isn't reflected on the front-end since this ordering state isn't preserved - just the objects being added to the relation. All I can think of is to just create a new model instance every single time with the order attached (as a custom many to many field) and adding to the M2M but that's killing the DB / structure instead of having single field instances / preventing duplicates. -
pip install requirements.txt not working properly
I'm trying to install all my Python/Django packages on my Digital Ocean Django server. I have my requirements.txt in the root directory, so I perform pip install -r requirements.txt - however it doesn't work. Here's my requirements.txt: amqp==2.2.2 billiard==3.5.0.3 celery==4.1.0 coverage==4.4.2 decorator==4.0.11 defusedxml==0.4.1 Django==1.11.8 django-allauth==0.29.0 django-apptemplates==1.2 django-celery-beat==1.0.1 django-common-helpers==0.9.1 django-cron==0.5.0 django-el-pagination==3.1.0 django-fs-trumbowyg==0.1.4 django-markdown-deux==1.0.5 django-trumbowyg==1.0.1 django-widget-tweaks==1.4.1 get==0.0.0 imageio==2.1.2 kombu==4.1.0 markdown2==2.3.1 moviepy==0.2.3.2 numpy==1.13.3 oauthlib==2.0.1 olefile==0.44 Pillow==4.0.0 post==0.0.0 public==0.0.0 python-magic==0.4.12 python3-openid==3.0.10 pytz==2017.3 query-string==0.0.0 request==0.0.0 requests==2.11.1 requests-oauthlib==0.7.0 schedule==0.4.3 setupfiles==0.0.0 tqdm==4.11.2 vine==1.1.4 here's the log: Collecting amqp==2.2.2 (from -r requirements.txt (line 1)) Using cached amqp-2.2.2-py2.py3-none-any.whl Collecting billiard==3.5.0.3 (from -r requirements.txt (line 2)) Using cached billiard-3.5.0.3-py3-none-any.whl Collecting celery==4.1.0 (from -r requirements.txt (line 3)) Using cached celery-4.1.0-py2.py3-none-any.whl Collecting coverage==4.4.2 (from -r requirements.txt (line 4)) Using cached coverage-4.4.2-cp35-cp35m-manylinux1_x86_64.whl Collecting decorator==4.0.11 (from -r requirements.txt (line 5)) Using cached decorator-4.0.11-py2.py3-none-any.whl Collecting defusedxml==0.4.1 (from -r requirements.txt (line 6)) Using cached defusedxml-0.4.1.tar.gz Requirement already satisfied: Django==1.11.8 in ./env/lib/python3.5/site-packages (from -r requirements.txt (line 7)) Collecting django-allauth==0.29.0 (from -r requirements.txt (line 8)) Using cached django-allauth-0.29.0.tar.gz Collecting django-apptemplates==1.2 (from -r requirements.txt (line 9)) Using cached django-apptemplates-1.2.tar.gz Collecting django-celery-beat==1.0.1 (from -r requirements.txt (line 10)) Using cached django_celery_beat-1.0.1-py2.py3-none-any.whl Collecting django-common-helpers==0.9.1 (from -r requirements.txt (line 11)) Using cached django-common-helpers-0.9.1.tar.gz Collecting django-cron==0.5.0 (from -r requirements.txt (line 12)) Using cached django-cron-0.5.0.tar.gz … -
Django Managing forms for related models using parent form field vlaue
I have three models, Problem, Choice, and Solution. Choice and Solution models are related to Problem by Foreign Key. That is, a problem can have many choices and solutions. Number of choices required for a problem is controlled a Problem.type field. I want to make a form in which lets a user edit Problem, Choice(s) and Solution in the same form. I am able to display Problem and Solution forms easily and handling the Choice form/formsets using Ajax. My Questions: Is there a more Pythonic (Djangonic) way of doing these kind of stuffs? Suppose I refresh my browser in the midway, knowingly or accidentally, Firefox shows all the fields as they were (including data filled in, and problem type selected) before refreshing, but the part of the form which was rendered via Ajax is lost. Is this a expected behaviour? In Chrome, entire form is reset upon refreshing. Is this behaviour expected? How I can prevent loss of half filled form data? One of the solutions that I have thought of is filling up the form step by step- First the problem details, followed by choices and Solution at last. This approach makes editing previous steps difficult. A user might … -
Ordering Django ModelCluster many to many field
Is there a way to re-order a (many-to-many) field using a ParentalManyToManyField from modelcluster.fields when editing an object instance? As I understand it the cluster defers the m2m save and it caches this. My object is a wagtail page and I'm doing the following: form.save(commit=False) # Clear the cache of the m2m fields.... Using self.object.(field).clear() form.save_m2m() # Save a wagtail revision for moderation through the admin interface After approving the change the fields are still int he same order? Is this not possible?