Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I solve this error with my reverse_lazy function?
I get the following error when using a CreateView: NoReverseMatch at /campus/NG Waverley Central/create Reverse for 'campus_page' with no arguments not found. 1 pattern(s) tried: ['campus/(?P[^/]+)/$'] I suspect is has something to do with the fact that I am passing campusid forward from my CampusPage view, and I do not know how to pass this campusid inside the reverse_lazy function. My urls.py looks as follows: urlpatterns = [ path('<str:campusid>/', views.CampusPage, name='campus_page'), path('login/', auth_views.LoginView.as_view(), name='login'), path('<str:campusid>/create', views.CreateStreamEvent.as_view(),name='create_streamevent'), ] My views.py looks as follows: def CampusPage(request, campusid): campusobj = CampusModel.objects.filter(campus_name=campusid) return render(request, 'campus/campus_page.html',{'campusid':campusid,'campusobj':campusobj}) class CreateStreamEvent(LoginRequiredMixin, CreateView): model = StreamEvent fields = ['title','campus'] template_name = 'campus/create_streamevent.html' success_url = reverse_lazy('campus_page') def form_valid(self, form): form.instance.user = self.request.user super(CreateStreamEvent, self).form_valid(form) return redirect('campus_page') I dont know if it is necessary, but my models.py looks as follows: class CampusModel(models.Model): campus_name = models.CharField(max_length=255, unique=True) description = models.TextField(blank=True,default='') banner = models.ImageField(upload_to=None, height_field=None, width_field=None, max_length=100,null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.campus_name class StreamEvent(models.Model): title = models.CharField(max_length=255) date_added = models.DateField(auto_now=False, auto_now_add=True) date_published = models.DateField(auto_now=True, auto_now_add=False) campus = models.ForeignKey(CampusModel, on_delete=models.CASCADE) def __str__(self): return self.title class Video(models.Model): title = models.CharField(max_length=255) url = models.URLField() youtube_id = models.CharField(max_length=255) streamevent = models.ForeignKey(StreamEvent, on_delete=models.CASCADE,null=True) def __str__(self): return self.title -
Django Rest Framework: setting `'Access-Control-Allow-Origin': '*'` in Response object doesn't do anything
I want only one route in my API to be accessible to all origins, so I've set Access-Control-Allow-Origin: * in the Response returned by the view: from rest_framework.views import APIView class ExampleView(APIView): def get(self, request): return Response("hi", headers={ 'Access-Control-Allow-Origin': '*', }) This works fine when I deploy my code to Heroku, but for some reason it does nothing when I run it locally. Requests just get blocked and I get a 403 forbidden response every time. Also I'm using django-cors-headers CORS_URLS_REGEX for every route that starts with /api/, this shouldn't have anything to do with the above, but mentioning just in case: CORS_URLS_REGEX = r'^/api/.*$' -
AttributeError at /account/delete/testuser1: 'str' object has no attribute 'field'
I am trying to allow users to delete their own account but am faced with the error: AttributeError at /account/delete/testuser1: 'str' object has no attribute 'field' The user is not deleted too. Any idea why? I am trying to make it such that the delete button is in the account page and when i press delete, the user gets deleted and redirected back to the home page Will be nice if you can share how i can create a function to deactivate an account too..is it simply setting is_active = False? html <form action="{% url 'account:delete_account' username=request.user.username %}" method="GET">{% csrf_token %} <a class="btn btn-danger btn-sm deleteaccount ml-3" href="{% url 'account:delete_account' username=request.user.username %}">Delete Account</a> </form> views.py def delete_user(request, username): context = {} if request.method == 'DELETE': try: user = User.objects.get(username=username) user.delete() context['msg'] = 'Bye Bye' except Exception as e: context['msg'] = 'Something went wrong!' else: context['msg'] = 'Request method should be "DELETE"!' return redirect(request, 'HomeFeed/snippets/home.html', context) urls.py path('delete/<username>', delete_user, name='delete_account'), models.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) -
django: image data not able to be save to db from form
I'm trying to fix this bug couple of days already. I extended User to have one more Image field, however, the image is not saving into the /media/profile path by itself. If I add an image from the admin panel the image will be shown in the front/user (profile image) as well it will be created into the wanted path /media/profile. I'm assuming my code is wrong where I'm creating user and additionally adding path since if I don't add the path it will look at the root media folder for the image. custom_user = Profile.objects.create(user = user, profile_image= 'profiles/'+today_path+'/'+profile_image) This is my first Django project its almost done, just this bug I'm not able to fix it. I will appreciate any help on how to fix it. Thank you, thank you, thank you! register form: <form action="{% url 'register' %}" method = 'POST'> {% csrf_token %} <div class="form-group"> <label class = 'fntmk color' for="first_name">Name</label> <input type="text" name="first_name" required> </div> <div class="form-group"> <label class = 'fntmk color' for="last_name">Surname</label> <input type="text" name="last_name" required> </div> <div class="form-group"> <label class = 'fntmk color' for="username">Username</label> <input type="text" name="username"required> </div> <div class="form-group"> <label class = 'fntmk color' for="email">Email</label> <input type="email" name="email" required> </div> <div class="form-group"> … -
Pug to django template engine Processor
I work with Django many days. I've been trying to learn node js and express. I introduced with pug. But pug has a many concept like indent have here any framework and library who like django template engine. Example: doctype html html(lang='en') head title Hello, World! body h1 Hello, World! div.remark p Pug rocks! -
pip command not found, virtualenv command not found on mac when installing django
Trying to learn python/django but cant even install django when i do virtualenv . or use the pip command, neither of them work on mac. python -V is 2.7.16, python3 -V is 3.8.2. pip command not found, virtualenv command not found on mac -
Multiple Django Dinja template
My view file context is return render(request, 'trail.html', {'form': form}) and My for loop on template is {% for fieldname in fieldset %}. I want to print form.fieldname. I used {{ form.fieldname }}, {{ form }}.{{fieldname}} and {{ form }}-{{fieldname}} nothing is printing the required field properly I am using {% for fieldname in fieldset%} {{form}}.{{fieldname}} {% endfor %} -
(Django) DataFieldTime always returns 00:00:00.000000
I'm trying to set a created_data and modify_data using datetimefield as follows: enter image description here but I added a value to the database, always return 00:00:00.000000 as follows: enter image description here Why is this? And I'd appreciate it if you could help me figure it out. I searched the web for an hour, but I couldn't find the answer... -
i have two models Chat and Message and how can i order the Chat with the pub_date of Message?
i have a chat and Message Model.How can i sort my Chat with the pub_date of Message example:consider that i am in two chats(A and B): i want that everytime i receive a message from B so that B should be the top of A and when i receive a message from A so that A should be the top of B. this is my models.py: from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django.utils.translation import ugettext_lazy as _ class Chat(models.Model): DIALOG = 'D' CHAT = 'C' CHAT_TYPE_CHOICES = ( (DIALOG, _('Dialog')), (CHAT, _('Chat')) ) type = models.CharField( _('type'), max_length=1, choices=CHAT_TYPE_CHOICES, default=DIALOG ) members = models.ManyToManyField(User, verbose_name=_("Participant")) def __str__(self): return 'members:[{}] - {}'.format(', '.join(self.members.all().values_list('username', flat=True)),self.type) class Meta: ordering = ['???? by pub_date of message ????'] class Message(models.Model): chat = models.ForeignKey(Chat, verbose_name=_("chat de discussion"),on_delete=models.CASCADE) author = models.ForeignKey(User, verbose_name=_("utilisateur"),on_delete=models.CASCADE) message = models.TextField(_("Message")) pub_date = models.DateTimeField(_('date de creation'), default=timezone.now) is_readed = models.BooleanField(_('Lu'), default=False) class Meta: ordering=['pub_date'] def __str__(self): return self.message how can i implement it.i have spent much time on this.Thanks. -
Django - Can I make choices hidden/invisible in my ChoiceField?
I have several choices from two categories in my ChoiceField - [Red, Green, Blue, 1, 2, 3] In my form I have two boxes with dropdowns. First allows you to select Category - Colors or Numbers. I have ajax call that when you select Colors in first box, second will reload to show only colors and vice versa. But in the first state (when you enter page) second dropdown let's you see all choices (both colors and numbers). I would like it to stay empty or with one temp choice for example - "Please select category first". I am wondering if I can hide them somehow with django or I need to create some kind of second ajax call that will execute each time while user reloads page? Thanks. -
Displaying Django model field in template
Sorry if this is duplicate, I've found a lot of scattered info on this, but not sure how to put this together. In my model I have: class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length=20) webbody = models.TextField() # models.FileField(upload_to='webcontent/projects') image = models.ImageField(upload_to='img/projects') def __str__(self): return self.title I can type HTML in webbody and display it in the template using admin no problem: {{project.webbody | safe}} But what I originally had was instead of a TextField, the commented line with filefield. I can upload the file through admin and that works nicely, but for the love of me I can't then display it in the template. I tried: {{project.webbody.url}} {% include project.webbody %} How does one properly handles external HTML files in django templates? -
Django problem with authenticated in html
why when I click on the link on the profile of another user, the option to log in is highlighted in the top menu, as if I had not authenticated (in the navbar it is possible to log in, the condition {% if user.is_authenticated%} is written there. If I open another page again everything is fine, the user is authenticated. navbar <div class=""> {% if user.is_authenticated %} <a class="navbar-brand" href="{% url 'account' %}"> <img src="{{user.profile.avatar.url}}" alt="" width="50" height="50" class="d-inline-block" /> </a> {% else %} <div class="signin"> <a href="{% url 'login' %}" type="button" class="btn btn-primary btn-rounded" > <div class="mx-auto">login</div> </a> <a href="{% url 'register' %}" type="button" class="btn btn-success btn-rounded" > <div class="mx-auto">register</div> </a> </div> vviews.py def list_users(request): users = Profile.objects.all() context = {'users':users} return render(request, 'profiles/list_users.html', context) def profile_detail(request, pk): user = Profile.objects.get(id=pk) context = {'user':user} return render(request, 'profiles/profile_detail.html', context) enter code here when going to this page, the user is not authenticated {% extends 'base/base.html' %} {% block content %} <div> <h1>HELLOOOO</h1> {{user.user}} </div> {% endblock %} url urlpatterns = [ path('', views.list_users, name='list_users'), path('account/', views.account, name='account'), path('profile_detail/<int:pk>/', views.profile_detail, name='profile_detail'), -
I keep getting this error in Django, its called "local variable referenced before assignment"
I am making this to-do list website with Django, but I keep getting this error in my "create" function in views.py file. here's the code : def create(response): if response.method == "POST": form = CreateNewList(response.POST) if form.is_valid(): n = form.cleaned_data["name"] t = ToDoList(name=n) t.save() return HttpResponseRedirect("/%i" %t.id) here's the error : local variable 't' referenced before assignment -
Is any solution in django to compare a foreign key column with primary key inside template, i need specific matchs in my project
My View.py it just render the objects thats fine. {% ifequal food_ing.f_name food.f_name %} {{ food_ing.f_name }} --> inside for loop i check this value, and it's (Pizza). {{ food.f_name }} -- this is also (Pizza) inside for loop in template, but i really don't know why condition equals to False... My file.html {% for food in foods %} {% for food_ing in food_ings %} **{% ifequal food_ing.f_name food.f_name %} <---> i need this statement to work** {% if food_ing.grm_amount == 0 %} <tr> <th>{{ food_ing.ing_name }}: &nbsp;&nbsp;</th><td class="text-muted font-weight-light">{{ food_ing.ltr_amount }} l</td> </tr> {% endif %} {% if food_ing.ltr_amount == 0 %} <tr> <th>{{ food_ing.ing_name }}: &nbsp;&nbsp;</th><td class="text-muted font-weight-light">{{ food_ing.grm_amount }} g</td> </tr> {% endif %} **{% endifequal %}** {% endfor %} {% endfor %} My models.py class IngFoodName(models.Model): ing_food_name = models.CharField(max_length=255, null=True) def __str__(self): return self.ing_food_name class Food(models.Model): f_photo = models.ImageField(upload_to='food_pics', blank=True) f_name = models.CharField(max_length=40, null=False) f_price = models.IntegerField(null=False) f_description = models.CharField(max_length=255, null=True) p_duration = models.IntegerField(null=False) def __str__(self): return self.f_name class FoodIngredients(models.Model): f_name = models.ForeignKey(Food, on_delete=models.CASCADE, null=True) ing_name = models.ForeignKey(IngFoodName,on_delete=models.CASCADE, null=True) ltr_amount = models.IntegerField(default=0, null=True) grm_amount = models.IntegerField(default=0, null=True) def __str__(self): return "Food {0} Ingredient {1} Litre Amount {2} Gram Amount {3}".format(self.f_name, self.ing_name, self.ltr_amount, self.grm_amount) Thanks, if anyone … -
Pass context to ModelSerializer field in Django Rest Framework
I am trying to pass a variable from my view to the serializer via context. The Serializer should be able to get the context variable and use it in a field that contains a nested serializer. Since the nested serializer field cannot be read_only, I cannot use serializerMethodField. This is how I pass the context to the serializer: class MyListCreateAPIView(generics.ListCreateAPIView): # [...] def get_serializer_context(self): return { 'request': self.request, 'format': self.format_kwarg, 'view': self, 'asTime': '2021-02-04 16:40:00', # <-- This is my context variable } This is my serializer: class MySerializer(serialisers.ModelSerializer): child = MyChildSerializer(read_only=False, asTime= ??) # <-- here I want to pass the context variable class Meta: model = MyModel fields = '__all__' I know that I can access the context variable with self.context.get('asTime') but I can't access self in MySerializer attributes (child). How do I do it? -
DoesNotExist: Category matching query does not exist
Why is my redirect not working. Everything works until the redirect statement I am receiving this error: DoesNotExist: Category matching query does not exist. The room url is made of 2 slugs. Type 1 slug is the slug from the category model and type 2 slug is from the room model. The same redirect statement was used for my delete message code and it worked. Not sure why this doesn't def edit_own_messsage(request, room_id): message = get_object_or_404(Message, id=room_id) if request.method == 'POST': form = UpdateMessageForm(request.POST or None, instance=message) if form.is_valid(): obj = form.save(commit=False) obj.save() return redirect(reverse("community:room", kwargs={'type1_slug': message.category.slug, 'type2_slug': message.room.slug })) models.py class Category(models.Model): categories = models.CharField(max_length=80, null=False, blank=False, unique=True) slug = models.SlugField(blank=True, unique=True) class Room(models.Model): categorical = models.ForeignKey(Category, related_name='categorical', on_delete=models.CASCADE) slug = models.SlugField(blank=True) class Message(models.Model): category = models.ForeignKey(Category, related_name='category', on_delete=models.CASCADE) room = models.ForeignKey(Room, related_name='messages', on_delete=models.CASCADE) name = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='naming', on_delete=models.CASCADE) urls.py path('<slug:type1_slug>/<slug:type2_slug>/', room_view , name= "room"), -
How can I delete multiple object in Django?
I’ve a list view, for show on the screen a list of object... In the view template, I created a table where I put a checkbox for each item... I would like to delete the selected objects, how can I do that? Thanks -
Djnago integration with built html template
I have built a complete front-end portfolio using HTML, CSS, and js. There is a a email contact form in the webpage and I want to send an email using Django through that contact form. when I tried to integrate it the index page is rendering but the CSS file is not accessible and all the design is disorganized. In this way my project files are organised This is the actual design But after rendering through Django it looks like this -
duplicate key value violates unique constraint "unique_followuser"
class FollowUserModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='followers') profile = models.ForeignKey(User,on_delete=models.CASCADE,related_name='following') timestamp = models.DateTimeField(auto_now_add=True) class Meta: constraints = [models.UniqueConstraint(fields=['author', 'profile'],name='unique_followuser')] What i want to do is basically i want an asymmetrical follow function. Like if: user1 follows user2, user2 should be able to follow user1 too. But the problem is that when user1 follows user2,user2 can't follow user1 asymmetrically because of unique constraint. Is there any solution for this? -
no module named "app" while trying to install a boilerplate Django
I'm trying to install a boilerplate in my personal computer but I'm getting this error: ModuleNotFoundError: No module named 'app' The boilerplate I'm trying to install is this one: https://github.com/jayfk/launchr The error happens specifically when I introduce this command: docker-compose run app python manage.py migrate -
Django multiple databases ... all models are created in second db despite router, is my router not good?
Django 2.2.18 I want to split the models of one app to a second database. The relevant app is named "dear_zoho_analytics", which I assume is the 'app_label'. The original database is "default". I have only one dbrouter, and it has code like this: class DbRouter(object): route_app_labels = ["dear_zoho_analytics", ] def db_for_read(self, model, **hints): . . . def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == "dear_analytics" return None when I do this: python3 ./manage.py migrate --database=dear_analytics I get the tables of every app created in the new database. python3 ./manage.py migrate dear_zoho_analytics --database=dear_analytics does what I want. However, this sort of implies that my allow migrate is not working because it appears to do nothing useful. -
Django Rest Framwork - Image Upload serializer not working but is valid and saving
I've tried everything but I cannot figure out why my images for an Avatar won't save to the media folder in Django. I am happy the front end is passing form data to the AvatarAPIView and I get the following when I print out the data being passed to the view. <QueryDict: {'myFile': [<InMemoryUploadedFile: 1965.jpg (image/jpeg)>]}> [07/Feb/2021 10:48:54] "PUT /api/profile/avatar/ HTTP/1.1" 200 31 view.py from profiles.api.serializers import (UserDisplaySerializer, SubscriptionSerializer, AvatarSerializer) from profiles.models import CustomUser from rest_framework import status, viewsets from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.generics import UpdateAPIView, GenericAPIView from rest_framework import mixins from rest_framework.parsers import MultiPartParser, FileUploadParser from django.http import HttpResponse class CurrentUserAPIView(APIView): def get(self, request): serializer = UserDisplaySerializer(request.user) return Response(serializer.data) def patch(self, request): serializer = UserDisplaySerializer(request.user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class UserUpdateAPIView(UpdateAPIView): queryset = CustomUser.objects.all() serializer_class = UserDisplaySerializer class AvatarAPIView(APIView): parser_class = (MultiPartParser) def get(self, request): serializer = AvatarSerializer(request.user) return Response(serializer.data) def put(self, request, *args, **kwargs): serializer = AvatarSerializer(request.user, data=request.data) print(request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer.py from rest_framework import serializers from profiles.models import CustomUser, Subscription class SubscriptionSerializer(serializers.ModelSerializer): class Meta: model = Subscription exclude = ('id', 'user', ) class UserDisplaySerializer(serializers.ModelSerializer): subscription = SubscriptionSerializer(read_only=True, many=False) class … -
Why there is wsgi in django admin
I cannot understand why there is a wsgi in Django admin: django.core.wsgi As far as I understand django cannot react on request directly, so wsgi works as an interface there. How can I see that it really works? When I am searching how to use nginx with django, I see all tutorials using nginx -> uwsgi -> django. But why not built-in Djangos wsgi? I actually managed to run nginx together with django without doing anything with uwsgi or wsgi, does it stil exist somewhere in between, how do i see it? I have wsgi.py file in django settings folder, but I think it is not called at any time: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.production') application = get_wsgi_application() Can someone please point me to the correct place where I can read it? My search did not help me.. -
How to display a status based on the model data
I need to indicate the level of the average of my data model. for example: I have a model. class Test(models.Model): level = models.CharField() lets say my level values are, apple dog cat if there are 20 apples over 30 entries. my html will display <h1>{{ critical }}</h1> else if there are 20 dogs over 30 entries, my html will display <h1>{{ light }}</h1> how can i do that? thanks! -
Python Crash Course, chapter 19, registration
I am a noob, currently on the chapter 19 of this book by No Starch Press. Try to build a registration option in my blog but sadly the version I have of the book is not updated on the latest version of Django. I already checked for support on other sites but I am really lost since all the info I get are related to different versions of Django . When I try to run the server I get an error about the line from django.contrib.auth.forms import UserCreationFormfrom django.shortcuts import render the function I wrote in the views section of the app is.. from django.shortcuts import render from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from django.contrib.auth import login from django.contrib.auth.forms import UserCreationFormfrom django.shortcuts import render from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect from django.contrib.auth import login from django.contrib.auth.forms import UserCreationForm def register(request): """Register a new user.""" if request.method != 'POST': # Display blank registration form. form = UserCreationForm() else: # Process completed form. form = UserCreationForm(data=request.POST) if form.is_valid(): new_user = form.save() # Log the user in and then redirect to home page. login(request, new_user) return redirect('learning_logs:index') # Display a blank or invalid form. context …