Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do you prefill a value in a model form field using __init__ in django?
So basically I want to be able to prefill a Charfield form field with a certain value in the init method. Here is my form: class UpdateForm(forms.ModelForm): #_____________________________________________________________ def __init__(self, *args, **kwargs): super(UpdateForm, self).__init__(*args, **kwargs) self.fields['form_field'].initial = "How are you doing?" self.fields['form_field'].widget = self.fields['form_field'].hidden_widget() #_____________________________________________________________ class Meta: model = form_model fields = ( 'form_field', ) However, I cannot seem to set the value of my form_field with How are you doing?. Morever, I need to be able to change the value in the init method. Does anyone know how I can do this? Thank you, and please send me any questions you have. -
unable to load photos in Django after deploying to heroku
I have made a portfolio + blog website using Django. it works perfectly when running it locally but after I deployed it to Heroku, accessing the portfolio redirected me to a 500 server error. I turned on debug mode and when I did the same, it didn't throw a 500 server error, however, the pictures won't load. this is very confusing and help will be very appreciated... settings.py from pathlib import Path import os from dotenv import load_dotenv load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'projects', 'blog', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'personal_portofolio.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ["personal_portofolio/templates/"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'personal_portofolio.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': … -
Is exact querying of ArrayField possible?
Documentation on ArrayField only has contains. I know you can use __n__iexact on the ArrayField to get an exact match of n position... Apart from chaining a bunch of __n__iexact, is there a better way? More specifically to my use case, I'm using django-filters and I want to be able to exactly search for an object by its slug ArrayField. -
Can i use email verification function and Login With google in one project. (in django)
I try to make a website that have email verification and login with google function, so first i make email verification function, and it work and then i try to make login with google function but when I see in the tutorial, there can only be 1 function, namely choosing a verification email or logging in with google, because the verification email section I made with a custom auth system, while logging in with google in the tutorial uses the default auth system from a package. If you can use both, how? -
Is it possible to add a data to nested just using UUID of it?
I'm quite new to DRF and I trying to build a system with Document and Category. These are models.py for it class TimeStampedModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class Document(TimeStampedModel): unique_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) title = models.CharField(max_length=50, blank=True, default="") description = models.TextField(blank=True, default="") image = models.ImageField(blank=True, null=True) category = models.ForeignKey( 'Category', on_delete=models.SET_NULL, related_name='documents', blank=True, null=True, ) class Meta: ordering = ("-created_at",) class Category(TimeStampedModel): unique_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) name = models.CharField(max_length=50, blank=True, default="") description = models.TextField(blank=True, default="") class Meta: ordering = ("-created_at",) def __str__(self): return self.name And Serializes.py class DocumentViewSet(ModelViewSet): serializer_class = DocumentSerializer queryset = Document.objects.all() lookup_field = "unique_id" @action(detail=True, methods=['delete']) def delete_document(self, request, unique_id): """Delete document""" docs = Document.objects.get(unique_id=unique_id) try: docs.delete() return Response(status=status.HTTP_204_NO_CONTENT, data={'message': f'Delete successfully with {docs.unique_id}'}) except: return Response(data={'message': f'Delete failed with {docs.unique_id}'}) class CategoryViewSet(ModelViewSet): serializer_class = CategorySerializer queryset = Category.objects.all() lookup_field = "unique_id" filterset_fields = "__all__" @action(detail=True, methods=['delete']) def delete_category(self, request, unique_id): """Delete category""" cats = Category.objects.get(unique_id=unique_id) try: cats.delete() return Response(status=status.HTTP_204_NO_CONTENT, data={'message': f'Delete successfully with {cats.name}'}) except cats.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND, data={'message': f'Delete failed with {cats.name}'}) What I'm trying to do is update the Category name, description and add the Document to Category using UUID of Document with these JSON … -
How to return a list of available time slots via a forms ValidationError
models.py from django.db import models from django.utils import timezone from django.urls import reverse from django.contrib.auth.models import User class Customer(models.Model): username = models.ForeignKey(User,on_delete=models.CASCADE) name = models.CharField(max_length=20,null=True) def __str__(self): return self.name # Create your models here. class Booking(models.Model): customer_name = models.ForeignKey(Customer,on_delete=models.CASCADE,null=True) username = models.ForeignKey(User,on_delete=models.CASCADE) qty_plts = models.PositiveSmallIntegerField(default=1) cbm = models.PositiveSmallIntegerField(default=1) created_date = models.DateTimeField(default=timezone.now()) delivery_date = models.DateField(null=True) delivery_time = models.TimeField(null=True) booking_number = models.CharField(max_length=50,unique=True) def __str__(self): return self.booking_number def save(self, **kwargs): if not self.booking_number: self.booking_number = f"{self.delivery_date:%Y%m%d}{self.delivery_time:%H%M}" super().save(**kwargs) def get_absolute_url(self): return reverse('bookmyslot:detail',kwargs={'pk':self.pk}) forms.py from django import forms from bookmyslot.models import Booking,Customer from bootstrap_datepicker_plus import DatePickerInput import datetime as dt from django.utils import timezone HOUR_CHOICES = [(dt.time(hour=x), '{:02d}:00'.format(x)) for x in range(7, 13)] class BookingForm(forms.ModelForm): def __init__(self,*args,**kwargs): user = kwargs.pop('username',None) super(BookingForm,self).__init__(*args,**kwargs) self.fields['qty_plts'].label = "Quantity Of Pallets" self.fields['cbm'].label = "Shipment CBM" self.fields['delivery_date'].label = "Delivery Date" self.fields['delivery_time'].label = "Delivery Time" self.fields['customer_name'].label = "Customer Name" self.fields['customer_name'].queryset = Customer.objects.filter(username=user) def clean(self): cleaned_data = super(BookingForm,self).clean() booking_number = f"{cleaned_data.get('delivery_date'):%Y%m%d}{cleaned_data.get('delivery_time'):%H%M}" if Booking.objects.filter(booking_number=booking_number).exists(): raise forms.ValidationError("Requested slot is already booked, please choose another time") class Meta: model = Booking fields = ('customer_name','qty_plts','cbm','delivery_date','delivery_time') widgets = {'delivery_date':DatePickerInput(options={"daysOfWeekDisabled":[0,6],"minDate":timezone.now().date().strftime('%Y-%m-%d')}), 'delivery_time':forms.Select(choices=HOUR_CHOICES)} views.py from django.shortcuts import render # Create your views here. from .models import Booking,Customer from .forms import BookingForm from django.urls import reverse,reverse_lazy from django.contrib import messages from django.contrib.auth.mixins … -
how to create update link in home page...?
views.py class UpdateEvents(UpdateView): model = Event fields = ['event_name','event_date','venue','description'] template_name = 'events/events_update.html' success_url = '/' url.py path('update_events/<pk>/',UpdateEvents.as_view(), name='update-events'), home.html : when i go this "update" link than show me 'The current path, {% url 'update-events' id=events.id % }, didn’t match any of these.' how to i create upadate link in home.py file??? <a class="btn btn-primary" href="{% url 'update-events' id=events.id %}">update</a> [this is error page][1] [1]: https://i.stack.imgur.com/BIhqX.png -
How to block page access to other logged in user in django?
I am trying to block logged in user to access other user update profile page. My situation: Suppose Person A is logged in to his profile and he know other user update profile URl. In this situation he can simple getting access of the update profile url of other user. So , here i want to limit this restriction only to the same logged in user to update their profile only. this is my code for updating profiles: @login_required def UpdateProfile(request, slug): user = Profile.objects.get(slug=slug) if request.method == "POST": form = UpdateProfileForm(request.POST, request.FILES, instance=user) if form.is_valid(): profile_pic = form.cleaned_data['profile_pic'] form.profile_pic = profile_pic form.save() messages.success(request,"Data Updated successfully") return HttpResponseRedirect(reverse('updateaddress', args=(request.user.profile.slug,))) else: messages.error(request, "Please check all fields are valid") return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: form = UpdateProfileForm(instance=user) context = { 'user':user, 'form':form, } return render(request, "authentication/register/update/profile.html",context) urls.py path("<slug:slug>/update-profile/", UpdateProfile, name="updateprofile"), -
Can django prefetch related work with 3 lookups?
I want to prefetch 3 tables plus the initial table. Here are model examples of the project i am working on class ExampleOne(models.Model): name = models.Charfield() option = models.BooleanField() money = IntegerField() class ExampleTwo(models.Model): word = models.Charfield() example_one = models.ManyToManyField(ExampleOne) number = IntegerField() class ExampleThree(models.Model): number = models.IntegerField() example_two = models.ForeignKey(ExampleTwo) def get_calculation_one(self): Calculate using data from Example_2 and Example_1 class ExampleFour(models.Model): date = models.DateField() example_three = models.ManyToManyField(ExampleThree) def get_calculation_two(self): Calculate using data from method on Example_3 Now I want to know if it is possible to retrieve data from all these models with as little hits to the database as possible because when I try to retrieve data it takes over one minute to retrieve the data and send it to the frontend The calculation might be making many database hits in order to get the data and calculate and i think that is why it is taking more than a minute to retrieve the data my view looks like this qs = ExampleFour.objects.prefetch_related( Prefetch('example_three__example_two__example_one') ).filter(...) Is there a way to use prefetch to make the retrieval faster or is there another suggestion on I can rewrite my code in order to avoid this long retrieval time? Note I … -
How to relate a Django form template to the id of an input html tag
newbie here, this is my problem, i used to have a form looking like this in my website where the ID's of each input helped my to apply a JavaScript code to let users check their password's strength, so as the checkbox to watch or hide the password etc... <input id="psw_1" type="password"> <input id="psw_2" type="password"> Now with Django i just need these two lines: {{ form.password1 }} {{ form.password2 }} If i use those templates inside an input or div tag or whatever, to assign the ID's i i need, it shows some weird outputs in the sign form, is there a way to use those ID's or tell the js script those Django templates are what I'm pointing to? -
How ro redirect user to correct page in django-oscar checkout?
I am trying to follow this implementation of django-oscar cash on delivery but after updating and changing things my checkout flow is getting redirected back and forth to two pages only. I am not sure where i am going wrong. ] -
How to proxy binary files in django
I have a Django service that needs to be a proxy for binary files. For example, the binary files FileA.pdf and FileB.xslx are in http://some-server.con/binaryfiles/. My service have to access this data, and then return that data in a Response. Currently, it works fine if I have a binary file on my own server, for example: file_name = './example.pdf' with open(file_name, mode='rb') as file: return Response( file.read(), headers={'Content-Disposition': 'attachment; filename="{filename}"'.format(filename=file_name)}, content_type=self.get_type(file_name)) But I'm not sure of how get the data from the other server. Can I open an external uri resources as it was a simple file? I will greatly appreciate any help -
Django Rest Framework fails to return a response if response it too large. http code 0
We are building an API on Django and using the Django Rest Framework. This API sits between two servers, so it receives requests from server A, makes requests to server B, formats the response from server B and responds back to server A with the formatted data. The view handler extends the ApiView class from DRF, and the response is a Response object from DRF as well. Here is pseudo code from views.py to put things into perspective: class dummy(APIView) # define auth here def get(request): # handle the request from server A # get the content here, from server B # content is a list of up to 1028 elements response = Response({'status':'success','content':content}, status=200) return response <--- fails here if content length > 200 elements The content is a list of dicts, each dicts contain 4 - 5 key/value pairs, if this list is less than 200 elements long, the response goes through just fine, but anything above 200 elements will result in a response code 0 and no error message explaining what happened, other than a broken pipeerror from server A. We increased the timeout on the request from server A to 30 seconds, just to be sure … -
?: (corsheaders.E014) Origin 'https://domain_name.com/' in CORS_ALLOWED_ORIGINS should not have path
MIDDLEWARE = [ ... "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", ] CORS_ALLOWED_ORIGINS = [ "https://domain_name.com", "http://127.0.0.1:8000", ] django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (corsheaders.E014) Origin 'https://api.krafttopia.com/' in CORS_ALLOWED_ORIGINS should not have path -
Getting Typerror in django but fields appear to be defined correctly
I'm brand new to django and I can't figure out why this is happening. Here is my model which I have added to my settings "Installed Apps" config and I have migrated: class User(models.Model): name = models.CharField(max_length = 200), state = models.CharField In the shell I import the model like so: from homepage.models import User then I try to create a new user like so: a = User(name='Alex', state='Alberta') and it throws this error which makes no sense to me because I've defined the fields of the User schema above: I know I'm missing something like maybe I'm supposed to add something to my views.py file before starting the shell but I just don't know. Any direction appreciated! Thanks! TypeError Traceback (most recent call last) <ipython-input-3-88cc332f436e> in <module> ----> 1 a = User(name='Alex Honing', state='Alberta') /usr/local/anaconda3/envs/pyfinance/lib/python3.9/site-packages/django/db/models/base.py in __init__(self, *args, **kwargs) 501 pass 502 for kwarg in kwargs: --> 503 raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) 504 super().__init__() 505 post_init.send(sender=cls, instance=self) TypeError: User() got an unexpected keyword argument 'name' In [4]: a = User(name = 'Alex', state ='Alberta') -
Passing both user ID and product ID to Paypal Button
I am using @paypal/react-paypal-js to display the PayPal button and create an order. I am specifically interested in processing credit card payments. Once my Django backend receives the payment capture completion event from PayPal, it needs to store information about a particular user owning a particular product. Hence, the notification has to contain both the user ID (i.e. email) and the product ID. This is how I am trying to pass these two pieces of information in my frontend: createOrder={(data, actions) => { return actions.order.create({ purchase_units: [ { amount: { value: course.price, currency_code: course.currency, }, custom_id: course.title, }, ], payer: { email_address: userEmail, } }); }} The user email address is automatically filled into the form. However, the webhook_event event in the server does not contain this information. That is, there is no payer field inside resource in webhook_event. How can I pass the two pieces of information so as to get them in webhook_event? (I would like to avoid the ugly solution of concatenating both pieces into custom_id) -
Switching from NoSQL to SQL land in django
I am porting my Mongo-Express app to Postgres-Django. The app includes a simple form for collecting a student's information and the books they have read over the summer. The express API writes the payload to MongoDB. The payload looks like below: { student_id: 123, student_name: 'James Hook', books: [ { book: 'War and Peace', author: 'Leo Tolstoy' }, { book: 'Harry Potter', author: 'JK Rowling' } ] } Mongo is a document-based database so I could store the above payload as-is. Now moving to django-postgres, I have to define models and I can see two options: A. Just create one model with three fields - student_id (IntegerField), student_name (CharField), and books (ArrayField(JSONField)) B. Go full RDBMS and create two models - student and books. Student and book have many-many relationship. Give this, I have a few questions: Q1. If I don't need to index on books, does option A make more sense? Q2. In option A, should it be just JSONField or ArrayField(JSONField)? Q3. In option B, how do we write TWO or more books for one student at a time? Do I need an ArrayFiled there? How does the model would look like and does it violate atomicity constraint … -
Heroku try to deploy python website ,,manage.py collestatic --noninput"
I create a website using Python ,JS, React, Django .When I deployed on Heroku via github, an error occur: -----> Determining which buildpack to use for this app ! Warning: Multiple default buildpacks reported the ability to handle this app. The first buildpack in the list below will be used. Detected buildpacks: Python,Node.js See https://devcenter.heroku.com/articles/buildpacks#buildpack-detect-order -----> Python app detected -----> Using Python version specified in Pipfile.lock cp: cannot stat '/tmp/build_02d1f320/requirements.txt': No such file or directory -----> Installing python-3.9.7 -----> Installing pip 20.2.4, setuptools 57.5.0 and wheel 0.37.0 -----> Installing dependencies with Pipenv 2020.11.15 Installing dependencies from Pipfile.lock (dee4f1)... -----> Installing SQLite3 -----> $ python leadmanager/manage.py collectstatic --noinput Traceback (most recent call last): File "/tmp/build_02d1f320/leadmanager/manage.py", line 22, in <module> main() File "/tmp/build_02d1f320/leadmanager/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect handler(path, prefixed_path, storage) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 338, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 248, in delete_file if self.storage.exists(prefixed_path): File "/app/.heroku/python/lib/python3.9/site-packages/django/core/files/storage.py", line 318, in … -
(NOT NULL constraint failed:owner_id)
I make migrations and run migrate. Then, I submit the form for registration but I get NOT NULL constraint. Below is my models: models.py class A(models.Model): u = models.OneToOneField(User, on_delete=models.CASCADE) num = models.IntegerField() class B(models.Model): x = models.ForeignKey(u, on_delete=models.CASCADE) y = models.CharField(max_length = charLen100) forms.py class AForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput(), required=True), first_name = forms.CharField(max_length=charLen100, widget = forms.TextInput(attrs= {'placeholder': 'First Name'})) last_name = forms.CharField(max_length=charLen100, widget=forms.TextInput(attrs= {'placeholder': 'Last Name'})) num_items = forms.CharField(label="How many items do you own?", widget=forms.Select(choices=ITEM_NUMBER_CHOICES)) class Meta: model = A fields = ('username', 'email', 'password','first_name', 'last_name') class BForm(forms.ModelForm): name = forms.CharField(widget=forms.TextInput(attrs={'placeholder':name'})) class Meta: model = B fields = ('name') views.py def register(request): registered = False if request.method == 'POST': user_form = AForm(request.POST) profile_form = BForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) profile = profile_form.save(commit=False) profile.user = user if 'picture' in request.FILES: profile.picture = request.FILES['picture'] profile.save() registered = True else: print(user_form.errors, profile_form.errors) else: user_form = UserForm() profile_form = UserProfileForm() context_dict = {} context_dict['user_form'] = user_form context_dict['profile_form'] = profile_form context_dict['registered'] = registered return render(request, ..., context=context_dict) so, what I am doing is that I have two tables in database A and B and A can have many B's that is B then holds A as a foreign key. Then, … -
Django migration: django.db.utils.OperationalError: (1824, "Failed to open the referenced table 'classroom_user'")
I am trying to deploy a Django app from a development server to a production server I have set up a virtualenv with python 3.8.10, created the mysql database, I am running in the virtualenv. I get no errors from python manage.py check, get "no changes detected" when running python manage.py makemigrations, but when I run ```python manage.py migrate`` I get the following: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying admin.0001_initial...Traceback (most recent call last):... final line of the traceback: Django.db.utils.OperationalError: (1824, "Failed to open the referenced table 'classroom_user'") ("classroom" is the name of the app within the project "codex") I just recently rebuilt all of the tables in this database on my development server with no issues. The database on the production server is empty. models.py is in place and complete. I have tried it both with an empty migrations folder and the migration folder removed. The migration does create django_admin_log, django_content_types, django_migrations, but no other tables. All of the other posts I have seen on this have been about have foreign key constraints, but in my models.py all of the tables that have foreign keys are specified after the … -
cant upload multiple images djago - ajax
I'm trying to upload multiple images with ajax request, i'm using modelformset_factory to upload several images , here is my code : class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) my forms.py class UploadDocumentsForm(forms.ModelForm): class Meta: model = Document fields = ['docs'] my views.py @login_required def add_new_image(request,id): obj = get_object_or_404(Booking,id=id) if request.is_ajax() and request.method == 'POST': images = UploadDocumentFormSet(request.POST,request.FILES) if images.is_valid(): for img in images: if img.is_valid() and img.cleaned_data !={}: img_post = img.save(commit=False) img_post.booking = obj img_post.save() return JsonResponse({'success':'success'}) else: messages.error(request,_('error message')) images = UploadDocumentFormSet(queryset=Document.objects.none()) return render(request,'booking/add_img.html',{'obj':obj,'images':images}) and here is my template includes html and ajax $('#addButton').click(function() { var form_dex1 = $('#id_form-TOTAL_FORMS').val(); $('#images').append($('#formset').html().replace(/__prefix__/g,form_dex1)); $('#id_form-TOTAL_FORMS').val(parseInt(form_dex1) + 1); }); const formData = new FormData() formData.append('csrf',document.getElementsByName('csrfmiddlewaretoken').value); formData.append('docs0',document.getElementById('id_form-0-docs').files[0]); formData.append('docs1',document.getElementById('id_form-1-docs').files[0]); formData.append('docs2',document.getElementById('id_form-2-docs').files[0]); formData.append('docs3',document.getElementById('id_form-3-docs').files[0]); const form = document.getElementById('docs-uploader-form') form.addEventListener("submit",submitHanler); function submitHanler(e){ e.preventDefault(); $.ajax({ type:'POST', url:"{% url 'booking:add_new_image' id=2222 %}".replace(/2222/,parseInt({{obj.id}})), data:formData, dataType:'json', success:successFunction, }) } function successFunction(data){ // console.log(data) form.reset(); alertify.success('added new image') } <button id="addButton" class="px-4 py-1 pb-2 text-white focus:outline-none header rounded-xl"> {% trans "add new image" %} </button> <form action="" method="POST" enctype="multipart/form-data" dir="ltr" id="docs-uploader-form">{% csrf_token %} {% for form in images.forms %} {{form.id}} {{images.management_form}} <div class="form-group mt-3" id="images"> {{ form.docs | add_class:'form-control-file' }} </div> {% endfor %} <div class="form-group mt-3" id="formset" style="display: none;"> {{ images.empty_form.docs | add_class:'form-control-file' … -
Django bootstrap collapse isnt working well
i am trying to make a nav bar collapse when a browser window reaches a minimum size it does collapse the right part of the navbar but the button doesnt show a list of the collapsed items which are register and login i am using django latest version with bootstrap3 <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"></button> <a class="navbar-brand" href="{% url 'blogs:Home' %}">MyBlog</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="{% url 'blogs:blogs' %}">blogs page</a></li> </ul> <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <li> <a>hello , {{ user.username }}</a> </li> <li> <a href="{% url 'users:logout' %}">logout</a> </li> {% else %} <li><a href="{% url 'users:register' %}">Register</a></li> <li><a href="{% url 'users:login' %}">Login</a></li> {% endif %} </ul> </div><!--navbar collapse--> </div> </nav> -
How to customize/styling forms using class based views
Is it possible to customize the HTML attributes of the form created by class base views? At this moment, I'm using a generic CreateView: class SlipCreateView(LoginRequiredMixin, CreateView): model = Atum fields = ['atum1', 'atum2', 'atum3', 'atum4', 'atum5', 'atum6', 'atum7'] I want to change, for example, the length and position of the input fields, the color, and others attributes. Is this possible? And if yes, how? Thank you advance. -
Django, Vue and WebSocket - getting client side to work
There was a similar question on SO about this some time ago, though I tried the answers and they did not work. I am implementing a SPA using Django backend and Vue front end with Vue cli. Django is using channels to send JSON via a WebSocket to the frontend, the frontend receives this data and is supposed to update a table. The Django part is working. A connection to the WebSocket is confirmed and data is received in Vue, though I have two problems that I have not been able to find a way to solve: The data, while in a variable, is not being shown on the table and The front end only receives the data once - I don't know how to apply a listener to the WebSocket, or in which part of my Vue app, so that new payloads (I hope I am saying that correctly) are received and updated accordingly. Below I have provided the Django consumers.py file, the Signals.vue view file, and the console.log output showing that the variable does contain the JSON object despite the table remaining blank. Does anyone have an idea of where I am going wrong and how I can … -
Django Model Constraint Condition With Field From Inherited Class - Is It Possible?
I'd like to use a field from a parent class as a constraint condition in a child class. models.py class ParentClass(object): ... is_public = models.BooleanField(default=False) class ChildClass(ParentClass): ... price = models.DecimalField(max_digits=6, decimal_places=2, null=True) class Meta: constraints = [ models.UniqueConstraint(fields=['price', 'is_public'], name='null_price'), models.CheckConstraint( check=Q(price__isnull=True) & Q(is_public=True), name='price_exists_check', ) ] When I attempt to migrate, I see this error in my terminal: myapp.ChildClass: (models.E016) 'constraints' refers to field 'is_public' which is not local to model 'ChildClass'. HINT: This issue may be caused by multi-table inheritance. It's obvious why I am seeing this error (is_public field lives in ParentClass). My question is, is it simply not possible then, or can I refactor something? What is my end-goal? To not let an instance of ChildClass is_pulic change to True if the price is null. I'd like to enforce this at the database level. Is there a way and if so, what needs to change?