Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
If statement in Django not displaying the output
I want to display a delete button alongside comments that the request.user has written so that only they can remove them, but for some reason can't get my if statement to work. Here is my template: {% for post in posts %} ... {% if post.comment_set.all %} {% for comment in post.comment_set.all %} <img src="{{ comment.user.image }}"> <p>{{ comment.body }}</p> {% if comment.user == request.user %} # delete icon with modal {% endif %} {% endfor %} {% endif %} {% endfor %} It is the if comment.user == request.user tag which is not working. I have tried outputting both comment.user and request.user in <p> tags and both display the way I would expect, so can't understand why it doesn't work. I have also tested the delete button which does display correctly when the if statement is removed. Here are my relevant models for reference: class Comment(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) body = models.TextField() class Post(models.Model): content = models.TextField() author = models.ForeignKey(Profile, on_delete=models.CASCADE) image= models.ImageField(blank=True, null=True, default='profile_pics/default.png', upload_to='profile_pics') class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Strangely, further up the page I have used similar code to display delete beside the blog posts themselves, using {% if post.author.user … -
HttpResponseRedirect in Django is not redirecting to the page views.py file
My views.py looks like: from django.shortcuts import render from django.http import HttpResponseRedirect from django.urls import reverse from django import forms from . import util import markdown2 def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def entry(request, title): if title not in util.list_entries(): return render(request, "encyclopedia/error.html", { "error": "Page Not Found", "query": title }) else: return render(request, "encyclopedia/entry.html", { "entry": markdown2.markdown(util.get_entry(title)), "title": title }) def search(request): if request.POST["q"] in util.list_entries(): return HttpResponseRedirect(reverse("entry", args=(request.POST["q"],))) else: return render(request, "encyclopedia/error.html") Here my urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<str:title>", views.entry, name="entry"), path("search", views.search, name="search") ] Next comes my layout.html template which other pages extend from this: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet"> </head> <body> <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form action="{% url 'search' %}" method="POST"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> <div> <a href="{% url 'index' %}">Home</a> </div> <div> Create New Page </div> <div> Random Page </div> {% block nav %} {% endblock %} </div> <div class="main col-lg-10 col-md-9"> {% block body %} {% endblock %} </div> </div> … -
Data doesn't change after sending PUT method
I'm doing some basic CRUD application with python django. Basicly, from the Front End, I want to send some raw text data, the Backend will catch It, and re-send the cleaned ones. For now, the clean method worked but for some reason, It still sending the same raw text to the Front End. This is my code: in models.py: class Post(models.Model): content = models.TextField(max_length=3000, blank=False, default='') in serializers.py: class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('id', 'content') in views.py: @api_view(['PUT']) def create_post(request): if request.method == 'PUT': post_data = JSONParser().parse(request) post_serializer = PostSerializer(data = post_data) if post_serializer.is_valid(): data_to_clean= str(post_serializer.data['content']) # this is raw text (i.e: "aBcD") cleaned = clean(data_to_clean) # this is text after cleaning (i.e: "abcd") post_serializer.data['content'] = cleaned # update the new text return JsonResponse(post_serializer.data, status = status.HTTP_200_OK) return JsonResponse(post_serializer.errors, status=status.HTTP_400_BAD_REQUEST) Can you point out what is wrong with this code. Many thanks. -
How can i pick only the first row of each hour in a db using django orm
I want to fetch only the first row of each hour in a db using django orm any suggetsions ? summary_exists = xx_table.objects.all().filter( summary_date__range=(date_from, date_to) -
Unable to import PyPDF2 module
I am using VScode text editor, and I'm trying to import PyPF2 module which I have already installed in my Django virtual environment. (project) C:\Users\Bhargava\django-apps\mysite>pip install PyPDF2 Requirement already satisfied: PyPDF2 in c:\users\bhargava\envs\project\lib\site-packages (1.26.0) But I'm still getting the following errors. error: Import "PyPDF2" could not be resolvedPylance (reportMissingImports) [Running] python -u "c:\Users\Bhargava\django-apps\mysite\home\mcq.py" Traceback (most recent call last): File "c:\Users\Bhargava\django-apps\mysite\home\mcq.py", line 1, in <module> import PyPDF2 ModuleNotFoundError: No module named 'PyPDF2' [Done] exited with code=1 in 1.337 seconds I've tried adding every path to system environment variables, but nothing worked. Can anyone help me out? Thank you. -
Which field can be used in django serializers for entering ipaddress with subnet mask
Which field can be used in django serializers for entering ipaddress with subnet mask. example: x.x.x.x\x is the input format. -
How to show a list instead of choose from choicelist in django
Here is an invoice. In this case, it shows lines of products and user can select products on each line from dropdown list. My need is to show all products, each line with one product which i can fill with details as price and quantity as example bellow. Models: class Invoice(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) number = models.CharField(max_length=64, unique=True, default=invoice_number) date = models.DateField(default=timezone.now) client = models.ForeignKey('Client',on_delete=models.CASCADE) class InvoiceItem(models.Model): invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(max_digits=20, decimal_places=2) quantity = models.DecimalField(default=0, max_digits=20, decimal_places=2) forms: class InvoiceForm(ModelForm): class Meta: model = Invoice fields = "__all__" class InvoiceItemForm(ModelForm): class Meta: model = InvoiceItem fields = "__all__" InvoiceItemFormSet = inlineformset_factory(Invoice, InvoiceItem, form=InvoiceItemForm, extra=3, can_delete=False) View : class InvoiceCreate(CreateView): form_class = InvoiceForm model = Invoice template_name = "sales/invoice_form.html" def get_success_url(self): return reverse_lazy('invoice_details', kwargs={'pk' : self.object.pk}) def get(self, request, *args, **kwargs): company_instance = request.user.company self.object = None form = InvoiceForm(company_instance) formset = InvoiceItemFormSet(form_kwargs={"company":company_instance}) products = list(Product.objects.values()) return self.render_to_response( self.get_context_data(form=form,formset=formset, products=products)) def post(self, request, *args, **kwargs): self.object = None company_instance = request.user.company form = InvoiceForm(company_instance, self.request.POST) formset = InvoiceItemFormSet(self.request.POST, form_kwargs={"company": company_instance}) if (form.is_valid() or formset.is_valid()): return self.form_valid(form, formset) else: return self.form_invalid(form, formset) def form_valid(self, form, formset): self.object = form.save() formset.instance = self.object formset.save() try: … -
(Django) webp Image url Cant open in new tab, that force me to download before opened
(Django) Anyone can open webp image in new tab?, I have a problem with webp when I open webp image in new tab I always forced to download that image and then that image can opened as File in Web Browser. I mean just like png or jpg when I open in new tab, that just show me Image in new tab as url not to force download that image. Any suggestion? Example Url: http://127.0.0.1:8001/media/image.webp -
Why isn't my POST Webhook working in Django?
I use the app Salesmate and am trying to write a a client on my site that adds features through the API. For this to work I need Salesmate's Webhooks. My client is in Django. When I send a GET request webhook it makes it into my client. When I send a POST request webhook it never makes it into the view. When I send a test POST request from https://reqbin.com/ it makes it into the view and performs as expected. I've played endlessly with the JSON body and headers. There could still be something I'm missing here, or there could be a flag raised in Django invalidating the sender, or something else... Here is Salesmate webhook request, in the app. I've played with many headers, and sent requests with and without JSON bodies. Request details 1 Request details 2 Here is my django view. Super simple, but it never gets called. from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse @csrf_exempt def pab(request): #Do something simple and trackable return HttpResponse(keep) -
How to serialize and de-serialize data in single field to a nested serializer Django Rest Framework?
Considering I have this model: class AddressLocation(models.Model): streetaddress = models.CharField(max_length=255, blank=True) xcoordinate = models.FloatField(null=False, blank=False) ycoordinate = models.FloatField(null=False, blank=False) created = models.DateTimeField(null=False, blank=False) And these serializers: class AddressSerializer(serializers.Serializer): streetAddress = serializers.CharField(label="Street Address", required=True) postalCode = serializers.CharField(label="Postal Code") city = serializers.CharField(label="City") country = serializers.CharField(label="Country") class AddressLocationSerializer(serializers.ModelSerializer): address = AddressSerializer() xcoordinate = serializers.FloatField(null=False, blank=False) ycoordinate = serializers.FloatField(null=False, blank=False) class Meta: model = AddressLocation fields = [ 'id', 'address', 'xcoordinate', 'ycoordinate', 'created' ] How can I serialize and de-serialize the values for "address" since the values of it's fields will be stored on a single field "streetaddress" on the model? For more info my data format for my request and response should look like this: Request: Method: POST data: { 'address':{ 'streetAddress': "Sample Street Name", 'postalCode': "9999" 'city': "City" 'country': "Country" }, 'xcoordinate': '<x coordinate value>, 'ycoordinate': '<y coordinate value> } Response: data: { 'id': <record_id> 'address':{ 'streetAddress': "Sample Street Name", 'postalCode': "9999" 'city': "City" 'country': "Country" }, 'xcoordinate': <x coordinate value>, 'ycoordinate': <y coordinate value>, 'created': <date_created> } I am fairly new to DRF so I am not sure if this is achievable. -
Having a form and some plots on the same page with django?
I'm trying to learn use Bokeh and django to visualize some data, and I'm on a windows 10 laptop doing this project using VS code and Anaconda in a virtual environment, if this is relevant. My goal is that the user shall be able to input a number into a field, hit submit, and the bokeh graph shall update. This means, if I understand it correctly that both bokeh graph and django form must lie under the same view-function in my views.py-script. I have successfully created the graph, and am hitting difficulties with the form. I think it stems from me not properly understanding the POST vs GET requests. Following a tutorial(https://www.youtube.com/watch?v=3XOS_UpJirU) I tested out the form feature by creating a forms.py with a very basic input form: from django import forms class InputForm(forms.Form): scalar=forms.IntegerField(label="A number: ") Then I created a basic "formtest.html" file just to display the form. <!DOCTYPE html> <html lang="en"> <head> <title>Document</title> </head> <body> <form method="POST"> {% csrf_token %} {{form}} <button type="submit">Submit</button> </form> </body> </html> And in views.py I added: def formtest(request): #This form was built to test that a value can be submitted and passed to the backend if request.method=="POST": form=InputForm(request.POST) if form.is_valid(): scalar=form.cleaned_data['scalar'] print("This is … -
How to navigate to home page? - python django
I have created an Index page using HTML and have given an URL for "Home" button, In a way that when the home button is clicked the page navigates from Index page to home page. But it doesn't navigate to home page, when clicked in URL address the address changes to the specified location correctly but the page displayed is still the Index page. <div class="top-menu"> <div class="container"> <div class="row"> <div class="col-xs-2"> <div id="fh5co-logo"><a href="{% url 'index' %}">TrainedbySamson<span>.</span></a></div> </div> <div class="col-xs-10 text-right menu-1"> <ul> <li class="active"><a href="{% url 'tbs_home:home' %}">Home</a></li> <li><a href="{% static 'gallery.html' %}">Gallery</a></li> <li><a href="{% static 'about.html' %}">Trainer</a></li> <li><a href="{% static 'pricing.html' %}">Pricing</a></li> <li class="has-dropdown"> <a href="{% static 'blog.html' %}">Blog</a> tbs_home/urls.py: urlpatterns = [ path('home',views.home, name='home'), ] tbs_home/views.py: def home(request): return render(request, 'home.html') templates/home.html: {% load static %} {% block content%} <h1 style = "font-family:Georgia;font:40px;font-style:normal;">Hi! {{name}}</h1> <form action="add" method="POST"> {% csrf_token %} Enter 1st num : <input type="text" name="num1"><br> Enter 2nd num : <input type="text" name="num2"><br> <input type="submit"> </form> {% endblock %} So when I click the home button according to the code the page should navigate to home.html page?. But it stays in the same Index page, thanks in advance. -
Django queryset with complex annotation
I have a User queryset along with 3 relations: class Review(models.Model): user = models.ForeignKey(settings.USER_MODEL) class ReviewTask(models.Model): review = models.ForeignKey("Review") competency = models.ForeignKey("Competency") class Competency(models.Model): name = models.CharField(max_length=50) I'm trying to annotate this queryset with a string that contains an ordered set of competency names associated with a user. For example, i I wanted to add this as a method on the User model, it would be as simple as: class User(...): def competency_names(self): names = set() for rt in ReviewTask.objects.filter(review__user=self): names.add(rt.competency.name) return ",".join(sorted(set(names))) The annotation examples I've looked at all seem far simpler than what I'm trying to accomplish. Is it feasible or no? -
{detail":"Missing filename. Request should include a Content-Disposition header with a filename parameter." in angular 10 and drf
I want to upload image but unable to upload when I test api in postman is doesn't gave any error but when I post data from angular and post data in json format it raised error {detail":"Missing filename. Request should include a Content-Disposition header with a filename parameter." in angular 10 and drf} When I post data from formData it raised error "rc_proof": [ "The submitted data was not a file. Check the encoding type on the form." ]" I am not getting whats going wrong here. I search a lot but not getting the expected result in my project Thank You in Advance ------------:) views.py class AgencyCarViewSet(viewsets.ModelViewSet): permission_classes = (AllowAny,) serializer_class = AgecyCarSerializer def get_queryset(self): return AgencyCar.objects.all() parser_classes = [MultiPartParser, FileUploadParser] serializers.py class AgecyCarSerializer(serializers.ModelSerializer): class Meta: model = AgencyCar fields = "__all__ component.ts onSubmitForm() { if (this.agencyCarForm.valid){ let data = { user : 1, brand: this.agencyCarForm.value.brand, carname: this.agencyCarForm.value.carname, car_model: this.agencyCarForm.value.carmodel, rc_proof: this.agencyCarForm.value.rc_proof, manufacture_year: this.agencyCarForm.value.manufacture_year, } const formData = new FormData(); formData.append("brand", this.agencyCarForm.value.brand); formData.append("carname", this.agencyCarForm.value.carname); formData.append("car_model", this.agencyCarForm.value.carmodel); formData.append("rc_proof", this.agencyCarForm.get('rc_proof').value); formData.append("manufacture_year", this.agencyCarForm.value.manufacture_year); formData.append("user", "1"); console.log(formData); this.service.postCars(data).subscribe((data: any) => { console.log(data); this.router.navigate(['/account']); },(error:any)=>{ console.log(error) }) } } componet.html <form [formGroup]="agencyCarForm" (ngSubmit)="onSubmitForm(agencyCarForm.value)"> <mat-form-field appearance="outline" class="w-100" > <mat-label>Brand</mat-label> <mat-select formControlName="brand" required (ngModelChange)="getCarName($event)"> <mat-option value="">Select … -
ValueError: Field 'id' expected a number but got 'suzukitadashi'
ValueError: Field 'id' expected a number but got 'suzukitadashi' error happens. I want to put data into DB got in Django server. I wrote models.py of app project, from django.db import models from django.contrib.auth.models import User class User(models.Model): user_id = models.CharField(max_length=10) password1 = models.CharField(max_length=20) password2 = models.CharField(max_length=20) class Analytics(models.Model): user_foreign_key = models.ForeignKey("auth.User", on_delete=models.CASCADE, verbose_name="foreign_key") point = models.CharField(max_length=200) I wrote models.py of index project from django.db import models class UserData(models.Model): data_foreign_key = models.ForeignKey("registration.User", on_delete=models.CASCADE) user_id = models.CharField(max_length=20) access_date = models.DateTimeField('アクセス日時') views.py of index def top(request): json_data = json.loads(request.body.decode("utf-8"), strict=False) user_data = UserData.objects.get(data_foreign_key="suzukitadashi") user_data.user_id = get_random_string(10) user_data.access_date = datetime.datetime.now() user_data.save() return JsonResponse(json_data, safe=False) When I accsess top method and run above code,the error happens. I rewrote the code like user_data = UserData.objects.get(data_foreign_key=1) same error happens. I login into Django app in suzukitadashi. What is caused this error? -
Django UserCreationForm doesnt show custom input fields
I am new to django and I am trying to learn the inbuilt user registration using the "django.contrib.auth.forms import UserCreationForm". Any help would be appreciated. Thanks!! The default form is interpreted in the browser, but when I explicitly add a field attribute(email) as in fields = ["username", "email", "password1", "password2"] in the meta class, I still get the same form with only username password and confirm passwords .The email doesn't show up in the browser. I am attaching the source codes of forms.py , views.py and the html(register page) below. Thanks in advance !! I am attaching every import lines just in case. Thanks! forms.py from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from .models import Order,Customer class CreateUserForm(UserCreationForm): class meta: model = User fields = ['username' , 'email' , 'password1' , 'password2'] class OrderForm(ModelForm): class Meta: model = Order fields = '__all__' ''' views.py: from django.shortcuts import render,redirect from django.http import HttpResponse from django.forms import inlineformset_factory from django.contrib.auth.forms import UserCreationForm from .models import * from .forms import OrderForm,customerForm,CreateUserForm from .filters import OrderFilter def registerPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() context = {'form' : … -
Style of django admin is not shown
This is how my Django admin page looks like: Though in my network section this is the result: And the url path of these requests are correctly set by the static url, these are the Django settings: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') I collect statics before serving my app: RUN python3 manage.py collectstatic --noinput (This is part of my Dockerfile) some parts of my docker-compose: web: restart: always image: <some private image> ports: - "127.0.0.1:8000:8000" volumes: - static_volume:/<path>/static nginx: container_name: nginx image: nginx:1.19.3 restart: always ports: - 80:80 - 443:443 volumes: - static_volume:/home/status/statics volumes: static_volume: This is inside my nginx container: Also this is in my https config for my nginx: Well to me it seems like everything is working and I can't understand what's wrong with it. -
Docker + django + gunicorn connect to Nginx of the host system
On ubuntu server 18.04 I run a docker container with Django 3.1 and Gunicorn which connects to a locally installed Postgres. I already have an another Django project with Nginx and Gunicorn on the same server without docker. The questions are: how to set up socket files for Gunicorn in a container and connect this container to the existing external Nginx so I can access the containerized django app from outside? docker-compose.prod.yml version: '3' services: app: build: context: . ports: - "8001:8001" volumes: - ./app:/app env_file: - .env.prod command: > sh -c "gunicorn app.wsgi:application --bind 0.0.0.0:8001" I run the container like this: docker-compose -f docker-compose.prod.yml up .env.prod ... DJANGO_ALLOWED_HOSTS='111.111.111.111 .mysitename.com localhost 172.18.0.1 127.0.0.1 [::1]' ... when running container executing of this command: curl 'http://127.0.0.1:8001/admin/login/?next=/admin/' gives me the html code of the admin page and it's ok. The existing Nginx is set up as in these digital ocean tutorials: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 I also secured it with Let's encrypt using this tutorial https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-18-04 -
Bring current user in logs inside Django
My goal in Django is to log every row with the current user so that when multiple users are using the app, I know which log is from whom. Step 1: I found that I can create filters for Logger: (like this) The problem that I have is that the record doesn't have a request inside. Step 2: I learn here, that I need middleware to store my current user so that logger could use it. My problem now is, that if I store in local, and then retrieve from local, apparently, this is not "same" local, so it doesn't have this information Middleware.py import threading local = threading.local() class UserNameMiddleware: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. setattr(local, 'my_user', 'Marko') print('set local Marko') response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response Filter.py import logging import threading local = threading.local() class UserFilter(logging.Filter): def filter(self, record): print('INSIDE') record.myusera = getattr(local, 'my_user', 'None') print(record.__dict__) return True Step 3: So, I was thinking to create a variable inside … -
custom primary email to login and secondary to disable to login in django
I am trying to make email management. Users can add a secondary email and make it primary for login and disable the previous email to login in to django. I build some models, forms, and views. Models.Py class Emails(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) email = models.EmailField() is_primary = models.BooleanField() *Forms.py class MultipleEmailForm(forms.ModelForm): class Meta: model = Emails fields = ('email', ) Views.py def addemail(request): form = MultipleEmailForm if form.is_valid(): user_emails = Emails.objects.filter(user=request.user).update(primary=False) primary_email = Emails.objects.get(pk=email_id, user=request.user) primary_email.primary = True primary_email.save() return render(request, 'account/addemail.html', context) -
Django Settings.py stuck on "SECURE_SSL_REDIRECT = True"
I added the setting SECURE_SSL_REDIRECT = True to my django settings.py. It works perfectly in production mode so no issues there however, now if I make it the following to test in development mode SECURE_SSL_REDIRECT = False I get the following error You're accessing the development server over HTTPS, but it only supports HTTP. What could the issue be? Seems like something is making it not register the new value. -
EmailMultiAlternatives not sending BCC emails
I have a Django management command defined like this: class Command(BaseCommand): help = "Sends out an email with new jobs added in a timespan of a week" def handle(self, *args, **options): time_a_week_ago = timezone.now() - timedelta(days=7) time_now = timezone.now() job_listings_added_this_week = JobListing.objects.filter(time_added__gte=time_a_week_ago, time_added__lt=time_now) email_subscribers = EmailSubscriber.objects.all() emails = [] for subscriber in email_subscribers: emails.append(subscriber.email) msg_plain = render_to_string("employers/weekly_newsletter.txt", {"joblistings_list": job_listings_added_this_week}) msg_html = render_to_string("employers/weekly_newsletter.html", {"joblistings_list": job_listings_added_this_week}) msg = EmailMultiAlternatives("New jobs added this week", msg_plain, "newsletter@myjobboard.com", [], bcc=[emails]) msg.attach_alternative(msg_html, "text/html") msg.send() self.stdout.write(self.style.SUCCESS("Successfuly sent out the weekly email.")) I set the email content to be output to a file. When I run the management command, this is is what I get: Content-Type: multipart/alternative; boundary="===============8145459042862347861==" MIME-Version: 1.0 Subject: New jobs added this week From: newsletter@myjobboard.com Date: Thu, 12 Nov 2020 05:23:05 -0000 Message-ID: <160512424922.55295.17004148678390675586@johns-computer.168.1.22> --===============8145459042862347861== Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Jobs added last week Hey! These job listings were added last week: Test job 5 - click here: http://127.0.0.1:8000/12/ Test job 6 - click here: http://127.0.0.1:8000/13/ --===============8145459042862347861== Content-Type: text/html; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit <h1> Jobs added last week </h1> <p> Hey! These job listings were added last week: </p> <ul> <li><a href="http://127.0.0.1:8000/12/">Test job 5</a></li> <li><a href="http://127.0.0.1:8000/13/">Test job 6</a></li> </ul> --===============8145459042862347861==-- ------------------------------------------------------------------------------- In … -
Why is the CharField related to Form not showing up?
I have created Comment Model for my Project but the CharField is not showing in the LocalHost for some reason. The submit button is working but there is no field to place text Here is the models.py class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) body = models.TextField(max_length=300) def __str__(self): return f"{self.post}-{self.user}-Comment No.{self.pk}" Here is the views: class Comment_create(CreateView): model = Comment fields = ['body'] template_name = 'blog/post_detail.html' form = CommentModelForm def form_valid(self, form): post = get_object_or_404(Post, slug=self.kwargs['slug']) form.instance.user = self.request.user form.instance.post = post return super().form_valid(form) def form_invalid(self, form): return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('blog:post-detail', kwargs=dict(slug=self.kwargs['slug'])) Here is the forms.py class CommentModelForm(forms.ModelForm): body = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder': 'Add a comment...'})) class Meta: model = Comment fields = ('body',) Here is the urls.py path('blogs/<slug:slug>/comment/', Comment_create.as_view(), name='comment-post'), Here is the template: <div class="container-fluid mt-2"> <div class="form-group row"> <form action="{% url 'blog:comment-post' post.slug %}" method="post" class="comment-form" action="."> {% csrf_token %} {{ form }} <input type="submit" value="Submit" class="btn btn-outline-success"> </form> </div> </div> -
CRUD IN THE SAME PAGE DJANGO
I am trying to do a CRUD using only one html page with django, but I have already encountered the first problem, when using nav-tabs I am not able to load the form when I click on the Create / Edit tab, maybe it has something to do with urls, but I don't know. index.html <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h2>Ordens de Serviço</h2> <ul class="nav nav-tabs"> <li class="active"><a data-toggle="tab" href="#list">Ordens de Serviço</a></li> <li><a data-toggle="tab" href="#create-update">Criar/Editar</a></li> <li><a data-toggle="tab" href="#detail">Ver</a></li> </ul> <div class="tab-content"> <div id="list" class="tab-pane fade in active"> <h3>Ordens de Serviço</h3> <table class="table"> <thead> <tr> <th>Nome</th> <th>TAG</th> <th>nivel</th> </tr> </thead> <tbody> {%for equipamento in equipamentos %} <tr> <td>{{equipamento.nome}}</td> <td>{{equipamento.tag}}</td> <td>{{equipamento.nivel}}</td> <td><a><button class="btn btn-primary">Editar</button></a></td> </tr> {%endfor%} </tbody> </table> </div> <div id="create-update" class="tab-pane fade"> <h3>Criar/Editar</h3> <form method="post"> {% csrf_token %} {{form}} </form> </div> <div id="detail" class="tab-pane fade"> <h3>Menu 2</h3> <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam.</p> </div> </div> </div> <script> </script> </body> </html> views.py: class ArvoreListView(ListView): queryset = Arvore.objects.all() template_name = 'example/index.html' context_object_name = 'equipamentos' class ArvoreCreateView(CreateView): form_class = ArvoreModelForm model = Arvore template_name = … -
Setting `CategoryInline.extra` at the class level is now deprecated. Set `CategoryInline.factory_kwargs` instead
I use django-extra-view on my project, i want to use CreateWithInlinesView and InlineFormSetFactory but i get this error Setting `CategoryInline.extra` at the class level is now deprecated. Set `CategoryInline.factory_kwargs` instead. This is my views.py class QuestionInline(InlineFormSetFactory): model = Question ordering = ("order", "category") extra = 1 class CategoryInline(InlineFormSetFactory): model = Category extra = 0 class SurveyCreate(CreateWithInlinesView): model = Survey fields = '__all__' list_display = ("name", "is_published") inlines = [CategoryInline, QuestionInline] and this is how i call it on page.html <form action="" method="post"> {% csrf_token %} <table> {% for formset in inlines %} {{ formset }} {% endfor %} </table> <div> <input class="btn btn-primary" type="submit" value="Submit"> </div> </form>