Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Annotate queryset with count of instances related to it in another queryset
I have three related models like so: Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE ) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) Product(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) price = models.FloatField() geo_location = models.PointField(srid=4326, null=True, blank=True) City(models.Model): name = models.CharField(max_length=75) geom = models.MultiPolygonField(srid=4326) the related city can be retrieved from the geo_location field if specified example : city = City.objects.get(geom__contains=someproduct.geo_location) or from the owner's profile : city = someproduct.owner.profile.city lets suppose i have a these queries: all_cities = City.objects.all() products = Product.objects.filter(price__lt=2500) what i want to achieve is products_count attribute on each instance of the all_cities queryset from products queryset maybe a loop would solve this but don't know how to implement it and there might be another solution using Subquery and OuterRef -
how to serve webp from a variable in a static tag wagtail 2.5
I made a carousel orderable. each instance has an image and char field for the webp file name through the picture element. The webp image loads perfect when I hard code the srcset instead of using a {{variable}}. Problem is that keeps the admin backend from being dynamic and leaves me hard coding every pic on the site or just the pages I want to rank for on google. Ive read a bunch of other posts but im still stuck. is there any way to serve webp filename cleanly from the backend? I have read. load static file with variable name in django django 1.5 - How to use variables inside static tag This one was the closest to solving my problem but falls short. https://snakeycode.wordpress.com/2015/02/20/variables-in-django-static-tags/ carousel orderable fields carousel_image = models.ForeignKey("wagtailimages.Image", on_delete=models.SET_NULL,related_name="+",) webp = models.CharField(max_length=100, blank=True, null=True) home template carousel {% for loop_cycle in self.carousel_images.all %} {% image loop_cycle.carousel_image max-750x500 as img %} <picture> <source srcset="{% static '{{loop_cycle.webp}}'%}" type="image/webp" > <img src="{% static '{{img.url}}'%}" alt="{{ img.alt }}"> </picture> As this works perfect when I hard code but then whats the point of having a carousel with an orderable that is next-gen image friendly? Thank you for reading Im going … -
How do I pass a variable from views to a base html template using Django
I have a floatbar with contact details that shows only when the website is opened on a mobile screen. However, there are pages where I do not want them to appear, and I figured I can pass this through context in the respective view classes. What I need to figure out is how do I access this in my base template where this floatbar is called. I did read a bit about context processors, but I am not sure if I can change the value of the variable being passed. I would like to be able to access the variable in base html, but also change the value stored within views.py -
How to deploy django app on hosting service
I'm new to web development. I bought the web hosting start-up package from Siteground to host my graphic design portfolio website. It's a simple Django app that is a one-page portfolio with a contact form using Django's sendEmail through gmail service. I've never deployed a Django app, let alone my own website. I've only made and deployed a Wordpress website which is pretty self-explanatory. I understand how to upload my website to the server through FTP, but I have no idea how to configure the Django app for deployment (aside the brief explanation in their docs) or how to connect the app to my server to run on the domain. I think I'm supposed to configure something in wsgi, but I don't really understand how that works and I can't find support anywhere on deploying a Django app on Siteground (or something like it) even though they have python support. I connected to Sitegrounds' SSH to follow some tutorials on Django deployment, but even though it's Unix I can't use (or don't understand how to) sudo apt-get to follow the tutorials. Here is my settings.py: import os with open('cfsite/key.txt') as f: SECRET_KEY = f.read().strip() # Build paths inside the project … -
How to access foreign key nested fields in template
I have these models: class Board(models.Model): # Board in chassis# name = models.CharField(max_length = 20) SMT = models.CharField(max_length = 20) HM = models.CharField(max_length = 20) class Chassis(models.Model): #chassis information# name = models.CharField(primary_key=True,max_length = 10) board = models.ManyToManyField(Board) fa = models.CharField(max_length = 20) class DocDetials(models.Model): #document details chassis = models.ForeignKey(Chassis,related_name="details",on_delete=models.SET_NULL, null=True) boards = models.TextField(max_length = 50, blank=True, null = True) fields for 'Boards' and 'Chassis' are already defined manually in 'admin' site. What I want to do is to choose from those fields to fill-out my form which is connected to 'DocDetails' model. my form used on my views is using the model 'DocDetails'. I would like to access chassis.name, chassis.board (all items) and chassis.fa fields in my template, so I can display them in my html page. so far I can only access chassis.name by doing: {{ form.chassis.value }} but I cannot access other fields typing similar template tags. is there a way to do this? -
Why will my profile pictures not show up Django
So I am creating a small website, and I want users to be able to upload profile pictures to their page. However, I ran into a problem, and the image won't render. I have the actual process for the user to upload a profile picture, and it saves to a directory, but it won't load in the HTML document I have looked online for answers, but have found none. I have tried renaming fields in the models.py file because I thought that it might be an issue where I need a certain field name. None of these worked Here is the relevant UserProfileInfo model in models.py class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50,blank=True,null=True) #models.OneToOneField(User,'on_delete')# last_name = models.CharField(max_length=50,blank=True,null=True) #models.OneToOneField(User,'on_delete')# bio = models.CharField(max_length=150) image = models.ImageField(upload_to='profile_pics',default='default.png') joined_date = models.DateTimeField(blank=True,null=True,default=timezone.now) verified = models.BooleanField(default=False) def __str__(self): return self.user.username def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) Here is the views.py file for the user registration def register(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForms(data=request.POST) if user_form.is_valid and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'image' … -
How to in Django get a data from the dropdown
How to get the value from the queryset? MODEL: class LOCATION(models.Model): name = models.CharField(max_length=4, default=None, blank=True, unique=True, error_messages={'unique':"Already in Used"}) class Site(models.Model): code = models.ForeignKey(LOCATION,on_delete=models.SET_NULL, null=True) FORM: class location_Form(forms.ModelForm): class Meta: model = LOCATION fields = '__all__' field_classes = { 'json_field': JSONFormField, } class site_Form(forms.ModelForm): class Meta: model = Site fields = '__all__' field_classes = { 'json_field': JSONFormField, } VIEW def SITEview(request): template_name = 'site.html' code_name = LOCATION.objects.all() form = site_Form(request.POST or None) if request.method == 'POST': dc_pk_list = request.POST.getlist('code', None) selected_dc_query = LOCATION.objects.filter(pk__in=dc_pk_list) selected_dc = [i for i in selected_dc_query] print(selected_dc) RESULTS: How to get a just a value? from the below result: [<location: CHE>] just need CHE how to get the a text value only? -
How to make a ManyToMany serialization to be able to create a object in the POST request?
I'm trying to create a serialize to handle a ManyToMany relation, but it's not working. I have read the documentation and I probably doing something wrong. Also I have read the answers here. Here are my models. class Author(models.Model): name = models.CharField(verbose_name="Name", max_length=255) class Book(models.Model): author = models.ForeignKey( Author, related_name="id_author", blank=True, null=True, on_delete=models.PROTECT) price = models.FloatField(verbose_name="Price") class FiscalDocument(models.Model): seller = models.ForeignKey( User, related_name="user_id", on_delete=models.PROTECT) book = models.ManyToManyField(Book) My serializer: class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ('id', 'name') class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('id', 'author', 'price') def to_representation(self, instance): response = super().to_representation(instance) response['author'] = AuthorSerializer(instance.author).data return response class FiscalDocumentSerializer(serializers.ModelSerializer): book = BookSerializer() class Meta: model = FiscalDocument fields = ('id', 'seller', 'book') def create(self, validated_data): book_data = validated_data.pop('book') fiscal_document = FiscalDocument.objects.create(**validated_data) Book.objects.create(FiscalDocument=FiscalDocument,**medicine_data) return fiscal_document When I try to access the endpoint of the FiscalDocument, django-rest-framework is throwing an error: Got AttributeError when attempting to get a value for field price on serializer BookSerializer. The serializer field might be named incorrectly and not match any attribute or key on the ManyRelatedManager instance. Original exception text was: ManyRelatedManager object has no attribute price. If anyone can help XD. -
"Unknown column in having clause" when using a SimpleFilter on Django admin
I'm using a simple filter to filter model results on Django Admin. Even though all the queries are tested and working well, the code keeps throwing an error. I think it may be a bug. OperationalError at /calibracion_de_instrumentos/instrumentos/ (1054, "Unknown column 'instrumentos.fecha_compra' in 'having clause'") As you may read, it says "Unknown column in having clause". If i execute qs.filter(tiempo_para_vencimiento__gte=timedelta(3) while debugging the method queryset in the Filter, it works fine... This is part of my admin.py class DiasVencimientoFilter(admin.SimpleListFilter): title = ('Por tiempo para vencimiento') # Parameter for the filter that will be used in the URL query. parameter_name = 'tiempo_para_vencimiento' def lookups(self, request, model_admin): qs = model_admin.get_queryset(request) if qs.filter(tiempo_para_vencimiento__lte=timedelta(0)).first() is not None: yield ('vencido', ('Vencido')) elif qs.filter(tiempo_para_vencimiento__gte=timedelta(3), tiempo_para_vencimiento__lte=timedelta(7)).first() is not None: yield ('menosDe3', ('Una semana')) elif qs.filter(tiempo_para_vencimiento__gte=timedelta(7), tiempo_para_vencimiento__lte=timedelta(14)).first() is not None: yield ('menosDe7', ('Dos semanas')) elif qs.filter(tiempo_para_vencimiento__gte=timedelta(14), tiempo_para_vencimiento__lte=timedelta(31)).first() is not None: yield ('menosDe14', ('Un mes')) return qs def queryset(self, request, queryset): if self.value() == 'vencido': return queryset.filter(tiempo_para_vencimiento__lte=timedelta(0)) elif self.value() == 'menosDe3': return queryset.filter(tiempo_para_vencimiento__gte=timedelta(3), tiempo_para_vencimiento__lte=timedelta(7)) elif self.value() == 'menosDe7': return queryset.filter(tiempo_para_vencimiento__gte=timedelta(7), tiempo_para_vencimiento__lte=timedelta(14)) elif self.value() == 'menosDe14': return queryset.filter(tiempo_para_vencimiento__gte=timedelta(14), tiempo_para_vencimiento__lte=timedelta(31)) # return queryset.filter(tiempo_para_vencimiento__lt=timedelta(0)) # return Instrumentos.get_all_data(Instrumentos.objects).filter(tiempo_para_vencimiento__lte=timedelta(0)) return queryset class AdminInstrumentos(admin.ModelAdmin): list_display = ... list_display_links = ... list_filter = (... , DiasVencimientoFilter) … -
DRF tries updating read-only fields
I have a Django model (derived from the CleanerVersion Versionable model) which I am serializing using DRF and I want several fields set to read only (they are created by a series of functions and are therefore set as properties), however when I try to update the record, the read-only fields are included in the validated_data, and are also included in the procedure which sets the attribute and the value during the update(). My model.py class Athlete(Versionable): ... @property def photo_status(self): if(self.photo!=None): return True return False ... For my serializer.py I tried different approaches: Setting the serializer field to read-only class AthleteSerializerSerializer(serializers.ModelSerializer):: ... photo_status= serializers.BooleanField(read_only=True) ... class Meta: model = Athlete fields = '__all__' ... Excluding the field class AthleteSerializer(serializers.ModelSerializer):: ... class Meta: model = Athlete exclude = ['photo_status'] ... Added the extra kwargs class AthleteSerializerSerializer(serializers.ModelSerializer):: ... class Meta: model = Athlete fields='__all__' extra_kwargs = { 'photo_status': {'read_only': True}, } ... and no matter what, when I run: serializer = AthleteSerializer(Athlete.objects.current.get(identity=a.identity),data=request.data.get("athlete")) serializer.is_valid() serializer.save() I get the following error message setattr(instance, attr, value) AttributeError: can't set attribute I set several different properties to read only, as well as a few field (e.g. CleanerVersion automatically updates the id and identity fields so … -
Dealing with varying child levels in Django models
So I've got a database that has an incomplete hierarchy and I'm not quite sure how to deal with it. For example, I want to measure the mass of species.. Each family can have multiple geneses. Each genus can have multiple species. However, not ALL species have a sub-species (with sub-species being the lowest level). In other words, the endpoint of the hierarchy could be subspecies OR species. The solution I have come up with doesn't seem to follow good principles. class mass(model.Models): name = models.CharField(max_length=100) value = models.NumericField() family = models.ForeignKey(family) genus = models.ForeignKey(genus) species = models.ForeignKey(species) subspecies = models.ForeignKey(subspecies) # Could be a blank field class family(model.Models): name = models.CharField(max_length=100) class genus(model.Models): name = models.CharField(max_length=100) family = models.ForeignKey(family) class species(model.Models): name = models.CharField(max_length=100) genus = models.ForeignKey(genus) class subspecies(model.Models): name = models.CharField(max_length=100) species = models.ForeignKey(species) -
how to use VueJs components in Django using django webpack loader?
I followed this tutorial and integrated Django and VueJs using django-webpack-loader?and now the main.js output from django-webpack-loader is loading to my index.html this is my project directory structure assets bundles app.js js components Demo.vue index.js db.sqlite3 manage.py myapp myproject node_modules package.json package-lock.json requirements.txt templates webpack.config.js webpack-stats.json my Demo.vue component has been imported to the index.js and using webpack.config.js file all necessary file has been bundled together to app.js my question is what is the next step? for example if I have some VueJs components and want to use them in some of my templates how should I do that?should I create components in the component directory and bundle them all? if this is the case how should I choose to use or not use a component in a specific template? and how should I use Django template tags to insert dynamic data? or I should write my components in another way? I know there is multiple questions here, but I couldn't find a good reference to answer my questions so any help would be appreciated -
s it possible to use request object outside of views or other way to get current user information
I want to operate some filter with user based. So I need logged user information in my admin.py or other file. But I don't understand how it possible to get current loged user id or other information. Any one help me? Example Code... @register(Category) class CategoryAdmin(admin.ModelAdmin): ordering = ['priority'] if **user.is_superuser**: #do something here.... list_display = ('name', 'slug', 'priority', 'report', 'read_counter') else: list_display = ('name', 'slug') -
django.template.exceptions.TemplateDoesNotExist: home.html
django project was working fine! home page and other pages were rendering no problems. I creating products app/ component page and accidentally named "templates" template so i renamed template to "templates" and that when i started have issues. I ran terminal commands: python manage.py makemigrations python manage.py migrate python collectstatic Nothing is working! I am getting an error message: django.template.exceptions.TemplateDoesNotExist: home.html -
Django: cannot delete formset forms (Javascript on the frontend)
I have a basic invoice application and, in the single invoice update view, it is possible to add and remove elements of the invoice. Adding them works, unfortunately it does not in removing them. Even if in the frontend they get removed (via Javascript), the number of TOTAL_FORMS reduces accordingly and formset.cleaned_data shows only the rendered forms, they are still there saved in the model instance. Invoice model: class Invoice(models.Model): class Meta: verbose_name = "invoice" verbose_name_plural = "invoices" def __str__(self): return f"{str(self.date)}-{self.client.name}" def get_absolute_url(self): return reverse("invoice-list") @property def total(self): tot = 0 for el in self.elements.all(): tot += el.price return tot date = models.DateField(auto_now_add=True) client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='clients') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="invoices") Element model: class Element(models.Model): class Meta: verbose_name = "element" verbose_name_plural = "elements" def __str__(self): return self.name name = models.CharField(max_length=200, blank=False, null=False) price = models.IntegerField() invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE, related_name="elements") invoice form and element formset: class InvoiceForm(ModelForm): class Meta: model = Invoice fields = ['client'] def __init__(self, *args, **kwargs): userid = kwargs.pop('userid', None) super().__init__(*args, **kwargs) self.fields['client'] = forms.ModelChoiceField(queryset=Client.objects.filter(user_id=userid)) InlineElementFormsetUpdate = inlineformset_factory(Invoice, Element, fields=('name', 'price'), extra=0, can_delete=True) Invoice UpdateView: def update_formset(request, id): user = request.user invoice = Invoice.objects.get(id=id) elements = invoice.elements.all() invoice_form = InvoiceForm(instance=invoice) if request.method == 'POST': … -
What is parameterized query when django is involved?
I have seen this question being asked What is parameterized query?! but I fully do not understand how it secures web applications from A1 injection! from the OWASP top 10 guide!. I would appreciate it if someone explains in a lay term format and how string formatting further makes web applications secure from the same vulnerability. -
Dynamically change form labels in Django/oTree
I have a form label that I want to have variable content. I expose to my template a variable called outgroup which I want to be included in the formfield label. My current (incorrect) attempt looks like this: {% formfield sent_amount label="How much do you want to send to a "+{{outgroup}} %} But this obviously doesn't work. What is the correct way to get a variable into the label method? -
how to filter dynamically the availables values of a foreign key in a inline definitions according a value of its parent model
I have the below models.py: class Vendor(models.Model): name = models.CharField(max_length=256) def __str__(self): return self.name class Products_by_vendor(models.Model): vendor = models.ForeignKey(Vendor,on_delete=models.CASCADE,null=False,blank=False) item = models.CharField(max_length=50) price = models.DecimalField(max_digits=10,decimal_places=2) def __str__(self): return str(self.vendor) + ' ' + self.item class Invoice(models.Model): number = models.IntegerField(null=False,blank=False) vendor = models.ForeignKey(Vendor,on_delete=models.PROTECT,null=False,blank=False) def __str__(self): return str(self.number) + ' ' + str(self.vendor) class Invoice_detail(models.Model): invoice = models.ForeignKey(Invoice,on_delete=models.PROTECT,null=False,blank=False) product = models.ForeignKey(Products_by_vendor, on_delete=models.PROTECT, null=False, blank=False) def __str__(self): return self.invoice + ' ' + sel.product And i using the admin site in order to built the CRUD functions needed. So, I have the setup for manage the header model and its related child in a form using inlines feasibility (Invoice and Invoice_detail). The code to admin.py is: class Invoice_detailInline(admin.TabularInline): model = Invoice_detail extra = 0 class EnterInvoice(admin.ModelAdmin): pass inlines = [Invoice_detailInline] admin.site.register(Invoice,EnterInvoice) Then, after added a new line for Invoice_detail model, for the field Invoice_detail.product, I need to show only the products records that belong at vendor entered in the header form In others words, the expected behavior is to filter the content of "list box" widget in functions to the value entered in a field of the parent model. I read the documentation and between several options that i think can be used … -
Image as base64 in django
What is the reason that the image will not work where I have converted the image with this code Is there a way to operate the image def image_as_base64(image_file, format='png'): """ :param `image_file` for the complete path of image. :param `format` is format for image, eg: `png` or `jpg`. """ if not os.path.isfile(image_file): return None encoded_string = '' with open(image_file, 'rb') as img_f: encoded_string = base64.b64encode(img_f.read()) return 'data:image/%s;base64,%s' % (format, encoded_string) print(image_as_base64( photo.image.path)) the output not work: data:image/png;base64,b'/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMTEhUSExMVFhUXGR0YFxgYGBobGBcXHhYeGRcYGBoaICggGB4lGx0bIjEjJSkrLi4uHh8zODMtNygtLisBCgoKDg0OGxAQGysmICUtLS0tLS0tLS0tLS0tLS0tLS0tL S0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLf/AABEIALcBEwMBIgACEQEDEQH/xAAbAAABBQEBAAAAAAAAAAAAAAAFAAEDBAYCB//EAEkQAAIBAgQDBQQJAQQIBAcAAAECEQMhAAQSMQVBUQYTImFxMoGRoQcUI0JSscHR8OEVM2JyU2OCkpOy0v EkQ6KzCBZEc6TC8//EABgBAAMBAQAAAAAAAAAAAAAAAAABAgME/8QAJREAAgICAgMAAgIDAAAAAAAAAAECERIhAzETQVEiYRSBBDJx/9oADAMBAAIRAxEAPwAZw6l3FAVe7B72KrgAmGcEqD41gaSN9RY6ttN46CIr1EqK/wBq9Bx4QdOsJdrRqpqxII0 3UyCDGCXZftRl+4q06zKlUD7N2mGG8apt4pOmwvzk4qjtxTo1DTqMj0pBOkhmOpIcreOZFumOJSbk1ib1SuyRVyzEv31RvYlokQHdgwUiSQsEHaW28JGO9GWqugCwPDqPjB7su+sgNcEBVHKe82kQBeY+lGmtZ6lHLtddKM7AGbXKr7NxNib4ov8ASdUL q31SidJBEliRdm8Jjw+Jzy2AGLXHN+iXNL2FOKU8pVKNUr1qbIRqKqRJZkDSGQgEFVAUWsbnY1eL/wBniitMs4hGAGp7VCgZbhNhUEExteACJr53t1TOWqd1TUVngeJJPsBA83BI0hh/iJPM4IdruOCmtNqVGgyka/ZBT20CkXuQKYX/ACkzyxpHUkmKW 02AuG8PyYzNVBUNSmNKI5LENqg1o7kSSEJCn2ZuTtgxl8rlmosrVagjSviK954hTnTTVOReqswfZU31WF8P7ZMRVY5ehqVO8B0c1rBgI2+/pn8IAxey/HX7tWWlSL1tD1AQY1KSaREEQdYDT+KPLGk3vZnFfDnKNkai6PrFWEZSGKFY01gVaAntd0GsQZ MbHFhsj...... -
How to run django an react project on pycharm?
I have a a complied version of react.js but I am not familiar with react.js. How do i run django project with react.js? -
(Django) Dynamically adding custom form to Inline admin
CONTEXT I'm building my personal website, and wanted to handle database translation. While django-apps already exist for it, I thought it'd be fun and interesting to build my own translation package. I'm currently at the last step, which is showing the Translation instances directly into the object's admin STRUCTURE What you need to know about the database is that I have the following tables/models: My models that have fields which require translations: Job, Type, Article, etc. Language (list of available languages) Item (equivalent to saying "the NAME field from the JOB model, instance 33" Translations (Many to many with Language and Item) As for the relationships that matter to us: Job, Type, and Article all have ForeignKeys to Item Note that they can have SEVERAL ForeignKey (if they have several fields that need translating) Item has a GenericForeignKey to store Job, Type, and Article instances Translation has a ForeignKey to Item WHAT I'M TRYING TO DO In the admin, in the Type (or Job, or Article) detail view, I'd like to directly display the Translation instances related to its object (Type--> Item --> Translation). It's basically like a nested inline, but I only display the last level. That way, I … -
How to flatten JSON before serializing?
Consider following JSON post request: { "a":{ "b": 1, "c": 1 } } my model only has fields for b and c. I need to flatten the JSON and serialize the following: { "b": 1, "c": 2 } I'm using serializers.ModelSerializer class to serialize: class CardTransactionEventSerializer(serializers.ModelSerializer): class Meta: model = CardTransactionEvent fields = [ "a", "b", ] view: class MyListView(generics.ListCreateAPIView): queryset = models.MyModel.objects.all() serializer_class = serializers.MySerializer model: class MyModel(models.Model): a = models.CharField(max_length=20, blank=False, ) b = models.CharField(max_length=10, blank=False, ) I don't care about the a I just need to serialize what is inside of it. Thank you in advance. -
How to pass extra context to Django inline formset template
I have an inline formset that works fine. Now I need to add some additional context data to the inline formset template. It is straightforward to add context data to the parent template, but I do not seem to figure out how to set it to the formset template. The data is fetched from external service, so I want to add it only when needed. Two hacky ways I have identified: templatetags template context processor, which would include a function that would return the value Are there any cleaner ways to do this? -
Django ModelChoice field is set to required=False but is still required in the browser
class One(forms.ModelForm): space = forms.ModelChoiceField(queryset=models.Space.objects.none(), required=False) mode_specific = False class Meta: id_fields = ["name", "description", "space"] def __init__(self, *args, **kwargs): super(One, self).__init__(*args, **kwargs) # this returns false print(self.fields["space"].required) But on the template, the "space" is still required, I'm not sure what the issue is. -
what value should I provide instead of "Confirm" if that is the issue! Or else please help me out about the issue
Well while deleting my 'posts'in 'blog' i got an error stating TemplateDoesNotExist. "Blog/post_confirm_delete.html". Do I have to give the address about the "post_delete" file in the "home" as well? After already linking it to "post_details". Please check the code below. Template post_delete file {% extends 'base.html' %} {% block content %} Delete post <form action="" method="post">{% csrf_token %} <p>Are you sure you want to delete "{{ post.title }}"?</p> <input type="submit" value="Confirm" /> </form> {% endblock content %} views file class BlogDeleteView(DeleteView): model = Post template = 'post_delete.html' success_url = reverse_lazy('home') reverse_lazy is already been impoerted. Linking file "post_detail.html" which contains URL Tags {% extends 'base.html' %} {% block content %} <div class="post-entry"> <h2>{{ post.title }}</h2> <p>{{ post.body }}</p> </div> <p><a href="{% url 'post_edit' post.pk %}">+ Edit Blog Post</a></p> <p><a href="{% url 'post_delete' post.pk %}">+ Delete Blog Post</a></p> {% endblock content %} MY URLS file all the models are already been imported urlpatterns = ( path('post//delete/', BlogDeleteView.as_view(), name='post_delete'), ) and my model class from django.db import models from django.urls import reverse Create your models here. class Post(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey( 'auth.User', on_delete = models.CASCADE, ) body = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse('post_detail', args=[str(self.id)])