Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot access staticfiles using Pycharm Community Edition
I am using Pycharm Community Edition and I am new to this and Django as well. I am trying to fetch the background image for my webpage using a CSS file. This is the html file for that specific webpage. <!-- load the path to your static file--> {% load static %} <link rel="stylesheet" type="text/css" href="{% static '/music/style.css}"/> {% if all_albums %} <h3>Here are all my albums:</h3> <ul> {% for album in all_albums %} <li><a href="{% url 'music:detail' album.id %}">{{ album.album_title }}</a></li> {% endfor %} </ul> {% else %} <h3>You don't have any albums</h3> {% endif %} Here is the CSS file: body{ backgroud : white url("images/background.jpg"); } I have also changed the settings file like this: import os STATIC_URL = 'static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, "static/"),) You can see my project tree as under for more clarification: There are two errors that I am getting whenever I am refreshing the page: Please help me out! Is this because of COMMUNITY EDITION? -
Django notification for new chat message using ajax
I have used this code to send messages for my chat app, but when I add notifications it doesn't work. help me please Note: i use django-notifications-hq def send(request): if request.user.is_anonymous or request.user.is_active == False: return redirect('/accounts/login') if request.method == 'POST': sender = request.POST.get("username") receiver = request.POST.get("friend") message = request.POST.get("message") message = message.strip() if (message == "") or (request.user.username != sender): return redirect('/room/'+receiver) if sender == receiver: return redirect('/') newmessage = Message(sender=sender, receiver=receiver, message=message) newmessage.save() if newmessage.save(): sender = request.POST.get("username") receiver = request.POST.get("friend") message = request.POST.get("message") notify.send(sender, recipient=receiver, verb='Message', description=message, level='light') return HttpResponse("message sent") return redirect('/') -
Not able to change account details and not sending email once edited - Django
So... My main intention is that when a user edits his/her account and changes the email, the system has to change all the other info except email and send an email to the new email (inputted by the user) with a confirmation link. And once clicked, the system has to redirect the user to another page and change the email for that account. My code was changing all the information (without sending emails) before I added all the email thingy. After I add it, it doesn't change the other details from the account or send a confirmation email. view (I know there is some incomplete code which I need to add): class NormalUserEditView(generic.UpdateView): form_class = EditProfileFormNormal template_name = 'authentication/edit_normalprofile.html' success_url = reverse_lazy('profile') def form_valid(self, form): me = self.request.user.id myuser = User.objects.get(email=self.request.POST['email']) if myuser.email == myuser.email: return redirect('profile') else: current_site = get_current_site(self.request) email_subject = "Email has been changed for", myuser, " - some website" email_message = render_to_string('authentication/email_confirmation.html', { 'name': myuser.first_name, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(myuser.pk)), 'token': generate_token.make_token(myuser), }) email = EmailMessage( email_subject, email_message, settings.EMAIL_HOST_USER, [myuser.email], ) email.fail_silently=True email.send() messages.success(self.request, f'Account Edit: Successful') return super().form_valid(form) def get_object(self): return self.request.user -
For Loop in Django Template
I am working on a Django project. It has two Apps, one for explaining the topic, which has its own model, and views, and the second app is a quiz app, which has its own model and view, which will test the ability / learning of the students on each topics. The main idea is that for each topic of each book, there will be a quiz to test the ability of the students. my book explanation model is as follows: class book_explination(models.Model): title = models.CharField (max_length = 255) slug = models.SlugField(max_length= 250, null = True, blank = True, unique= True) lesson_no = models.CharField (max_length = 255) book_text = models.TextField (blank=False, null=False) book_text_explination = models.TextField (blank=False, null=False) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, null= True, blank=True) timestamp = models.DateField(auto_now=False, auto_now_add=True) def __str__(self): return self.title my view for the course model is as follows: def maths_topics(request): content_list = book_explination.objects.filter(title = "maths") return render(request, 'blog/maths_topics.html', {'content_list': content_list}) my url on url.py file is as under: path('nahwa_meer_topics/', maths_topics, name = 'maths_topics'), my quiz model is as follows: class Quiz(models.Model): title = models.CharField(max_length=255) book_name = models.CharField(max_length=255) slug = models.SlugField(blank = True) topic = models.CharField(max_length=255) number_of_questions = models.IntegerField() class Meta: verbose_name_plural = 'Quizes' def __str__(self): return self.title … -
Django instance in model form
There was a problem, I wanted to make an Django user object creation form, but it doesn't work. Exactly the same view with a different model works fine. I think the problem is how I transmit the data and instance in form. views: @login_required(login_url='login') def CreateRoom(request, pk): topic = Topic.objects.get(id=pk) form = RoomForm(data=request.POST, instance=room) if request.method == 'POST': if form.is_valid(): room = form.save(commit=False) room.host=request.user room.topic=topic room.save() return redirect('home') context = {'form': form, 'topic': topic} return render(request, 'room_form.html', context) forms: class RoomForm(ModelForm): def __init__(self, *args, **kwargs): super(RoomForm, self).__init__(*args, **kwargs) self.fields['themes'].queryset = self.instance.themes.all() class Meta: model = Room fields = '__all__' exclude = ['topic', 'host', 'participants'] -
reverse() doesn't resolve in django-rest-framework
django-rest-framework question: TLDR: reverse() doesn't work when everything I'm being told says it should. OK, Longer version: I have a route that works when I navigate to it. "/api/tag/" I have the route set where all my api routes are set router.register("tag", TagViewSet, basename="tag") TagViewSet is based off a ModelViewSet. If I comment this line out /api/tag/ doesn't work in the browser (so it's the authoritative place). The questions comes when I replace "/api/tag/" in my tests to reverse('tag-list') or reverse('tag:tag-list'). Neither resolves. When I put in (using debug mode) http://localhost:port/api/sldkfjalsdjfalskdjflaksj I get a list of things that resolve which has the line api/ ^tag/$ [name='tag-list'] So I'm wondering what else I can check for to make this reverse() or reverse_lazy() to work. -
How to save uploads models data to the user that is logged in, DjangoRestFramework
I want to post data {photos and caption} and I want it to save to the user that is logged in. I get this error 'Got a TypeError when calling Uploads.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to Uploads.objects.create(). You may need to make the field read-only, or override the UploadsSerializer.create() method to handle this correctly.' In serializer.save() I put user = request.user as the argument, but that just gives me the error mentioned above. Putting that argument worked in other projects, but is giving me trouble, and I don't understand why even with the error. Serializer.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'username', ] class ProfileSerializer(serializers.ModelSerializer): user = models.OneToOneField(User, on_delete = models.CASCADE, null = False, blank = True) class Meta: model = Profile fields = [ 'first_name', 'last_name', 'phone_number', 'bio', 'profile_picture', 'banner_picture' ] def to_representation(self, instance): my_fields = {'first_name', 'last_name', 'bio'} data = super().to_representation(instance) for field in my_fields: try: if not data[field]: data[field] = "" except KeyError: pass return data class UploadsSerializer(serializers.ModelSerializer): caption = serializers.CharField() file = serializers.URLField() id = serializers.IntegerField(read_only = True) class Meta: model = Uploads fields = ['id', 'file', … -
Switching between django development environment and production environment settings
I have a django project with different environments for production and development. The production environment runs on Postgresql while the development environment runs on sqlite3. I deployed on railway.app with all the necessary variables set. After installing railway cli and connecting my project, it's now running on production settings. Now I want to switch back to use development settings but it continues using production settings. I tried to unlink the project, then logout. Yet it's not working. -
I want to make a python web application live. But it shows
[1]It showed me. What's the solution? Please give me a solution -
How to use Django-simple-captcha on the admin login page?
I would like to add captcha on my django login form using Django Simple Captcha found here: http://code.google.com/p/django-simple-captcha/ This works great if you create a new form but I'm using the django.contrib.auth.forms the one that comes with django. Any idea how I might be able to implement captcha with the existing django auth views? Thank you! Please do not suggest using Google reCaptcha. My urls.py from django.contrib.auth import views as auth_views urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login') ,... ] My login.html <form class="fadeIn second" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary"> Login </button> </form> My Forms.py from captcha.fields import CaptchaField class MyFormCaptcha(forms.Form): captcha = CaptchaField() -
Why all the tags not displaying in home.html page?
So here's the problem, I'm trying to display all the tags on the homepage in a dropdown menu but the tags are not being called in base.html. But when I open the specific post itself, the Dropdown menu displays the tags used in that post. Why is that? Can't the tags used in each post be passed on to all pages? Btw I'm using Django-taggit for it. My views.py goes like this: def home(request, tag_slug=None): posts = Post.objects.all() # tag post tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) posts = posts.filter(tags__in=[tag]) context={ 'posts': posts, #introduces the content added in Post Class 'tag':tag, } return render(request, 'blog/home.html', context) And my urls.py goes like this: urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('tag/<slug:tag_slug>/',views.home, name='post_tag'), ] My base.html goes like this: <li class="list-group-item list-group-item-light" style="text-align:center"> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Tags </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for tag in post.tags.all %} <a class="dropdown-item" href="{% url 'post_tag' tag.slug %}">{{tag.name}}</a> {% endfor %} </div> </div> </li> -
How to add margin in forms in django admin panel
Is there any way to add margin between forms in django admin panel, because my admin panel looks so cramped without any margin i can control -
Attribute Error: Object has no Attributes while trying to update the manytoo
Attribute Error: Object has no Attributes "avg_rating" Errors occurs while trying to update the ManytooOne Field in views.py perform_create func. Imm trying to update a avg_rating which is instance of Review model, Every time an a comment is received. my review is related to watchlist through foreign key. Here's my models.py class WatchList(models.Model): title = models.CharField(max_length=50) storyline = models.CharField(max_length=200) active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Review(models.Model): username = models.ForeignKey(User, on_delete=models.CASCADE) rating = models.PositiveIntegerField(validators = [MinValueValidator(1), MaxValueValidator(5)]) comment = models.CharField(max_length=200, null=True) watchlist = models.ForeignKey(WatchList, on_delete=models.CASCADE, related_name="reviews") avg_rating = models.FloatField(default=0) num_rating = models.IntegerField(default=0) active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.comment serializer.py class ReviewSerializer(serializers.ModelSerializer): username = serializers.StringRelatedField(read_only=True) class Meta: model = Review exclude = ["watchlist"] class WatchListSerializer(serializers.ModelSerializer): ### using relation serializer to list all the reviews in a movie reviews = ReviewSerializer(many=True, read_only=True) class Meta: model = WatchList fields = "__all__" views.py class ReviewCreateView(generics.CreateAPIView): serializer_class = ReviewSerializer permission_classes = [IsAuthenticated] def get_queryset(self): return Review.objects.all() def perform_create(self, serializer): ##posting the comment in a movie using movies primary key primary_key = self.kwargs.get("pk") watchlist = WatchList.objects.get(pk=primary_key) #NOt allowing the same user to comment on the same movie twice username = self.request.user review_queryset = Review.objects.filter(watchlist=watchlist, username=username) … -
Use Set of Choices as the order_by
class OrganizationAccount(AbstractUser): OrgRole = [('President', 'President'),('Internal VP', 'Internal Vice President'), ('External VP', 'External Vice President'), ('Treasurer', 'Treasurer'), ('Secretary', 'Secretary'), ("Assistant Secretary", "Assistant Secretary"), ("Auditor", "Auditor"), ("Outreach Program Director", "Outreach Program Director"), ("Event Coordinator", "Event Coordinator"), ("Public Information Officer", "Public Information Officer"), ("Digital Officer", "Digital Officer"), ("Representative", "Representative"), ('Member', 'Member') ] role = models.CharField(choices = OrgRole, max_length=32) I'm looking for a way to call OrganizationAccount.objects.all().order_by('OrgRole') In a sense that it would produce a query set in this order (Pres, Internal VP, External VP, ...) Is there any way to execute this? -
Cpanel Django ERR_TOO_MANY_REDIRECTS on Admin/Auth/User and Admin/Auth/Group Pages
I'm doing a project for a client using Django and have finally installed it on CPanel. Everything seems to be working great, but when I try to access the admin panel, the tables group or user has an error because it says it's doing a lot of redirections. In the admin panel, I just have this: When I try to register something, it loads the page, like this: But when I try to access the tables, it shows me an ERR_TOO_MANY_REDIRECTS, as shown in the following picture: It basically says that it's not working and to try to delete my cookies. I did that, and nothing worked. In the urls.py I only have the admin path so the redirection problem is not from something I miscofigured there. I haven't modified the installation parameters for settings.py besides the Allowed_Host variable to allow the URL of the page, the database connection using PostgreSQL and its working, and the variables of the static files are also working. So I'm feeling deadlocked because I can't find an answer to this and I don't believe I'm the first one experiencing this. If someone knows anything, please let me know. -
How can i limit the number of objects we can save by with a condition and without a condition in django?
What is meant is, I want to save only one object with is_featured field true, if user tried to save another object with is_featured field true it needs to give a prompt, How can i accomplish that in django any idea? class Event(BaseModel): title = models.CharField(max_length=200) time = models.TimeField() date = models.DateField() location = models.CharField(max_length=200) location_url = models.URLField() description = models.TextField() is_featured = models.BooleanField(default=False) image = VersatileImageField('Image', upload_to="web/events") class Meta: db_table = 'web_event' verbose_name = ('Event') verbose_name_plural = ('Event') ordering = ('auto_id',) def __str__(self): return str(self.title) -
Firebase Cloud Messaging registration token - Flutter and Django
I am trying to send push notifications (iOS, Android, Web) to specific users when certain events happen in my app. I am using the firebase_admin python plugin with Django, working properly for authentication and verifying jwt, but it is giving me this error when trying to send a Message/Notification from Django: firebase_admin.exceptions.InvalidArgumentError: The registration token is not a valid FCM registration token I am getting the token directly from my Flutter instance and sending it in the request body from Flutter to Django. My method for getting the token from Flutter: await FirebaseMessaging.instance.getToken().then((token) async { fcm_token = token!; }).catchError((e) { print(e); }); My python code that sends notification: registration_token = self.context['request'].data["token"], # See documentation on defining a message payload. message = Message( notification=Notification( title='New Product Added', body='A new product called ' + validated_data['name'] + ' has been added to your account.', ), token=str(registration_token) ) # Send a message to the device corresponding to the provided # registration token. response = send(message) I have verified that the token being passed to Django is correct, by comparing it to what I am getting from Flutter -
Building chart using charjs in Django
I need to create a chart with chartjs with displaying month wise count on current year in a line chart. The data should be retrieved from the model named "invoice" and the feild name is "Invoice_date". Note: Invoice_date is an DateFeild(). in views.py def home(request): if request.user.is_authenticated: customers = User.objects.filter(groups__name='Customer').count() totalinvoice = invoice.objects.all().count() supplier = User.objects.filter(is_staff=True).count() # chart labels = ["Jan","Feb","Mar","Apr","Jun","Jul","Aug","Sep","Oct","Nov","Dec"] data = [12,14,19,25,28,80,23,35,46,78,45,23] // This data's should be retrieved dynamically return render(request, 'home.html', { 'totalinvoices':totalinvoice, 'customers':customers, 'supplier':supplier, "labels":json.dumps(labels), "data":json.dumps(data), }) else: return redirect("login") Please someone help me in figuring out. -
Django: How can I show the name instead of the id in the list?
I have a form to create a user, when displaying the data in the list the foreign keys are shown with the id, how can I make the name appear instead of the id? I'm trying to do it with a for inside the template but it doesn't show me anything my user table has the cargo_empleado table as a foreign key and inside the cargo_empleado table I have a column called nombre_cargo, the column nombre_cargo I want to be displayed instead of the id template <td class="ps-0 pe-0"> {% for cargo_empleado in request.user.cargo_empleado %} {% if cargo_empleado.nombre_cargo == 'funcionario' %} <a href="" class="btn btn-info btn-sm no-hover" style="cursor: default; border-radius: 2rem; pointer-events: none;">Funcionario</a> {% endif %} {% if cargo_empleado.nombre_cargo == 'diseñador' %} <a href="" class="btn btn-warning btn-sm no-hover" style="cursor: default; border-radius: 2rem; pointer-events: none;">Diseñador</a> {% endif %} {% endfor %} <!-- {% if display.7 == 1 %} <a href="" class="btn btn-info btn-sm no-hover" style="cursor: default; border-radius: 2rem; pointer-events: none;">Funcionario</a> {% else %} <a href="" class="btn btn-warning btn-sm no-hover" style="cursor: default; border-radius: 2rem; pointer-events: none;">Diseñador</a> {% endif %} --> </td> -
Web Application Technologies and Django, (string that looks like 53656C696E613333) 2022
my wish is to know exactly what are asking for in this part of the final exercise of week 5 of the course (Web Application Technologies and Django University of Michigan). enter image description here enter image description here I understand that I have to run the above in pythonanywhere and... 1) I don't know if I have to enter the same code written there in the text box above, 2) I have to enter the outputs of said code in the text box, 3) I have to enter in the text box the code corresponding to the question shaded in blue in the image or its output or the code of the question with the output??? Besides, if possible, I would like to know what exactly asks that question. I don't know if I should update the first value of the table so that its hexadecimal (name, age) returns that "53656C696E613333" or something else. I appreciate the help. -
Each child in a list should have a unique "key" prop error with uuid as key react
I'm getting an "Each child in a list should have a unique "key" prop." in console here specifically (it quotes the first line as the relevant line) <Dropdown.Menu variant="dark"> {[ [0, "prod_name", "Name"], [1, "price", "Price"], [2, "average_rating", "Rating"], ].map((item, i) => ( <> <Dropdown.Item as={Button} key={uuid.v4()} onClick={() => { this.setState({ sort: item[0], open: false }); this.context.sort(item[1], "asc"); }} className={ this.state.sort === item[0] ? "text-black giBold active" : "text-light" } > {item[2] + " (ascending)"} </Dropdown.Item> <Dropdown.Item as={Button} key={uuid.v4()} onClick={() => { this.setState({ sort: item[0] + 3, open: false }); this.context.sort(item[1], "desc"); }} className={ this.state.sort === item[0] + 3 ? "text-black giBold active" : "text-light" } > {item[2] + " (descending)"} </Dropdown.Item> </> ))} </Dropdown.Menu>; I changed the key to be uuid since I realised tonnes of id's of different items are going to be the same in hopes that it would fix the error yet it keeps popping up. Is there something else at play here that I've missed, I tried looking for answers but couldn't find much. -
Save multiple files in a database with multiple submit buttons on a single html page
I am building a website in python django and I am new to this. Is there a way I can save multiple files with multiple submit buttons on the same html page. I created a table to store them separately. Any assistance would be appreciated. -
websockets with Django channels rest framework in docker-compose
I've made an application with two websockets connections using Django channels rest framework. Locally, everything works fine. I have such settings: #routing.py from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application from django.urls import re_path from gnss.consumers import CoordinateConsumer # noqa from operations.consumers import OperationConsumer # noqa websocket_urlpatterns = [ re_path(r'ws/coordinates/', CoordinateConsumer.as_asgi()), re_path(r'ws/operations/', OperationConsumer.as_asgi()), ] application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AuthMiddlewareStack( URLRouter(websocket_urlpatterns) ), }) # consumers.py from djangochannelsrestframework.decorators import action # noqa from djangochannelsrestframework.generics import GenericAsyncAPIConsumer # noqa from djangochannelsrestframework.observer import model_observer # noqa from djangochannelsrestframework.observer.generics import action # noqa from djangochannelsrestframework.permissions import AllowAny # noqa from .models import Coordinate from .serializers import CoordinateSerializer class CoordinateConsumer(GenericAsyncAPIConsumer): queryset = Coordinate.objects.all() serializer_class = CoordinateSerializer permission_classes = (AllowAny,) @model_observer(Coordinate) async def coordinates_activity(self, message, action=None, **kwargs): await self.send_json(message) @coordinates_activity.serializer def coordinates_activity(self, instance: Coordinate, action, **kwargs): return dict(CoordinateSerializer(instance).data, action=action.value, pk=instance.pk) @action() async def subscribe_to_coordinates_activity(self, request_id, **kwargs): await self.coordinates_activity.subscribe(request_id=request_id) As for the consumers.py for the ws/operations/ it's exactly the same. When I run my Django app on local machine in development server (python manage.py runserver) everything works fine. But for some reason, when I run my app in docker-compose, ws/operations/ works, but ws/coordinates not. I don't recieve messages from Django for … -
django: How to write JavaScript fetch for url with slug parameter?
A django and async newbie here, trying to improve a simple message-board app. I'm sure you've all seen this problem dozens of times, but I'm unable to find a solution... Currently, when a user likes a posted message, it refreshes the whole page. I'd like to use simple JavaScript with the fetch API to prevent this, without having to resort to Ajax, as I've never used it. The problem is, I'm very new to the fetch method as well and I'm struggling to find the correct syntax for the url in the fetch request, as it uses the post model's slug field as a parameter. Like so: urls.py urlpatterns = [ ... path('post/<slug:slug>/', views.FullPost.as_view(), name='boards_post'), path('like/<slug:slug>/', views.PostLike.as_view(), name='post_like'), ... ] models.py ... class Post(models.Model): """ Model for message posts """ STATUS = ((0, "Draft"), (1, "Published")) title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name="board_posts" ) category = models.ForeignKey( Category, on_delete=models.CASCADE, default="", related_name="category_posts" ) created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) content = models.TextField() post_image = CloudinaryField('image', default='placeholder') status = models.IntegerField(choices=STATUS, default=0) likes = models.ManyToManyField(User, related_name="post_likes") class Meta: # Orders posts in descending order ordering = ['-created_on'] def __str__(self): return self.title def number_of_likes(self): return self.likes.count() def … -
URL to redirect related model instance django
I have a 2 models with ForeignKey linked to each other class Moc(models.Model): title = models.CharField(max_length=128, blank=False) scope = models.TextField(max_length=128, blank=False) .... def __str__(self): return self.title class Verifier(models.Model): moc = models.ForeignKey(Model1, related_name='verifiers' on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) approve = models.BooleanField(default=False). reject = reject = models.BooleanField(default=False) .... def __str__(self): return str(self.id) I have a respective forms, views and templates to create, update, delete records. def verifier_signoff_view(request, pk): verifier = Verifier.objects.get(pk=pk) form = VerifierSignForm if request.method == 'POST': form = VerifierSignForm(request.POST, instance=verifier) if form.is_valid(): form.save(commit=False) if verifier.approve is True and verifier.reject is True: return HttpResponseForbidden('You have either APPROVE or REJECT - operation not allowed!') else: form.save() return redirect('verify_coorinate' pk=verifier.moc_id) # This is where I need help... else: return render(request, 'moc/verify_signoff.html', context={'verifier': verifier, 'form': form}) What I want is that after I update Model2 instance as per above view, I want to redirect back to Model1 instance rather than verifier instance. Any help please...