Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Styling many to many field in form
I created form based on this model: class Playlist(models.Model): title = models.CharField(max_length=40, null=True) description = models.CharField(max_length=500, null=True) author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) miniature = models.ImageField(upload_to='images/playlist', default="defaults/default.png", validators=[validate_miniature_file_extension]) tracks = models.ManyToManyField(Track) form: class AddPlaylist(forms.ModelForm): class Meta: model = models.Playlist fields = ['title', 'description', 'tracks', 'miniature'] widgets = { 'description': Textarea(attrs={'cols': 30, 'rows': 10}), } When I rendered it, behavior of "tracks" surprised me. It looks like this: First thing: Names - I want to name those tracks with (Track is model and has field "title") Track.title. How can I do it? I didn't found anything when I was searching for widgets to ManyToManyField. Second thing: Selecting - for example when I click on Track object(1) when Track object(4) is selected, obj(4) becomes unselected, and obj(1) becomes selected. Using shift provides to select fields between objects (between obj(1) and obj(3) for example), but user can't select obj(1) and obj(3) for example. -
Django: "How often" do I need @transaction.atomic
atomic blocks can be nested. In this case, when an inner block completes successfully, its effects can still be rolled back if an exception is raised in the outer block at a later point. Do I understand correctly that I don't need to add @transaction.atomic decorator before do_stuff()? If do_staff changes the database and an exception occurs, the parent view_func will take care of the rollback. from django.db import transaction @transaction.atomic def viewfunc(request): # This code executes inside a transaction. do_stuff() That's not neccesary, correct? from django.db import transaction @transaction.atomic def do_stuff(): do_something_in_the_database() @transaction.atomic def viewfunc(request): # This code executes inside a transaction. do_stuff() -
Fetching different username registed in Users table and saving it as foreign key using formset
I am saving a form having formset as below:- forms.py AuthorFormset = modelformset_factory( Author, fields=('title','content','due_date','author' ), extra=1, widgets={'title': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Author Name here'}), 'content': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Description'}), 'due_date': forms.DateInput(attrs={ 'class': 'form-control', 'placeholder': 'Date'}), 'author': forms.TextInput(attrs={ 'class': 'form-control author-input', 'placeholder': 'Participants' }), In my models.py I am saving author as the foreign key of user table. class Author(models.Model): title = models.CharField(max_length=100, null=True) content = models.TextField(null=True) due_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) class Meta: db_table = 'author' def __str__(self): return self.author.username However on debugging I found that the formset object that is returned in the POST request says 'id': 'none' for author field. I think 'author' input field is only accepting userId and not username. I am new to django and I donot know how to save username from userId from User model. Please point me in the right direction. -
Django Join - I need all fields of parents and child table
I need two fields on the Result Please help me headline,publications,title i need to return on the all fields. But it returns only on headline,publications i have joined the Parent and child table. But i cant get the Child table Fields. I need a Two table Fields. django.core.exceptions.FieldError: Cannot resolve keyword 'headline' into field. Choices are: id, manufactures, title class Car(models.Model): title = models.CharField(max_length=30) class Meta: ordering = ('title',) def __str__(self): return self.title class Manufactures(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Car) class Meta: ordering = ('headline',) Car.objects.filter(manufactures__headline__startswith="Title").values('title') -
Custom pagination in djangotables2
can anyone tell me how do I add a bootstrap 'pagination' class to my pagination element in djangotables2? I have tried looking in documentantion but it doesn't say anywhere. Thanks in advance -
Need an advice on the widget ClearableFileInput in Django
Question is about the following: How to get rid of the default “upload” button in Imagefield or Filefield represented by ClearableFileInput in a simple way? I have done it already but it seems like I made it in a long way of things, lets say. I made new widget based on the ClearableFileInput class CustomClearableFileInput(ClearableFileInput): template_name = 'customclearablefileinput.html' and have overridden template_name Standard Django template for this widget looks like this( originally unformatted): {% if widget.is_initial %}{{ widget.initial_text }}: <a href="{{ widget.value.url }}">{{ widget.value }}</a>{% if not widget.required %} <input type="checkbox" name="{{ widget.checkbox_name }}" id="{{ widget.checkbox_id }}"> <label for="{{ widget.checkbox_id }}">{{ widget.clear_checkbox_label }}</label>{% endif %}<br> {{ widget.input_text }}:{% endif %} <input type="{{ widget.type }}" name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %}> Finlay I have changed the standard button in the following way: {% load bootstrap4 %} {% load static %} {% load thumbnail %} {% if widget.is_initial %} <a href="{{ widget.value.url }}"><img class=" ml-3" src="{% thumbnail widget.value "small" %}"></a> {% if not widget.required %} {% endif %}<br> {% endif %} <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="inputGroupFileAddon01">Upload</span> </div> <div class="custom-file"> <input type="file" class="custom-file-input" id="inputGroupFile01" aria-describedby="inputGroupFileAddon01"> <label class="custom-file-label" for="inputGroupFile01">Choose file</label> </div> </div> Question is – is it any way to do … -
How do I apply Mixins to all CBVs in a django app?
Let's say I want to use the LoginRequiredMixin and a UserPermissionMixin created by myself and apply them to all the views in an app. This is just an example, I might also have mixins that add some context or do other stuff. I could do it manually, for example this view: class MyCreateView(LoginRequiredMixin, UserPermissionMixin, CreateView) But, since I have many views and I might have other specific mixins for some views, this gets messy and hard to manage. One solution that came to mind would be to create new classes for the generic views: class DecoratedCreateView(LoginRequiredMixin, UserPermissionMixin, CreateView): pass class DecoratedDetailView(LoginRequiredMixin, UserPermissionMixin, DetailView): pass class DecoratedUpdateView(LoginRequiredMixin, UserPermissionMixin, UpdateView): pass class DecoratedDeleteView(LoginRequiredMixin, UserPermissionMixin, DeleteView): pass and then, use these as my generic views: class MyCreateView(DecoratedCreateView) Is this a good approach? Do I have to add any methods in the classes above or do I just leave them blank and it'll work as expected? Is there any other way to achieve this, maybe in urls.py ? -
How to Sum a value with row duplicates in the Django orm query
Goal I am looking for a way to get a sum of values Expected Results {'Bar': 10} Models class ModelX(models.Model): name = models.CharField(...) class ModelA(models.Model): value = models.IntegerField() class ModelB(models.Model): modela = models.ForeignKey(ModelA) modelxs = models.ManyToManyField(ModelX, through='ModelC') class ModelC(models.Model): modelb = models.ForeignKey(ModelB) modelx = models.ForeignKey(ModelX) modelxx = models.ForeignKey(ModelX, related_name='modelcs') What I've tried Modelx.objects.values('name').annotate( total=Sum('modelcs__modelb__modela__value') ).values('total') The Problem ModelC can contain multiple rows with the same modelxx relation. This will cause duplicates, and cause the sum of 'value' to get duplicated Example Below are the example models where I would expect to see the 10 as stated in the expected results up top: modelx = ModelX.objects.create(name='Foo') modelxx = ModelX.objects.create(name='Bar') modela = ModelA.objects.create(value=10) modelb = ModelB.objects.create(modela=modela) modelc1 = ModelC.objects.create(modelb=modelb, modelx=modelx, modelxx=modelxx) modelc2 = ModelC.objects.create(modelb=modelb, modelx=modelxx, modelxx=modelxx) -
Best practices for unknown max_length in Django?
After having to increase max_length of another field in a model, I've started to wonder: maybe this is not the way? I'm getting data from an external API, so I can't check what's the maximum length. Let's say that I'm guessing the field can have 100 chars - because it makes sense, but I have no idea if this is actually the case, there might appear a value which is 300 chars long. What's the recommended approach here? 1) Truncate the value (where should I put the code then? and what with fields such as URL, which won't work after truncating?)? 2) Skip the value? 3) Set length of every field to 100*expected length? -
Django - Inherit Permissions in Mixins
I have two models. I want to inherit permissions from one model to another. So here's my pseud-django-code: class BaseMixin: class Meta: abstract = True permissions = ( ("can_change_something", "Can change something"), ) class Article(BaseMixin): # some fields class Meta: permissions = ( ("can_change_something_on_articles", "Can change something on articles...") ) My problem: When I go to the admin panel to groups these permissions don't show up. What should I do? -
Django 2.2 DetailView rendering blank page
I'm using Django 2.2 here. I'm getting blank page rendered with DetailView but with fuction based view it works perfectly. Here is code for DetailView class ProductDetailView(DetailView): queryset = Product.objects.all() template_name = 'products/detail.html' def get_context_data(self, **kwargs): context = super(ProductDetailView, self).get_context_data(**kwargs) return context def get_object(self, *args,**kwargs): request=self.request pk=self.kwargs.get('pk') instance = Product.objects.get_by_id(pk) if instance is None: raise Http404("Product doesn't exists") return instance urlpatterns=> path('products/<int:pk>/', ProductDetailView.as_view()), fucntion based view def product_detail_view(request, pk=None): instance = Product.objects.get_by_id(pk) if instance is None: raise Http404("Product doesn't exists") context = { 'object_detail': instance } return render(request, 'products/detail.html', context) Thanks -
Django "500 internal server error" on login attempt in production
I'm new to django and web design in general but I have a small apache2 webserver running on a raspberry pi, I have successfuly set up the server to work with django 2.2 and I can access the site via a dataplicity wormhole and it works fine. However, when I attempt to login through the admin page or through my website I get an "500- internal server error". There is nothing in the apache error log and if I run the server via python manage.py runserver it works as expected only when running it through apache do I get the problem. This is my apache2.conf: DefaultRuntimeDir ${APACHE_RUN_DIR} PidFile ${APACHE_PID_FILE} Timeout 300 KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 5 User ${APACHE_RUN_USER} Group ${APACHE_RUN_GROUP} HostnameLookups Off ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn IncludeOptional mods-enabled/*.load IncludeOptional mods-enabled/*.conf Include ports.conf <Directory /> Options FollowSymLinks AllowOverride None Require all denied </Directory> <Directory /usr/share> AllowOverride None Require all granted </Directory> <Directory /var/www/> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> WSGIScriptAlias / /home/pi/pi_site/pi_website/wsgi.py WSGIPythonHome /home/pi/pi_site/myvenv WSGIPythonPath /home/pi/pi_site <Directory /home/pi/pi_site/pi_website> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static/ /home/pi/pi_site/static/ <Directory /home/pi/pi_site/static> Require all granted </Directory> AccessFileName .htaccess <FilesMatch "^\.ht"> Require all denied </FilesMatch> LogFormat "%v:%p %h %l %u … -
explaining custom modeld fields mechanism
i don't, this not the first time to have the feeling stuck in a challenging new things but it may be the first to be not able to have an even external blogs explaining the subject not just the docs . so i hope to find some one explain the fundamentals of creating a custom django model field. here is an example if you want to know what i am facing class OrderField(models.PositiveIntegerField): def __init__(self, for_fields=None, *args, **kwargs): self.for_fields = for_fields super(OrderField, self).__init__(*args, **kwargs) def pre_save(self, model_instance, add): if getattr(model_instance, self.attname) is None: # no current value try: qs = self.model.objects.all() if self.for_fields: # filter by objects with the same field values # for the fields in "for_fields" query = {field: getattr(model_instance, field)\ for field in self.for_fields} qs = qs.filter(**query) # get the order of the last item last_item = qs.latest(self.attname) value = last_item.order + 1 except ObjectDoesNotExist: value = 0 setattr(model_instance, self.attname, value) return value else: return super(OrderField, self).pre_save(model_instance, add) i have read some of the docs, but feel free to explain it as it's for any one with no prior experience so everyone will find it helpfull -
Cart object wont insert the record in database via create function
I have a Cart Model which is not inserting a fresh record. class Cart(models.Model): cartid = models.IntegerField(db_column='CARTID') # Field name made lowercase. productid = models.IntegerField(db_column='PRODUCTID') # Field name made lowercase. prodctname = models.TextField(db_column='PRODCTNAME') # Field name made lowercase. This field type is a guess. price = models.TextField(db_column='PRICE') # Field name made lowercase. This field type is a guess. quantity = models.IntegerField(db_column='QUANTITY') # Field name made lowercase. dateadded = models.DateTimeField(db_column='DATEADDED') # Field name made lowercase. customerid = models.IntegerField(db_column='CUSTOMERID') # Field name made lowercase. sellerid = models.IntegerField(db_column='SELLERID') # Field name made lowercase. class Meta: managed = False db_table = 'CART' @login_required def addToCart(request): cart = Cart.objects.create(productid = productId, sellerid = sellerId,prodctname= prodName,price = price,quantity=1, dateadded= datetime.datetime.now(),customerid = request.user.id) I get the following error: IntegrityError at /addToCart NOT NULL constraint failed: CART.CARTID It just stopped inserting records suddenly -
Is there a editable grid in django2.1?
We are looking to bind a data model to datagrid in Django. So is there a Editable datagrid in Django that reflects changes of the grid back to the database? How to Bind Data to any popular Datagrid so that changes will reflect to respective tables?Please give a Code... -
How to pre-populate form with data received from a previous HTML form submission in Django?
I'm trying to populate my ModelForm with some of data that I have submitted to previous HTML page which is also ModelForm. I just want to pass it to another form so it doesn't have to be written twice. I've tried couple solutions from stackoverflow but they are 6+ years old, kinda outdated and also couldnt come up with solution from django docs https://docs.djangoproject.com/en/2.2/topics/forms/ I have two models, which have same fields which are 'name' and 'boxid' I need to pass it from first input to second(to populate it). forms.py class NewCashierForm(forms.ModelForm): class Meta: model = Cashier fields = ("cashier_company", "cashier_dealer", "cashier_name", "cashier_boxid", "cashier_type", "cashier_package", "cashier_otheritem", "cashier_otheritemserial", "cashier_length", "cashier_promotion", "cashier_amount", "cashier_paymenttype") labels = {"cashier_company":('Firma'), "cashier_dealer": ('Diler'), "cashier_name":('Ime i prezime'), "cashier_boxid":('Box ID'), "cashier_type":('Tip'), "cashier_package":('Paket'), "cashier_otheritem":('Drugi uredjaj'), "cashier_otheritemserial":('SBU'), "cashier_length":('Dužina'), "cashier_promotion":('Promocija'), "cashier_amount":('Iznos'), "cashier_paymenttype":('Nacin uplate')} exclude = ['cashier_published'] def save(self, commit=True): cashier = super(NewCashierForm, self).save(commit=False) if commit: cashier.save() return cashier class NewPersonForm(forms.ModelForm): class Meta: model = Person fields = {"person_name", "person_adress", "person_phone", "person_boxid"} labels = {"person_name":('Ime i prezime'), "person_adress":('Adresa'), "person_phone":('Telefon'), "person_boxid":('Box ID')} def save(self, commit=True): person = super(NewPersonForm, self).save(commit=False) if commit: person.save() return person views.py def addcashier(request): if request.method == 'GET': form = NewCashierForm() else: form = NewCashierForm(request.POST) if form.is_valid(): fs = form.save(commit=False) fs.user … -
How to create dict in the django?
I want to get an JSON response from the API and give a response with the selected field. I have fetched the response but I am not able to create a response with the new value. I am very new to python world and in learning stage. def search(request): if request.method == 'POST': searchQry = request.POST.get("searchQry","") nodeIP = settings.NODEIP params = {'search':searchQry} apiResponse = requests.get(url = nodeIP, params = params) data = apiResponse.json() newArray = {} nodeName = 'RPID' if nodeName == 'RPID': for x in data: newArray['cphNumber'] = x["data"]["cphNumber"] newArray['farmName'] = x['data']['farmName'] newArray['addressLine1'] = x['data']['addressLine1'] return HttpResponse(json.dumps(newArray)) else: return HttpResponse('Unauthrozed Access') My response array looks likes this : [{"data": {"cphNumber": "321","farmName": "313","addressLine1": "13","addressLine2": "13","region": "13", "postalCode": "13"},"id": "4c1b935664e6f684e89ee363f473ce3567599d4b9da0f5889565d5b6f0b84440"},{"data": {"cphNumber": "321","farmName": "313","addressLine1": "13","addressLine2": "13","region": "13","postalCode": "13"},"id": "7cbe7be9797896545410ed6c4dcc18064525037bc19fbe9272f9baabbb3216ec"},{"data": { "cphNumber": "321","farmName": "313","addressLine1": "13","addressLine2": "13","region": "13","postalCode": "13"},"id": "7df10c0b7b84434d5ace6811a1b2752a5e5bca13b691399ccac2a6ee79d17797"}] In response I am getting only one array. I know I have to do something like newArray[0]['cphNumber'] But I am getting an error. Can you please help me to solve this . -
Django Process Form With Element That Might Not Exist
I have a form which contains an element that is not bound to a model. There are cases where this form element will not be rendered in the HTML at all, but when I post the form I want it to validate still if it doesn't exist. I have looked into the possibility of changing the value that is posted to something, but can't see a way of doing this. I have tried overriding the clean method, but I am not sure how you do that. I have tried setting it to required=False, but that has no effect because it seems to require a null value to be posted at the very least. My form class looks as below: class StimForm(ModelForm): body = forms.CharField( widget=forms.Textarea ) userstims = forms.ChoiceField(required=False) class Meta: model = Stim fields = ['body','privacytype','stimtype'] The HTML is below. As this is possibly hidden the data for userstim is not posted in some cases. I still want the form validation to work in these cases. <div class='form-group row' id="userstim" style="display:none;"> <label class="col-2 col-form-label">Add Custom Stim:</label> <div class="col-5"> {{ form.userstims }} </div> <div class="col-5"> <a href="/stimbook/adduserstim">Add Stim</a> </div> </div> -
How to make a single object (Singleton) across django webservice calls
I am using a django webservice. However, whenever this webservice is called, it creates the objects in views.py. I have an object which should not be instantiated across calls, as it needs to push something to queue in RoundRobin fashion, and if object is created again, it will again start from 0. I have tried using staticmethod but it does not work. Then I tried Lock, but that again instantiated again in each webservice call, so it can work only if I use multithread within the webservice call, not between 2 webservice calls. I am coming from .Net background and used to use HttpContext as suggested in this question. How to make singleton static value securely accessible across all calls for a single HTTP request Expectations: If I give a print statement in that object (def) then it should print only once when webservice is called first time, not again. -
why this code not storing data in database and showing error instead?
i am working on some django code in my application but it's showing TypeError. models.py class Board(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) def __str__(self): return self.name class Topic(models.Model): subject = models.CharField(max_length=255) last_updated = models.DateTimeField(auto_now_add=True) board = models.ForeignKey(Board, related_name='topics',on_delete=models.CASCADE) starter = models.ForeignKey(User, related_name='topics',on_delete=models.CASCADE) class Post(models.Model): message = models.TextField(max_length=4000) topic = models.ForeignKey(Topic, related_name='posts',on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(null=True) created_by = models.ForeignKey(User, related_name='posts',on_delete=models.CASCADE) updated_by = models.ForeignKey(User, null=True, related_name='+',on_delete=models.CASCADE) class Topic(models.Model): last_updated = models.DateTimeField(auto_now_add=True) class Post(models.Model): updated_by = models.ForeignKey(User,null=True,on_delete=models.CASCADE,related_name="+") views.py def board_topics(request, pk): board = get_object_or_404(Board, pk=pk) return render(request, 'topics.html', {'board': board}) def new_topic(request, pk): board = get_object_or_404(Board, pk=pk) if request.method == 'POST': subject = request.POST.get('subject','') message = request.POST.get('message','') user = User.objects.first() topic = Topic.objects.create( subject=subject, board=board, starter=user ) post = Post.objects.create( message=message, topic=topic, created_by=user ) return redirect('board_topics', pk=board.pk) return render(request, 'new_topic.html', {'board': board}) -
delete django formset with javascript
hi I have improved add Django formset and save the extra form data now I want to delete the extra forms if the user need to delete some of them how to do that this is my template and javascript code for add extra forms and its work totally fine {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <form method="post" id="regForm" action="."> {% csrf_token %} <h1>Visa Info:</h1> <!-- One "tab" for each step in the form: --> <div class="tab">Name: {{form.visa_type|as_crispy_field}} {{ form.arrival_time|as_crispy_field }} {{ form.departure_time|as_crispy_field }} {{form.number_of_vistor|as_crispy_field}} {{form.purpose_trip|as_crispy_field}} {{form.city|as_crispy_field}} <h1>user info</h1> <div id="userform"> {% for form_data in formset %} {{ form_data.management_form }} {{form_data.first_name|as_crispy_field}} {{form_data.last_name|as_crispy_field}} {{form_data.middle_name|as_crispy_field}} {{form_data.date_of_birth|as_crispy_field}} {{form_data.gender|as_crispy_field}} {{form_data.passport|as_crispy_field}} {{form_data.passport_ex|as_crispy_field}} {{form_data.nationality|as_crispy_field}} {% endfor %} </div> <a class="btn btn-default" id="{{ formset.prefix }}">add</a> {{ formset.management_form }} </div> <div class="tab">Dliver Information: {{emailForm.email|as_crispy_field}} {{emailForm.instructions|as_crispy_field}} Do you want the real visa to be dlever to you? <div class="btn btn-primary" id="show">yes</div> <div class="btn btn-danger" id="hide">no</div> <div class="menu"> {{dliveryform|crispy}} </div> </div> <div style="overflow:auto;"> <div style="float:right;"> <button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button> <button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button> </div> </div> <!-- Circles which indicates the steps of the form: --> <div style="text-align:center;margin-top:40px;"> <span class="step"></span> <span class="step"></span> <span class="step"></span> <span class="step"></span> </div> </form> {% endblock content %} {% block javascript … -
Strange error on delete action in Django Admin
I've build error reporting system. The problem is that when I try to add entry to the Session during process_exception in the middleware the data will be not saved. class HandleExceptionGracefullyMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_exception(self, request, exception): if isinstance(exception, Http404): return prev_page = request.META.get('HTTP_REFERER') error = traceback.format_exc(100) request.session['traceback'] = error request.session['e'] = exception request.session['prev_page'] = prev_page request.session.modified = True request.session.save() print(request.session.session_key) session_store = SessionStore(session_key=request.session.session_key) session_store['traceback'] = error session_store['e'] = exception session_store['prev_page'] = prev_page session_store.save() print(error) # now -
Using model as multiple field of another model in Django
I am creating some music app. I have "Track" model, and I want to let user create playlist, that can contain multiple Tracks. My searching didn't help me to do it. (Also one Track can be used in multiple playlists, for example Track "XXX" can be used in playlist "YYY" and in playlist "ZZZ"). Here's models.py: from django.db import models from django.contrib.auth.models import User from .validators import * #Model that accutaly contains user's tracks/songs class Track(models.Model): title = models.CharField(max_length=40, null=True) description = models.CharField(max_length=500, null=True) author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) miniature = models.ImageField(upload_to='images/track', default="defaults/default.png", validators=[validate_miniature_file_extension]) audio_or_video = models.FileField(upload_to='audio_and_video/', default="file_not_found", validators=[validate_track_file_extension]) #Model that contains playlists class Playlist(models.Model): title = models.CharField(max_length=40, null=True) description = models.CharField(max_length=500, null=True) author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) miniature = models.ImageField(upload_to='images/playlist', default="defaults/default.png", validators=[validate_miniature_file_extension]) Tracks = models.ForeignKey(Track, default=None, on_delete=models.CASCADE) # I tried this, but it won't work at all because it can contain only one Track -
Django ValueError 'accounts.user', but app 'accounts' isn't installed
Few days I write an app to extends User Model, it is simple and worked nice. later I push to the GitHub and delete from my local machine. Now I have cloned that app again to my machine and tried to migrate and run server but it returns this error: ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'accounts.user', but app 'accounts' isn't installed. My Installed apps these: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accountsapp' ] I am not getting where the project got apps name accounts this is very odd error i seen ever. If you want to see my entire project, go there: Porjects on Github, click here to see You will see how simple this apps. Even i have deleted previos db file, pychch, migrations history etc, not getting why it is not working -
Django-Dynamic Form Increment ID for each new input element added in formset
I have a form which takes 4 fields as input as below:- forms.py AuthorFormset = modelformset_factory( Author, fields=('due_date','author' ), extra=5, widgets={'due_date': forms.DateInput(attrs={ 'class': 'form-control', 'placeholder': 'Date'}), 'author': forms.TextInput(attrs={ 'class': 'form-control', 'id': 'txtSearch', 'placeholder': 'Participants' }), } I have added a css ID to field author which is a Text input. To this text input I am also conducting an Ajax call through Jquery Autocomplete feature. view.html <form class="form-horizontal" method="POST" action=""> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div class="row form-row spacer"> <div class="col-2"> <div class="input-group"> {{form.author}} </div> </div> Javascript <script> $(document).ready(function(){ $("#txtSearch").autocomplete({ source: "/ajax_calls/search/", minLength: 2, open: function(){ setTimeout(function () { $('.ui-autocomplete').css('z-index', 99); }, 0); } }); }); </script> Everything is working fine its just that I am only able to handle Ajax call of only the first field. I want to increment ID for each new field added in dynamic forms.