Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django file download doesn't initiate unless I click the request
I have a webapp that integrates with various systems and allows our access management team to run campaigns for reviewing employee access to the systems. I'm having some trouble with getting the results of the campaigns to download properly. I have the file being sent to the proxy and served to the end user upon hitting a button, but the download doesn't initiate unless I go to the developer console in Chrome and click the request manually. If I double click the highlighted request, it downloads the file but I want it to download automatically (most people won't know to go to the developer console) This is the code I use to generate the response: response = HttpResponse(bulk_update) response['Content-Type'] = 'text/csv' response['Content-Disposition'] = 'attachment; filename="{}"'.format(file) response['X-Accel-Redirect'] = f'/archive/{file}' return response I use Django and Nginx, any help on getting this to download automatically when the button is hit will be a great help. -
Infinite recursive redirects with nginx
I'm dockerizing a full stack for running offline. This stack consists of a Django API (backend), a set of static files built using React (frontend) and Nginx to serve both. Prevously, the frontend and the backend both had their own Nginx instance serving them, and it was working well. The backend was available at api.myhost.com and the frontend was available at myhost.com. However, now it makes more sense to serve the frontend at myhost.com/ and the backend at myhost.com/api/. Both the backend and the frontend have static files. Specifically, the backend has static files used in the Django admin site (not really important information). In order to accomplish this, I've tried a bunch of different Nginx configurations. Here's the most recent one: upstream django-channels { # FastCGI socket to API server rest-api:9000; } server { listen 80 default_server; listen [::]:80; server_name _; underscores_in_headers on; # This is the location of index.html. # STATIC FILES FOR THE BACKEND ARE LOCATED IN /home/docker/static/api/ root /home/docker/static/; # localhost/admin should redirect to localhost/api/admin/ # and get caught by the "~ ^/api/(.*)$" block below location = /admin { return 301 $scheme://$host:$server_port/api/admin/; } # localhost/admin/ should also redirect to localhost/api/admin/ # and get caught by the … -
TypeError: Field.__init__() got an unexpected keyword argument 'Label'
I am coding a blog for myself. I'm coding for a user to register an account, but I'm getting some errors as follows: File "C:\Users\hitechlab\Desktop\mysite\home\urls.py", line 18, in from . import views File "C:\Users\hitechlab\Desktop\mysite\home\views.py", line 4, in from .forms import RegistrationForm File "C:\Users\hitechlab\Desktop\mysite\home\forms.py", line 9, in class RegistrationForm(forms.Form): File "C:\Users\hitechlab\Desktop\mysite\home\forms.py", line 10, in RegistrationForm username = forms.CharField(Label='Tài Khoản', max_length=30) File "C:\Users\hitechlab\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\fields.py", line 267, in init super().init(**kwargs) TypeError: Field.init() got an unexpected keyword argument 'Label' -I can't find my error anywhere, hope someone can help. Here is my code urls.py from unicodedata import name from django.urls import path from blog.models import Post from . import views urlpatterns = [ path('', views.list, name = 'blog'), path('<int:id>/', views.post, name = 'post'), ] forms.py import email from tkinter import Label, Widget from django import forms import re from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist class RegistrationForm(forms.Form): username = forms.CharField(Label='Tài Khoản', max_length=30) email = forms.EmailField(Label='Email') password1=forms.CharField(Label= 'Mật Khẩu', Widget = forms.PasswordInput()) password2=forms.CharField(Label= 'Nhập lại mật khẩu', Widget = forms.PasswordInput()) def clean_password2(self): if 'password1' in self.cleaned_data: password1= self.cleaned_data ['password1'] password2= self.cleaned_data ['password2'] if password1==password2 and password1: return password2 raise forms.ValidationError('Mật khẩu không hợp lệ') def clean_username (self): username= self.clean_data['username'] if not re.search(r'^\w+$',username): raise forms.ValidationError("Tên tài … -
Django: The uploaded images are not Showing in template, says file not found
I am not able to get the image on my template from database. I had install pillow for supporting ImageField but its not working but It is successfully installed in my file proof.I am getting a broken image instead of uploaded image. Please help me out. note: I am not using virtual environment. Below are my codes. error: error pic image not found. Views.py def home(request): dr_data = dr_reg.objects.all() data ={ 'dr_data':dr_data } return render(request, 'home.html',data) models.py class dr_reg(models.Model): user = models.OneToOneField('User',on_delete=models.CASCADE, primary_key=True) fname = models.CharField(max_length=50,blank=False) lname = models.CharField(max_length=50,blank=False) image = models.ImageField() specialisation = models.CharField(max_length=100,blank=False) qualificaton = models.CharField(max_length=100,blank=False) phone = models.CharField(max_length=12,blank=False,unique=True) gender = models.CharField(max_length=7,blank=False) address = models.TextField(max_length=500,blank=False) state = models.CharField(max_length=50,blank=False) city = models.CharField(max_length=50,blank=False) zip = models.CharField(max_length=50,blank=False) email = models.EmailField(max_length=50,blank=False) dUsername = models.CharField(max_length=100,blank=False,unique=True) dPassword = models.CharField(max_length=100,blank=False) def __str__(self): return self.fname home.html {% extends 'base.html' %} {% load static %} <head> <link rel="stylesheet" href="{% static 'style1.css' %}" type="text/css"> {% block title %}Home{% endblock title %} </head> {% block body %} <div class="container"> <div class="row"> {% for n in dr_data %} <div class="col-md-4"> <div class="card mb-2"> {% if n.image %} <img src="{{ n.image.url }}" class="card-img-top" alt="img"> {% endif %} <div class="card-body"> <h5 class="card-title">{{ n.fname }} {{n.lname}}</h5> <p class="card-text">{{ n.gender }}</p> <p class="card-text">Qualificaton: {{n.qualificaton}}</p> … -
Incomplete response received from application in cpanel django application
I am trying to host a django website on the cpanel . I used to get the page response from the server but now I am getting this "Incomplete response received from application" . I cant even figure out how to know whats the error or what steps to follow to get the error so that I can solve it . I tried other methods like checking urls.py files but not able to figure out what is the error . If you want any specific part of code , I would be happy to post it here to solve the problem . -
Signals in django. Profile does not exist
For each user I create, I also create a profile with post_save signals. With that profile you can follow users using the many to many 'followers' field. When I press addfollower or removefollower I get an error that highlights : profile = Profile.objects.get(pk = pk) as the wrong line. As this error only occurs with the profiles that I create through signals, it seems to me that the problem is when I am creating the profile automatically. My signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from .models import Profile from django.dispatch import receiver @receiver (post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: profile = Profile.objects.create(user = instance) profile.followers.add('1') my methods: class AddFollower(ListView): def post(self, request, pk , *args, **kwargs ): print('usuario aaaaaaaaaaaaaaaaaagregado') profile = Profile.objects.get(pk = pk) profile.followers.add(self.request.user) return redirect('profile', username = profile.user.username) class RemoveFollower(ListView): def post(self, request, pk , *args, **kwargs ): print(f'reeeeeeeeeeeeeeeeeeeeeeeemovingFollower2{request.user}') profile = Profile.objects.get(pk = pk) profile.followers.remove(self.request.user) return redirect('profile', username = profile.user.username) my profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_img = models.ImageField(default='user.png') followers = models.ManyToManyField(User,blank=True, related_name='followers') def __str__(self): return f'{self.user.username} profile' -
How to avoid writing same code twice on a dynamic websocket site in django templates and javascript?
In a django project, templates are used on the backend which render html that is displayed on the page. But when dealing with Channels (websockets) which receive 'notifications' from the server, I find that I have to re-write code in javascript to render the same html elements. As an example, I started out with a HTML table element that in a django template page: {% for t in tickets %} <tr class="ticket-row"> <td>{{ t.id }}</td> <td> <a href="/tickets/{{ t.id }}"> {{ t.subject }} </a> </td> <td> <a href="/users/{{ t.user.id }}"> {{ t.user.name}} </a> </td> <td class="tooltipped" data-tooltip="{{ t.date_time_updated }}"> {{ t.date_time_updated|naturaltime }} </td> <td class="tooltipped" data-tooltip="{{ t.date_time_created }}"> {{ t.date_time_created|naturaltime }} </td> .... When channels receives a notification in javascript, I want to insert another row to the table without refresh, so I write JS code to do so like this: function insertTicketRow(ticket) { document.getElementById("results").innerHTML = "Server: " + data.subject; var table = document.getElementById('ticket_table'); var row = table.insertRow(1); // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element: var cellId = row.insertCell(0); var cellSubject = row.insertCell(1); var cellFrom = row.insertCell(2); cellId.innerHTML = data.id; cellSubject.innerHTML = linkElement("/tickets/" + data.id, data.subject); cellFrom.innerHTML = linkElement("/users/" + … -
Best approach(framework or library) to create live chat feature in django rest framework and React Project?
I am creating one project in which I want to create live chat section where our user can communicate with our agent through this feature.I am using React Js for frontend and django rest framework for backend, So I wanted suggestion what approach should I follow to achieve the same,through googling I found that Django channels are best option for chat feature in django, but I wanted more concise approach for the same I mean more suitable approach. -
How to check user type after login ? DJANGO
I have two user types in my application. How do I check user type after login? My login view extends django's LoginView. In my Login View, i tried with form_valid, but I think it does validation before authentication. models.py class CustomUser(AbstractUser): is_client = models.BooleanField(default=False) is_supermarket = models.BooleanField(default=False) def __str__(self): return self.username views.py class LoginView(LoginView): def get(self, request, *args, **kwargs): #check if the user is logged in and redirect to home page if request.user.is_authenticated: return redirect('produtos:home') return super(LoginView, self).get(request, *args, **kwargs) -
How to return user input using an api in Django views? i keep receiving an error 'WSGIRequest' object has no attribute 'request'
this is my code for views.py. I would like the user input to replace the value for the 'q' key in the querstring dict. def index(requests): return render(requests, 'index.html') def news(requests): if requests.method == 'POST': search = 'POST' url = "https://google-finance4.p.rapidapi.com/search/" querystring[0] = search querystring = {"q":"*airbnb*","hl":"en","gl":"US"} headers = { "X-RapidAPI-Key": "my api key", "X-RapidAPI-Host": "google-finance4.p.rapidapi.com" } response = requests.request("GET", url, headers=headers, params=querystring) print(response.text) return render(requests, 'news.html') else: return HttpResponse('Error') someapp/urls.py urlpatterns = [ path('', views.index, name ='home'), path('news/', views.news, name="news") ] mysite/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('search.urls')), path('news/', include('search.urls')) ] templates/index.html <form> class="form-inline" method="POST" action="{{ 'news/' }}" name="news" > <div class="input-group mb-3"> {%csrf_token%} <input type="text" class="form-control" placeholder="Enter Crypto" name="search" style="width: 50%; display: block; margin: 0 auto" /> <button class="btn btn-outline-primary btn-md" type="submit" id="button-addon2" > Search </button> templates/news.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Crypto Talk</title> </head> <body> <h1>{{news.views}}</h1> </body> </html> Am I formatting my syntax in the h1 element incorrectly, would this even tell Django to place the response I am looking for in this h1 tag? -
Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/blog/edit_post/post
I believe I have configure everything properly, but I can't seem to figure out what is causing the error message. What I'm trying to do is applying a view that allows me to edit a blog post. Error message: Using the URLconf defined in diyblog.urls, Django tried these URL patterns, in this order: admin/ blog/ [name='index'] blog/ blogs/ [name='all-posts'] blog/ <int:post_id> [name='post-details'] blog/ new_post/ [name='new-post'] blog/ edit_post/<int:post_id> [name='edit-post'] summernote/ ^media/(?P<path>.*)$ The current path, blog/edit_post/post, didn’t match any of these. View: def edit_post(request, post_id): post = Post.objects.get(id=post_id) edit_form = PostForm(instance=post) if request.method == 'POST': if edit_form.is_valid(): mod_post = edit_form.save(commit=False) mod_post.save() return redirect(get_all_posts) context_dict = { 'edit_form': edit_form } return render(request, 'blog/edit_post.html', context=context_dict) Form: class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'body',) exclude = ['author', ] widgets = { 'body': SummernoteWidget(), } url patterns: urlpatterns = [ path('', views.index, name='index'), path('blogs/', views.get_all_posts, name='all-posts'), path('<int:post_id>', views.get_post_details, name='post-details'), path('new_post/', views.add_new_post, name='new-post'), path('edit_post/<int:post_id>', views.edit_post, name='edit-post') ] Template: <h1>Edit Post</h1> <form action="post" method='post'> {% csrf_token %} {{ edit_form.as_p }} <button name="submit">Save changes</button> <form> Can anyone help me figure out why I'm receiving this error message and why it's happening? -
Django = display image on html from views with for loop
i am trying to display image from db with views and in the inspact broswer i see it find my image but still return me 404 error. my models.py: class HomePhoto(models.Model): title = models.CharField(max_length=100) img = models.ImageField(upload_to='home_page_images/') view.py: def index(request): data = HomePhoto.objects.all() return render(request, 'home.html',{'data':data,}) html: {% for d in data %} <img src="{{d.img}}" alt="Third slide"> {% endfor %} url.py: urlpatterns = [ path('',views.index,name='index') ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) the html in the broswer inspact: <img src="home_page_images/orangeshirt_1ZrO8ay.jpg" alt="Third slide"> <!--THIS IS THE RIGHT PATH AND THE RIGHT NAME OF THE IMAGE--> -
My HTML form isn't submitting input to Django database, each time I check my admin page it shows there an input but I wouldn't show what the input is
this is what it shows me each time I open my admin page to check the user inputs, it shows there's an input but not showing the input -
OperationalError at / no such table: users_user
I had a model Profile which was an extension to my User model which was the ForeignKey of my Post model, but I changed it to an AbstractUser and now if I try migrating or running and refreshing the page the server I get an error. models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): bio = models.TextField(max_length=500,null=True) from django.db import models from django.conf import settings from django.urls import reverse class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=100) content = models.TextField() def get_absolute_url(self): return reverse('post-details', kwargs={'pk': self.pk}) settings.py INSTALLED_APPS = [ ... 'posts', 'users', ] AUTH_USER_MODEL = 'users.User' error message after I try migrating Apply all migrations: admin, auth, contenttypes, posts, sessions, users Traceback (most recent call last): File "/home/user/Projects/DNF/Project/manage.py", line 22, in <module> main() File "/home/user/Projects/DNF/Project/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/dist-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/dist-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.10/dist-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.10/dist-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.10/dist-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/django/core/management/commands/migrate.py", line 295, in handle pre_migrate_apps = pre_migrate_state.apps File "/usr/local/lib/python3.10/dist-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.10/dist-packages/django/db/migrations/state.py", … -
How to exclude a field but save its data?
I creating an app to keep pets info. I'm displaying a form to insert data with a user profile. I don't want to display the parent option because that should be saved automatically but have no idea how to do that. If I exclude the parent, in the form doesn't appear but the pet's info is not linked to the user. Any help would be appreciated. class PetForm(ModelForm): class Meta: model = Pet exclude = ('parent',) class Pet(models.Model): pet_name = models.CharField(max_length=200) parent = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.pet_name -
Authentication in Django Custom Model
I have a model ApplicantRegister which has various fields.I want to register applicant after fill up the required information.After Registration and Mail Verification I want to logged in applicant through email and password.But I am getting Log in Details Wrong even though i submitted right information.Can't we use django built in authenticate in custom model ? models.py class ApplicantRegister(models.Model): applicant_name_in_english = models.CharField(max_length=50) applicant_name_in_bengali = models.CharField(max_length=50) father_name_in_english = models.CharField(max_length=50) father_name_in_bengali = models.CharField(max_length=50) mother_name_in_english = models.CharField(max_length=50) mother_name_in_bengali = models.CharField(max_length=50) marital_status = models.CharField(max_length=20) spouse_name_in_english = models.CharField(max_length=50, blank=True) spouse_name_in_bengali = models.CharField(max_length=50, blank=True) gender = models.CharField(max_length=10, choices=GENDER_CHOICES) present_address_in_english = models.TextField() present_address_in_bengali = models.TextField() permanent_address_in_english = models.TextField() permanent_address_in_bengali = models.TextField() religion = models.CharField(max_length=20) home_district = models.CharField(max_length=30, choices=DISTRICT_CHOICES) national_id = models.CharField(max_length=30) date_of_birth = models.DateField() phone = models.CharField(max_length=50) confirm_phone = models.CharField(max_length=50) email = models.EmailField(unique=True) confirm_email = models.EmailField() password = models.CharField(max_length=50) confirm_password = models.CharField(max_length=50) applicant_photo = models.ImageField(upload_to='applicantImages/', validators=[validate_file_size([200]), validate_file_extension, validate_image_dimension([300], [300])]) applicant_signature = \ models.ImageField(upload_to='applicantSignature/', validators=[validate_file_size([100]), validate_file_extension, validate_image_dimension([300], [80])]) reference_1 = models.TextField() reference_2 = models.TextField() is_active = models.BooleanField(default=False) def __str__(self): return self.applicant_name_in_english views.py def registerView(request): applicant_form = ApplicantRegisterModelForm() if request.method == 'POST': applicant_form = ApplicantRegisterModelForm(request.POST, request.FILES) if applicant_form.is_valid(): applicant = applicant_form.save(commit=False) applicant.is_active = False applicant.save() current_site_info = get_current_site(request) mail_subject = 'The Activation link has been sent to your email … -
How to filter/hide fields in django rest framework HTML form using authenticated user
I created two models: parcel (package) model, 'shelf' model to which parcels can be assigned. class Parcel(models.Model): owner = models.ForeignKey(get_user_model(), on_delete=models.PROTECT) name = models.CharField(max_length=100, blank=False) contents = models.TextField(blank=False, validators=[MaxLengthValidator(1500)]) size = models.CharField(max_length=50, blank=True, validators=[package_size_validator]) weight = models.PositiveIntegerField(blank=True, null=True) contact = models.CharField(max_length=50, blank=True) creation_date = models.DateTimeField(auto_now_add=True) last_modification = models.DateTimeField(auto_now=True) code = models.CharField(max_length=30, unique=True, blank=False) def __str__(self): return f'Parcel: {self.code}, {self.owner}, {self.name}' class ParcelShelf(models.Model): owner = models.ForeignKey(get_user_model(), on_delete=models.PROTECT) name = models.CharField(max_length=100, blank=False) creation_date = models.DateTimeField(auto_now_add=True) last_modification = models.DateTimeField(auto_now=True) parcels = models.ManyToManyField('Parcel', blank=True, related_name='shelf_parcel') def __str__(self): return f'ParcelShelf: {self.owner}, {self.name}' I came to a solution where the logged-in user can see only his packages and shelves. The problem I have is with the many-to-many relationship where parcels can be added to shelves. I want to come to a solution where the logged in user can add to the shelf only those parcels which he is the owner, creator. It will look better in pictures. All packages created by user t2@t2.com (user id = 17): parcels list Now the view when the user t2@t2.com wants to create a shelf: shelf list All packages are visible, while only those created by the user t2@t2.com should be available. Code to serializer: class ParcelShelfSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.email') … -
what's the url pattern for a url with query string parameters
What's the url pattern i should add to my urls.py that matches a url like this "http://127.0.0.1:8000/reservation/response/?type=43&content=test" -
'CategoryDocument' object has no attribute 'children' in Django elasticsearch
I setup everything for implementing elastic search in Django rest framework. I launched the elastic server using bat file and it runs successfully in the background. Then when I call the api , it throws me above error. class Category(models.Model): name = models.CharField(max_length=255) name = models.CharField(max_length=255) description = models.TextField(blank=True) status = models.BooleanField(default=True) My search.py class PaginatedElasticSearchAPIView(APIView, LimitOffsetPagination): serializer_class = None document_class = None @abc.abstractmethod def generate_q_expression(self, query): """This method should be overridden and return a Q() expression.""" def get(self, request, query): try: q = self.generate_q_expression(query) search = self.document_class.search().query(q) response = search.execute() print(f'Found {response.hits.total.value} hit(s) for query: "{query}"') results = self.paginate_queryset(response, request, view=self) serializer = self.serializer_class(results, many=True) return self.get_paginated_response(serializer.data) except Exception as e: return HttpResponse(e, status=500) class CategorySearchView(PaginatedElasticSearchAPIView): serializer_class = CategorySerializers document_class = CategoryDocument def generate_q_expression(self, query): return Q( "multi_match", query=query, fields=[ "name", ], fuzziness="auto", ) My serializers. py class CategorySerializer(serializers.ModelSerializer): class Meta: model = Subject fields = ["id", "name","description","status"] My documents.py: @registry.register_document class CategoryDocument(Document): # name = TextField() class Index: name = "category" settings = {"number_of_shards": 1, "number_of_replicas": 0} class Django: model = Category fields = [ "name","description" ] My urls.py : http://localhost:8000/elastic/search/Math/ I tried to call this api family but it shows the above error. Is this because I … -
Django 3.2.7 - Detect Currently Running Command From Code
TL;DR: Is it possible from within a django project to detect which command is currently running? DETAILS: We have a Django project (running 3.2.7) running which migrations are a little mixed up. There is a config model which has been developed way after the initial migrations has been done. This config model is basically a Django ORM model mapped to a DB object and has some caching features (which I will not go into details). The actual code running on servers never experience any problems, since config model is already provisioned on DB. But right now I'm trying to dockerize the whole project and I need to apply migrations from scratch. When I try to apply the migrations to a fresh db, It reads settings.py, which contains ROOT_URLCONF variable, that is being directed to another .py file this .py file contains urlpatterns list, which contains references to various django models Some of these models includes reference to the config model that I've mentioned earlier. When they are imported, those models are trying to pull configs from this config model, which is not initialized yet on the DB, causing psycopg2.errors.UndefinedTable: relation "core_config" does not exist error. Model is so deeply integrated … -
Django delete record using modal
I'm new in Django and i like to implement a Modal to delete records. The problem is a funny error in the modal form because is expecting a parameter. The modal link has this but I don't know how add the right parameter. This is my List in html <table id="tablaAlmacenes" class="table table-bordered table-striped"> <thead> <tr> <th>Almacén</th> <th>Detalles</th> <th></th> </tr> </thead> <tbody> {% for almacen in object_list %} <tr> <td>{{ almacen.almacen }}</td> <td>{{ almacen.descripcion }}</td> <td> <div> <a href="" class="btn btn-link text-info">Detalles</a> <a a href="" class="btn btn-link text-primary">Editar</a> <a class="btn btn-link deleteAlmacen" data-id="{{ almacen.id}}"><span class="fas fa-trash text-danger"></a> </div> </td> </tr> {% endfor %} </tbody> <tfoot> <tr> <th>Almacén</th> <th>Detalles</th> <th></th> </tr> </tfoot> </table> this is my url.py urlpatterns = [ path('',include('polls.urls'),name='home'), path('admin/', admin.site.urls), # path('contact/',views.contact, name='contacto') path('almacenes/', AlmacenesListView.as_view(), name='almacenes'), path('almacenes/nuevo', AlmacenesCreateView.as_view(), name='crear_almacen'), path('almacenes/<int:id>/remove/', AlmacenesDeleteView.as_view(), name='eliminar_almacen') ] This is my views.py class AlmacenesListView(ListView): model = Almacen template_name = 'pages/index.html' success_message = "Bien!!!!" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = "Lista de Almacenes" print(reverse_lazy('almacenes')) return context class AlmacenesCreateView(SuccessMessageMixin, CreateView): model = Almacen form_class = AlmacenesForm success_url = reverse_lazy('almacenes') success_message = "Bien!!!!" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context class AlmacenesDeleteView(DeleteView): model = Almacen success_url = reverse_lazy('almacenes') and my modal code <div … -
why new (custom) module in django app is not recognized?
I'm new to Django and I wanted to simply add some python files to one of my apps, in order to split code. If I create 'main.py' inside my app folder and import it from views.py (for istance) then I get: File "/home/francesco/django-projects/my-env/my-projects/my-app/views.py", line 3, in <module> import main ModuleNotFoundError: No module named 'main' I couldn't find anything online, I don't know if it can't be done (if so, is there a workaround?) or if I'm doing something wrong (if so, what's the correct way?). I'm using django 4.1 Thanks -
COPY failed: file not found in build context or excluded by .dockerignore: stat app: file does not exist
I am having an issue when I ran : sudo docker-compose up -d --build I am getting this error : Sending build context to Docker daemon 281.1MB Step 1/12 : FROM python:3.9.6-alpine ---> 0238e48b207f Step 2/12 : ENV PYTHONDONTWRITEBYTECODE 1 ---> Using cache ---> a03ccfedc62e Step 3/12 : ENV PYTHONUNBUFFERED 1 ---> Using cache ---> 77317bf71fab Step 4/12 : COPY ./requirements.txt /requirements.txt ---> Using cache ---> 4b6f8c9c33c8 Step 5/12 : RUN apk add libffi-dev ---> Using cache ---> 12e20c847c71 Step 6/12 : RUN apk add -u zlib-dev jpeg-dev gcc musl-dev ---> Using cache ---> 768f9b4c4f86 Step 7/12 : RUN python3 -m pip install --upgrade pip ---> Using cache ---> 41c9d9b5ebc9 Step 8/12 : COPY ./requirements.txt /usr/src/app ---> Using cache ---> fbb27974c713 Step 9/12 : RUN pip install -r requirements.txt ---> Using cache ---> 442d7cb81277 Step 10/12 : RUN mkdir /app ---> Using cache ---> 687beeed37e6 Step 11/12 : COPY ./app /app COPY failed: file not found in build context or excluded by .dockerignore: stat app: file does not exist ERROR: Service 'app' failed to build : Build failed (venv) idris@idris-G3-3579:~/Documents/workspace/moove$ Below is docker-compose.yml file : version: '3' services: app: build: context: . ports: - "8000:8000" volumes: - ./app:/app command: > … -
In template 'endblock'. Did you forget to register or load this tag?
I'm new to python and working and following a book tutorial, but I keep getting the same error. TemplateSyntaxError at / Invalid block tag on line 8: 'endblock'. Did you forget to register or load this tag? Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.0.7 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 8: 'endblock'. Did you forget to register or load this tag? Exception Location: /Users/dej/Desktop/code/news/.venv/lib/python3.10/site-packages/django/template/base.py, line 568, in invalid_block_tag Python Executable: /Users/dej/Desktop/code/news/.venv/bin/python Python Version: 3.10.6 Python Path: ['/Users/dej/Desktop/code/news', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python310.zip', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10', '/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/lib-dynload', '/Users/derrellj/Desktop/code/news/.venv/lib/python3.10/site-packages'] Server time: Tue, 30 Aug 2022 15:41:36 +0000 ################ here is my templates/home.html file.... {% extends "base.html" %} {% block title %}Home{% endblock title %} {% block content %} {% if user.is_authenticated %} Hi {{ user.username }}! <p><a href="{% url 'logout' %}">Log Out</a></p> {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">Log In</a> | <a href="{% url 'signup' %}">Sign Up</a> {% endif %} {% endblock content %} can anyone help me solve this problem -
Django setting debug=False breaks href links
I am developing a website using Django framework. It works perfectly well using Django=True, however when I set Django=False, system could not find the other html files which are being accessed in <a href=... links. Let say, I am developing 'mysite', then the following code: <li><a href="index-2.html"><i class="fab fa-dribbble"></i></a></li> is present behind an icon on mysite. Then clicking the icon takes the user to 'mysite.com/index-2.html', however it throws "The requested resource was not found on this server" error. And this happens only when we set Django=False and in production. No link on the homepage is working due to this.