Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django app works locally but not when deployed with Caddy
I am trying to get a chatbot running using a web interface with the help of Django. Locally this code works perfectly fine: app = Flask(__name__) app.static_folder = 'static' @app.route("/") def home(): return render_template("index.html") @app.route("/get") def get_bot_response(): userText = request.args.get('msg') return str(chatbot.get_response(userText)) if __name__ == "__main__": app.run() When I access localhost:5000 I can interact with the bot. However, when I deploy it on my university's virtual machine using the following caddyfile, the bot does not reply: *name of my virtual machine*.cs.ucl.ac.uk tls *my username*@ucl.ac.uk root *path to chatbot directory* proxy /chatbot localhost:5000 { transparent without /chatbot except /static } I know that the callback URL works because I have hosted chatbots on facebook before using the same flask framework and the same caddyfile (without "except /static"), with the help of Facebook's send/receive API. Any idea what I am doing wrong? I am a researcher with 0 experience in web development and will appreciate any help -
Django trigger an event on server stopped
I have a Django server (running on built-in server-container). Want to do something before app shutdown. Is there a way to trigger an event when server (or whole app) stopped/terminated. -
how to pass multiple context in django?
in line number 11 to 14 have two parameters why_choose_uss and Servicess i want to pass this two parameters in laxmi/index.html -
Data from views in Django is not showing in Django template
I was in middle of developing my E - commerce website using Django. Everything was working file unless I found a strange bug while Developing this website. So lets come to the Problem When I am trying to send a Dictionary to Django Template it is not showing the values in the Template I have Attached snapshot of my Code. Please tell me How to solve this bug Click Here to see my Python Code Click here to see the Django template code Click here to see the result that the Python code is working correctly but the Django template have a error ( I feels like this ) Please tell me where I am wrong -
How to create user with automatic default fields
I am not sure how to phrase this but I have the User from the user model given by django.contrib.auth.models I can register, login, and logout a user but now I would like to do a bit more. I want to have a wallet that the user is associated with upon registering. So far what I did was create a separate app called wallets and my model looks like... class Wallet(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) cash = models.FloatField(default=100, blank=True) The idea is that instead of extending my User model class to have another field being that I am using the existing User model already I am doing a OneToOneField(User) so that a user is associated with a wallet and that wallet containing the default amount of cash of 100 dollars When I create a user I want the wallet to be created and linked to that user as well. How do I do this? -
Is there any open source code available for a free lance platform in django?
I'm looking for a open code for a free lance platform in Django but so far I have not found anything. Are there any leads? -
how can i merge two forms fields in Django?
Is there a concept where two forms fields can be merged together? I want the output in a single {{ forms }}. i want to merge the ResultForm field(result_values) into LessonForm fields! please tell me if anybody know the concept? forms.py class LessonForm(forms.ModelForm): class Meta: model = Lesson fields = [ 'name', 'expected_values' ] class ResultsForm(forms.ModelForm): class Meta: model = Results fields = ['result_values'] -
django template comparing data from file executing wrong code path
I have a file /tmp/something.txt the contents of the file have the following is just simply a 1 In my view I have the following class StrippedView(AccessRequired, TemplateView): template_name = 'stripped' title = 'stripped' def get_context_data(self, **kwargs): with open('/tmp/something.txt','r') as file: data = file.read() context = super(stripped, self).get_context_data(**kwargs) context['title'] = self.title context['something'] = data return context And here is what I have in my template <tr> <th> Activate </th> {% if something == 1 %} <td> <a class="btn btn-warning btn-sm" href="{% url 'system:stripped' %}"><b>{% bootstrap_icon 'lock' %} Deactivate</b></a> </td> {% else %} <td> <a class="btn btn-primary btn-sm" href="{% url 'system:stripped' %}"><b>{% bootstrap_icon 'lock' %} Activate</b></a> </td> {% endif %} </tr> So here is what I expect to happen When the file has a 1 in it then the first button displays that says activate and if the file has anything else then it will display the Activate button What did happen Instead what is happening is it is always display the Activate button What have I tried At first I wanted to know what was actually being returned so I replaced the text of the activate button with the variable like so <a class="btn btn-primary btn-sm" href="{% url 'system:https' %}"><b>{% … -
Logging in a user Django REST
I am using Token Authentication, I want to add a Login and Logout Endpoint to my Api I am using Django REST My code: serializers.py #Login class UserLoginSerializer(serializers.Serializer): email = serializers.EmailField() password = serializers.CharField() def validate(self, data): email = data.get("email", "") password = data.get("password", "") if(email and password): user = authenticate(email= email, password= email) #If user credintials are correct if(user): if(user.is_active): data["user"] = user else: raise serializers.ValidationError("User Is Deactivated!") else: raise serializers.ValidationError("Unable To Login with given Email/Password!") else: raise serializers.ValidationError("Must Provide Email / Password!") return data views.py: #Login class UserLoginView(GenericAPIView): serializer_class = UserLoginSerializer def post(self, request): serializer = UserLoginSerializer(data= request.data) serializer.is_valid(raise_exception= True) user = serializer.validated_data["user"] login(request, user) token, created = Token.objects.get_or_create(user= user) return Response({"token": token.key}, status= status.HTTP_200_OK) My Question is: The problem that I am facing is whenever I login a user, I get the following message: "Unable To Login with given Email/Password!", Although the right credentials were provided. What might the problem be? Thanks. -
template code not working in different app template
I try to learn Django, I'm sure that my question is stupid but I think every beginner must pass this route to success, of course with the help of pro's. Also, I have a site with 2 app's, profiles and posts In this project I can see who I'm following in a list in template (posts/main.html) the problem is that I need the same list also in the other template (profiles/main.html). I have made a copy of the piece of code but it doesn't worked. I really don't know how to explain it better or I don't know how I can search it exactly. I tried this : 1.) How to use views in different apps templates 2.) How to import views from other apps views 3.) and a lot more, I read all the stuff but I couldn't find what I'm looking for Thanks a lot for your help. POSTS APP posts/models.py class Post(models.Model): ... author = models.ForeignKey(Profile, on_delete=models.CASCADE) text = models.TextField(default='no text...') ... def __str__(self): return str(self.text)[:30] posts/urls.py from django.urls import path from .views import posts_of_following_profiles, index, contact, about, category, PostListView, PostDetailView, post, detay from profiles.views import ProfileListView app_name="posts" urlpatterns = [ ... path('following/', ProfileListView.as_view(), name='posts-follow-view'), ... ] … -
Serialize Dictionary Object Where Keys Are Different
I have a dictionary object which has the days of the week as keys. Please can someone advise if there is a way to serialize this object using a Django Serializer. The example dictionary output looks like this: [{'mon': {'AM': False, 'PM': False}}, {'tue': {'AM': True, 'PM': False}}, {'wed': {'AM': False, 'PM': False}}, {'thu': {'AM': True, 'PM': True}}, {'fri': {'AM': False, 'PM': True}}, {'sat': {'AM': False, 'PM': False}}, {'sun': {'AM': False, 'PM': False}}] The closest I can get is having serializer method fields for each day of the week, but that returns null for every weekday which is not part of the set. I have tried: class SlotSerializer(serializers.Serializer): AM = serializers.BooleanField() PM = serializers.BooleanField() class SchoolSlotSerializer(serializers.Serializer): mon = serializers.SerializerMethodField(required=False) def get_mon(self,obj): if obj.get('mon'): return SlotSerializer(obj['mon']).data #Repeated for each weekday -
Why does my form error not show up in the template?
I have a user login form class PersonLoginForm(forms.Form): username = forms.CharField(max_length=20, required=True) password = forms.CharField(max_length=100, required=True) def clean_password(self): user = Person.objects.get(username=self.cleaned_data['username']) if not user.check_password(self.cleaned_data['password']): self.add_error('password', 'That password is incorrect!') return self.cleaned_data In there I check if the password is correct so that I can let an error message appear in the template I access the error message in my template like so <div class="field-wrapper"> {% render_field form.password.errors %} {% render_field form.password.label_tag %} {% render_field form.password placeholder='password...' type='password'%} </div> but The error message does not show up! This is the view for the login form def user_login(request): if request.method == 'POST': form = PersonLoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.success(request, 'Successfully logged in!') return redirect('all_users') print(form.errors) form = PersonLoginForm() context = { 'form': form, 'title': 'Login', } return render(request, 'index/login.html', context) I print it after form.is_valid() evaluates to False <ul class="errorlist"><li>password<ul class="errorlist"><li>That password is incorrect!</li></ul></li></ul> It doesn't even show up in the template -
How can I use Django DeleteView in my template
I am using Django DeleteView in a template and I've created a url & view. But it shows "Generic detail view EmployeeDeleteView must be called with either an object pk or a slug in the URLconf." I was looking on django docs, and looks like that DeleteViews are coupled with the models. How can I use Django DeleteView here. If any one help me please. views.py class EmployeeDeleteView(DeleteView): model = Employee success_url = 'create_employee' def get(self, request, *args, **kwargs): return self.post(request, *args, **kwargs) urls.py path('delete_employee/<int:id>', EmployeeDeleteView.as_view(), name='delete_employee'), Delete Button <button class="deletebtn show-form-delete" type="submit"> <i class="fa fa-trash-o"></i>&nbsp;<a onclick="return confirm('Are you sure do you want to delete {{i.name}}')" href="{% url 'delete_employee' i.id %}">Delete</a></button> -
How to set up SASS to work with Django and AWS S3
I'm trying to set up my Django project to use SASS, unsuccessfully so far. I've installed libsass, django-compressor, and django-sass-processor. My settings.py includes these lines: INSTALLED_APPS = [ 'sass_processor', .... [my other apps here] ] STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'sass_processor.finders.CssFinder', ] SASS_PROCESSOR_ROOT = os.path.join(PROJECT_ROOT, 'static/css') AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = 'myproj-debug' if IS_DEBUG else 'myproj' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_DEFAULT_ACL = 'public-read' AWS_LOCATION = 'static' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'myproj.storage_backends.MediaStorage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) My base.html includes these lines: {% load sass_tags %} <link href="{% sass_src 'app.scss' %}" rel="stylesheet" type="text/css"> When I run my debug Django server with ./manage.py run server, the processor seems to find my app.scss file okay, because when I move it to a different location I get an error. But where is the compiled app.css file being placed? I see in my page source that the {% sass_src line becomes <link href="https://myproj-debug.s3.amazonaws.com/static/app.css" rel="stylesheet" type="text/css"> but no file shows up there. (I'd actually like to have it placed at https://myproj-debug.s3.amazonaws.com/static/css/app.css but that's another matter.) How do I get app.css to compile and show up in my AWS S3 bucket like it should? -
Django queryset order by latest value in related field
Consider the following Models in Django: class Item(models.Model): name = models.CharField(max_length = 100) class Item_Price(models.Model): created_on = models.DateTimeField(default = timezone.now) item = models.ForeignKey('Item', related_name = 'prices') price = models.DecimalField(decimal_places = 2, max_digits = 15) The price of an item can vary throughout time so I want to keep a price history. My goal is to have a single query using the Django ORM to get a list of Items with their latest prices and sort the results by this price in ascending order. What would be the best way to achieve this? -
ERROR 404 after submitting a form with POST request
http://127.0.0.1:8000/tasks works fine but when when I add a task and submit it, I get a 404 thrown at me, ERROR: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ polls/ newyear/ tasks/ [name='index'] tasks/ add [name='add'] The current path, tasks/{ % url 'add' % }, didn't match any of these mysite\tasks\urls.py from django.urls import path,include from . import views urlpatterns = [ path("", views.index, name='index'), path("add", views.add, name='add')] mysite\mysite\urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('polls/',include('polls.urls')), path('newyear/', include('newyear.urls')), path('tasks/', include('tasks.urls'))] mysite\tasks\views.py from django.shortcuts import render tasks = ["foo", "bar", "baz"] def index(request): return render(request, "tasks/index.html", { "tasks": tasks }) def add(request): return render(request, "tasks/add.html") ) mysite\tasks\templates\tasks\index.html {% extends "tasks/layout.html" %} {% block body %} <h1> Tasks </h1> <ul> {%for task in tasks%} <li> {{task}}</li> {%endfor%} </ul> <a href="{% url 'add' %}">Add a New Task</a> {% endblock %} mysite\tasks\templates\tasks\add.html {% extends "tasks/layout.html" %} {% block body %} <h1> Add Task </h1> <form action= "{ % url 'add' % }" method="post"> <input type="text" name="task"> <input type="submit"> </form> <a href= "{% url 'index' %}">View Tasks</a> {% endblock %} -
How to register several models in one admin page?
I need an admin page which will contain several model lists. Each model has own register and settings so I need to use this admin classes to group them in one page. To be clear, example: models.py class Student(models.Model): name = models.CharField(max_length=60) age = models.PositiveSmallIntegerField() class Teacher(models.Model): name = models.CharField(max_length=60) subject = models.CharField(max_length=60) admin.py @admin.register(models.Student) class StudentAdmin(admin.ModelAdmin): # settings @admin.register(models.Teacher) class TeacherAdmin(admin.ModelAdmin): # settings # need them together like this: class TwoModelsAdmin(admin.ModelAdminGroup) admin_panels = (StudentAdmin, TeacherAdmin,) Is there any way to do that? -
Nested models in django
I have an django app with a model called Folder, user can create a Folder with a name field. what i want is to make this Folder model nested, so that user will be able to create Folders inside a folder. For example user created a folder called ABC and got inside the DetailView of that folder and created another folder DEF and then got into DEF and created another folder called GHI and so on. I am pretty new to django, i tied searching the web but got nothing. models.py from django.db import models from django.contrib.auth.models import User from django.db.models.deletion import CASCADE from django.core.validators import MinValueValidator from django.core.exceptions import PermissionDenied # The Folders Model. class Folder(models.Model): name = models.CharField(max_length = 250) cr_date = models.DateTimeField(auto_now_add = True) def __str__(self): return "%s" % self.name views.py import requests from django.shortcuts import render from django.views.generic.base import TemplateView from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required from django.views.generic.list import ListView from ahmed_drive.models import Folder from . import models from django.views.generic.detail import DetailView from django.db.models import Q from django.views.generic.edit import UpdateView, CreateView, DeleteView from django.http.response import HttpResponseRedirect #### Normal Pages Related Views #### class HomeView(TemplateView): template_name = "ahmed_drive/home.html" #### Pages Related Folder Model #### @method_decorator(login_required, … -
Django static files 404 using nginx
I'm aware this has been asked a few others times, but none of those solutions seem to be working for me. This was my first time deploying a Django project, so for reference, I followed this tutorial: https://linuxhint.com/create_django_app_ubuntu/ For that reason, it is entirely possible that something flew over my head completely. nginx config (I've tried alias instead of root, with and without trailing slash, made sure the static file aren't owned by root, etc.): upstream django { server 127.0.0.1:8000; } server { listen 80; location /static/ { root /home/bryan/Projects/portfolio; try_files $uri =404; } location / { try_files $uri @send_to_django; } location @send_to_django { proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://django; } } settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) Note: django.contrib.staticfiles is installed python manage.py collectstatic appears to be working I do believe I am referencing the static files correctly in my templates: {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'home/css/index.css' %}"> My file structure: portfolio (django project root) home (django app) static (project static files) home (static files for home app) css Other than the static files, the site works flawlessly with this setup. -
Comments input form (HTML, DJANGO)
Help me how to display the form for entering comments under the article, so that the form is under the article on the barbers.html page. When I write the form in barbers.html it is not displayed. I think everything else is correct, but just in case I also publish urls.py urlpatterns = [ path('',views.HomePage.as_view(),name='index'), path('barbers/',views.BarbersPage.as_view(), name='barbers'), path('post_detail/<int:post_id>/', views.post_new, name='post_detail'), ] views.py class BarbersPage(ListView): model = Post template_name = 'main/barbers.html' context_object_name = 'posts' def post_new(request, post_id): post = get_object_or_404(Post, pk=post_id) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('barbers') else: form = CommentForm() return render(request, 'main/post_detail.html', {'form': form}) forms.py class CommentForm(ModelForm): class Meta: model = Comment fields = ('name', 'body') models.py class Post(models.Model): photo = models.ImageField(upload_to='media/photos/',null=True, blank=True) name_barber = models.CharField(max_length=30, null=True, blank=True) description = models.TextField(blank=True, null=True) def __str__(self): return self.description[:10] class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=30) body = models.TextField(null=True) add_date = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post, self.name) post_detail.html <h1>New comment</h1> <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> barbers.html {% for post in posts %} <img src="{{MEDIA_URL}}{{post.photo.url}}" width="800" /> <h3> {{ post.name_barber}} </h3> <p>{{ post.description}}</p> <h3> … -
How can I do a dynamic url that doesn't raise a 404 error if I click twice on the navbar the same button?
I am currently working on my first web design and I'm experiencing some trouble with my url. What I'm trying to do is a navbar that when you click on the button, redirects you to a page. However, if I click twice on the navbar button, it raises a problem because the program is still reading the other url. Here's some photos so you can understand. [When I click on the translator button, the url adds translator. Now If I click another time in the translator button, it raises a 404 error. Now If I click on the home button, I still have the translator/ in the url, so it raises another 404 error. My question is, how can I do a dynamic url so that when I click on another button, it doesn't appear a 404 error and redirects me to that page. Here's the code of the navbar <nav class="navbar fixed-top navbar-expand-lg navbar-light" style='background-color: snow;'> <div class = 'container'> <a class="navbar-brand" href="#"> <img src="{% static ''%}" width="70" height="30" class="d-inline-block align-top" alt=""> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarTogglerDemo01"> <ul class="navbar-nav mx-auto"> <li class="nav-item active"> <a class="nav-link" href='home'>Home <span … -
How do I get pagination to work with django_filters to work in Django 3?
In my html, I can either do {% for i in filter.qs %}, which has my sorted model or {% for i in page_obj %}, which has my paginated model. Is there a way to paginate the sorted model? -
Django signals for Comment notification
I am working on django project and I have written a post_save signal to notify post author when commented. Now, I want to add a post_save signal to notify post author/ comment user that a comment (reply) is made. Below are my model and signal code. Can someone assist please? I am new on django and have just started learning django signals. class Comment(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE) post = models.ForeignKey('forum.Post',related_name='comments', on_delete=models.CASCADE) reply = models.ForeignKey('self', null=True, blank=True, related_name='replies', on_delete=models.CASCADE) text = models.TextField(max_length=250, blank=True) @receiver(post_save, sender=Comment) def user_comment_post(sender, instance, created, **kwargs): if created: comment = instance post = comment.post #reply = comment.reply text_preview = comment.text[:90] sender = comment.user notify = Notification.objects.create(post=post, sender=sender, comment=comment, user=post.author, text_preview=text_preview, notification_type=2) notify.save() -
api jsonresponse containing multiple fields from multiple tables
I need to create an api which will contain data from below two models. class User(models.Model): u_id = models.CharField(max_length=9,default=None,unique=True) real_name = models.CharField(max_length=200) tz = models.CharField(max_length=200) def __str__(self): return self.u_id class Activity(models.Model): u_id = models.CharField(max_length=9,default=None) start_time = models.DateTimeField() end_time = models.DateTimeField() def __float__(self): return self.start_time User class contains user detail and it's user id is unique. Activity class can contain multiple start and end time for same user id. We need an api which will contain multiple start and end time entries for the same user. I tried querying both models into one querylist and passing that as jsonresponse but it doesnt work. views.py def user_activity(): base_url_user = 'http://127.0.0.1:8000/users/' base_url_activity = 'http://127.0.0.1:8000/activity/' res_user = requests.get(base_url_user).json() res_activity = requests.get(base_url_activity).json() u = {} a = {} for i in range(len(res_user)): u[i + 1] = res_user[i] for i in range(len(res_activity)): a[i + 1] = res_activity[i] for u[i]["u_id"] in a[i]: querylist = [ {'queryset': User.objects.all()}, {'queryset': Activity.objects.all()} ] return JsonResponse(querylist) serializers.py from rest_framework import serializers from .models import * class Userserializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class Activityserializer(serializers.ModelSerializer): class Meta: model = Activity fields = '__all__' urls.py from django.urls import include, path from rest_framework import routers from . import views router = … -
Django Form Update Failing with a NULL not allowed
I have a customer instance that I am trying to update only a FEW fields in using a form, as the rest is 'behind the scenes' info. I am receiving this error: Cannot insert the value NULL into column 'iddef_cst', table 'EasyTrade20.dbo.app_customer_cst'; column does not allow nulls. UPDATE fails Even though that record was already populated and already has that value included. views.py: def edit_customer(request, id): customer_obj = get_object_or_404(AppCustomerCst, id_cst=id) form = CustomerMaintForm(request.POST, instance=customer_obj) if form.is_valid: form.save() forms.py class CustomerForm(forms.ModelForm): class Meta: model = AppCustomerCst fields = ('id_cst', 'is_active_cst', 'name_cst', 'address_1_cst', 'address_2_cst', 'address_3_cst', 'city_cst', 'state_cst', 'zip_cst', 'country_cst', 'salesrep_cst', 'type_cst', 'is_allowed_flat_cst', 'balance_notify_cst', 'receive_emails_cst', 'contact_domain_cst' I have tried to create an instance of the form with form.save(commit=False) and use the fields from customer_obj to pass the current values to the form for update, but it seems the final form.save() creates a new object. Is there any clean way to use a ModelForm to update only a handful of fields in a model instance?