Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Lightbox error when trying to find close.png next.png loading.png prev.png
Could someone point me in the direction where I am supposed to be saving the subjected files? The error I am getting is "Not Found: /images/close.png" when trying to add buttons to my lightbox images. It's obviously expecting an images folder but I cannot seem to place it in the correct location within my project. Anyone lend a hand on where exactly to place this images folder..? Using Pycharm enter image description here -
Serving Django Channel and Django Rest Framework from same Elastic Bean Server?
How to serve the Django Rest Framework and Django Channel from the same Elastic Bean Container? -
@user_passes_test not working as expected - Django Python
I have created a role based login in Django 3.1.2. And i have used @user_passes_test decorator to check the role of user according to his/her role he can access the views, or we can say views will execute but it is not working as expected. models.py class User(AbstractUser): GENDER = ( (True, 'Male'), (False, 'Female'), ) USER_TYPE = ( ('Admin', 'Admin'), ('Designer', 'Designer'), ('Customer', 'Customer'), ) user_id = models.AutoField("User ID", primary_key=True, auto_created=True) avatar = models.ImageField("User Avatar", null=True, blank=True) gender = models.BooleanField("Gender", choices=GENDER, default=True) role = models.CharField("User Type", max_length=10, choices=USER_TYPE, default='Customer') Here in user models I have a field, with help of that I can specify user role and default is Customer. views.py # view to check whether a user is Designer or Admin def check_role_admin_or_designer(user): if user.is_authenticated and (user.role == 'Admin' or user.role == 'Designer'): print(user.role) return True # view to check whether a user is Admin def check_role_admin(user): if user.is_authenticated and (user.role == 'Admin' or user.is_superuser): return True else: return HttpResponse("You are not Authorized to access this page") # my login view def loginPage(request): if request.user.is_authenticated and request.user.role == 'Customer': return redirect('user-home') if request.user.is_authenticated and ( request.user.role == 'Admin' or request.user.role == 'Designer' or request.user.is_superuser): return redirect('admin-home') else: if … -
How can I update page content without reloading the page on Modal close?
I am trying to edit a post on a page, clicking on edit link opens a Modal, clicking on save button, saves the edited post in the database but I have to refresh the page to see that edited post on the screen. I want the screen to be updated as soon as the modal is closed but I don't want the page to be reloaded. How can I achieve this without reloading the page? Views.py def editTweet(request, post_id): postData = Posts.objects.filter(id = post_id) if request.method == "PUT": data = json.loads(request.body) print("data value is ", data) #updating data in the database where id = post_id Posts.objects.filter(id = post_id).update(postContent = data.get('postContent', None)) print ("i'm inside PUT") return render(request, 'network/index.html') else: print("i'm inside else") return JsonResponse([post.serialize() for post in postData], safe=False) JavaScript function loadModal(id) { //load the modal var modal = document.getElementById("myModal"); var btn = document.getElementById("editLink"); var span = document.getElementsByClassName("close")[0]; var saveBtn = document.getElementById("saveButton"); //populate the modal with tweet content fetch(`/edit/${id}`) .then(response => response.json()) .then(postDetails => { modal.style.display = "block"; postDetails.forEach(element => { document.querySelector('#editPostBox').value = `${element.postContent}`; }) }) // When the user clicks on <span> (x), close the modal span.onclick = function () { modal.style.display = "none"; } saveBtn.onclick = function(){ fetch(`/edit/${id}`, … -
AttributeError: Generic detail view AddMessageView must be called with either an object pk or a slug in the URLconf
Generic detail view AddMessageView must be called with either an object pk or a slug in the URLconf. Basically I am trying to access a page for me to add post into a room through the link in room.html. However I received the error above. Why is this error happening?? It might be that i need to specify the 2 diff slugs in my classbased view but how do I do that if the slug belongs to 2 different models? url.py path('<slug:type1_slug>/<slug:type2_slug>/messages/', AddPostView.as_view(), name= "add_post"), room.html <a href="{% url 'add_post' type1_slug=room.slug type2_slug=category.slug %}"> views.py def room_view(request, type1_slug, room_slug): context = {} category = get_object_or_404(Category, slug=type1_slug) context['category'] = category room = get_object_or_404(Room, slug=room_slug, typeofcategories=category) context['room'] = room return render(request, "room.html", context) class AddPostView(DetailView, FormView): model = Room form_class = PostForm template_name = 'HomeFeed/add_post.html' models.py class Category(models.Model): category = models.CharField(max_length=80, null=False, blank=False, unique=True) slug = models.SlugField(blank=True, unique=True) class Room(models.Model): categories = models.ForeignKey(Category, related_name='typeofcategories', on_delete=models.CASCADE) description = models.TextField(max_length=300, null=True, blank=True) slug = models.SlugField(blank=True) -
django-static-precompiler throwing error with no message
I'm trying to use django-static-precompiler to compile scss but I'm getting an error StaticCompilationError that says No exception message supplied The version for django-static-precompiler is 2.0 and sass is installed and is the latest version (1.32.6). I have the precompiler configured to point to node modules in my settings.py. STATIC_PRECOMPILER_COMPILERS = ( ('static_precompiler.compilers.SCSS', { "executable": "node_modules/.bin/sass" }), ) Here is a snippet from the template it's used in: <link rel="stylesheet" href="{% static "/css/style.scss"|compile %}" /> The error message is not very helpful. Does anyone have any idea what the issue could be? -
request.post variable is always returning as empty
So I'm trying to see if user matches their old password, if they don't then it will give a message saying "Your old password in incorrect" but if they match their old password then it should check if user matched new and confirmed password correctly, if they did not then it should give a message saying "Your new passwords do not match" but if their password is empty it should say "Your new passwords are empty, But even if my passwords are not empty it always says my passwords are empty. I have also tried if new_password1 or new_password2 == '' but that also has the same result. views.py @login_required def userchange(request): if request.method == 'POST': user = request.user old_password = request.POST['Old password'] new_password1 = request.POST['New password1'] new_password2 = request.POST['New password2'] if user.check_password(old_password): if new_password1 == new_password2: if new_password1 or new_password2 is None: return render(request, 'main/change.html', {'error':'Your new passwords are empty!'}) else: user.set_password(new_password1) return render(request, 'main/change.html', {'error':'Your password has been changed succesfully!'}) else: return render(request, 'main/change.html', {'error':'Your new passwords do not match'}) else: return render(request, 'main/change.html', {'error':'Your old password is incorrect'}) elif request.method == "GET": return render(request, 'main/change.html') change.html <h1>Note: You will be logged out</h1> <h2>{{ error }}</h2> <form method="POST"> … -
I want my search function to be able to take multiple words rather than just one word, or exact sentence match in my database
Here is my search bar function: ` def searchbar(request): if request.method == "GET": search = request.GET["search"], deity = Deity.objects.filter(Q(name__contains=search[0])|Q(location__contains=search[0])|Q(alt_name__contains=search[0])|Q(culture__contains=search[0])|Q(religion__contains=search[0])|Q(description__contains=search[0])|Q(pop_culture__contains=search[0])), context = { "user": User.objects.get(id = request.session['user_id']), "deity": deity, "search": search[0], } return render(request, 'search_results.html', context) ` My Navbar has a search text box and button, and it searches my entire database for exactly what I put into the search bar (with the exception of capitalization, that doesn't seem to matter). However, if I put a sentence in, it takes whole sentence and searches for it exactly not recognizing the individual words in the search. How can I fix this? -
Annotate queryset with a boolean from ManyToMany relation
Lets say I have a Book model like this: class Book(models.Model) title = models.Charfield(...) likes = models.ManyToMany(User, related_name="books_liked") I need to annotate a queryset with a is_liked field for the current logged user. something in the view like this: qs = Book.objects.all().annotate(????) so I can use something like this in the template {% for book in books %} {% if book.is_liked %} ... {% endif %} {% endfor %} I'm checking this docs section, but I'm not too sure how to proceed or if is the correct way. https://docs.djangoproject.com/en/3.1/ref/models/expressions/#exists-subqueries How can I do this? Thanks. -
Django Channels: "No text section for incoming WebSocket frame!"
I'm using django-channels's AsyncJsonWebsocketConsumer [reference] and I keep getting the error "No text section for incoming WebSocket frame!" after sending a message on an established socket connection. AsyncJsonWebsocketConsumer throws this error when it can't find text_data. # django-channels source code async def receive(self, text_data=None, bytes_data=None, **kwargs): if text_data: await self.receive_json(await self.decode_json(text_data), **kwargs) else: raise ValueError("No text section for incoming WebSocket frame!") This is my code which causes this error to be thrown. async def send_message(self, txt): message = Message.objects.create(body=txt) data = serializers.MessageSerializer(message).data await self.send_json({ 'type': msg.get('type'), 'data': data, }) # await self.channel_layer.group_send(self.conversation_group_name, data) async def receive_json(self, content, close=False): message_type = content.get('type') if message_type == 'send.message': await self.send_json({ 'type': message_type, 'data': content.get['data'] }) -
Deploying Django to Production (Not on Heroku/PythonAnywhere)
i currently have completed my Django Project and am ready to launch it.Its my first time launching so I'm asking if anyone has a checklist of what is required to be changed before you launch it to production. `After launching it, do you need to keep your laptop switched on at all times to runserver? Or is there a way to someone else's server to run it, and if I use IAAS from someone else, would I be able to makechanges/ access the admin panel anytime i want? i need to change DEBUG from true to false -My static CDN and email login confirmations, how will they be stored and how will i be able to access them? -The settings secret key, will the settings.py file be widely available to the public for everyone to see? Or will it be hidden. If hidden, how can i hide it. Also same for the stripe key. -Requirements.txt, how do I "import" all the codes to the "server" to make sure that they all work? -What are all the files to be hidden from the public and how can I hide them? Is there anymore changes that I need to make? -
How do I turn Django Multislelect checkbox fields into clickable buttons?
Trying to create each of the fields/moods as clickable buttons. Not looking to make it a dropdown menu, as I want all the buttons to be visible at once. This is what I have so far... <b>What are you feeling?</b><br> Please choose at least one mood for best results. <br> {% for x in form.visible_fields.7%} <div> {{ x }} </div> {% endfor %}``` -
Django distinguish between add_fieldsets and get_fieldsets
I have a below fieldset in my model, fieldsets = [ (None, { "fields": ["email", "password", "name"] }), ("Account Profile", { "fields": [ "company", "profession", ] }), ("Account Settings", { "fields": [ "nsfw", "is_staff", "is_active", "is_dev", "detector_token", "detection_api_access" ] }), ] And I have added a get_fielsets method to display is_superuser field only when the logged in user is a superuser, def get_fieldsets(self, request, obj=None): fieldsets = super(AccountAdmin, self).get_fieldsets(request, obj) print(fieldsets) if request.user.is_superuser: fieldsets[2][1]['fields'].insert(1, 'is_superuser') return fieldsets Now the problem is that my code has add_fieldsets as below which gets called while creating new accounts and it gets failed at statement fieldsets[2][1]['fields'].insert(1, 'is_superuser') because it do not have those records, add_fieldsets = ((None, { 'classes': ('wide', ), 'fields': ("email", 'password', 'password2', "is_staff", "is_active") }), ) What is the best way to handle this scenario. I am getting error as tuple index out of range -
using dictionary in models.py
Im trying to write a model for a character in my version od D&D and I want that the user could only choose from the two dictionaries which I wrote from django.conf import settings from django.urls import reverse from django.db import models import misaka from django.contrib.auth import get_user_model User = get_user_model() # Create your models here. Races={ 'Dragonborn':{'attack':13,'deffence':12,'intelligence':12,'agility':12,'wisdom':13,'charisma':13}, 'Dwarf':{'attack':11,'deffence':14,'intelligence':14,'agility':10,'wisdom':15,'charisma':11}, 'Elf':{'attack':10,'deffence':8,'intelligence':15,'agility':13,'wisdom':15,'charisma':14}, 'Gnome':{'attack':15,'deffence':15,'intelligence':10,'agility':15,'wisdom':10,'charisma':10}, 'Half-Elf':{'attack':13,'deffence':10,'intelligence':13,'agility':14,'wisdom':12,'charisma':13}, 'Halfling':{'attack':12,'deffence':13,'intelligence':14,'agility':13,'wisdom':12,'charisma':11}, 'Orc':{'attack':15,'deffence':15,'intelligence':11,'agility':12,'wisdom':11,'charisma':11}, 'Human':{'attack':12,'deffence':12,'intelligence':13,'agility':13,'wisdom':13,'charisma':12} } Classes={ 'Barbarian':{'attack':6,'deffence':3,'intelligence':1,'agility':4,'wisdom':1,'charisma':1}, 'Bard':{'attack':2,'deffence':1,'intelligence':4,'agility':4,'wisdom':4,'charisma':4}, 'Cleric':{'attack':3,'deffence':2,'intelligence':4,'agility':1,'wisdom':4,'charisma':2}, 'Druid':{'attack':3,'deffence':2,'intelligence':3,'agility':2,'wisdom':3,'charisma':3}, 'Fighter':{'attack':6,'deffence':3,'intelligence':1,'agility':4,'wisdom':1,'charisma':1}, 'Monk':{'attack':2,'deffence':2,'intelligence':3,'agility':4,'wisdom':3,'charisma':2}, 'Paladin':{'attack':5,'deffence':5,'intelligence':2,'agility':1,'wisdom':2,'charisma':1}, 'Ranger':{'attack':4,'deffence':1,'intelligence':3,'agility':5,'wisdom':3,'charisma':1}, 'Rogue':{'attack':5,'deffence':1,'intelligence':1,'agility':7,'wisdom':1,'charisma':1}, 'Sorcerer':{'attack':2,'deffence':1,'intelligence':6,'agility':1,'wisdom':5,'charisma':1} } class Character(models.Model): user=models.ForeignKey(User,related_name='characters',on_delete=models.CASCADE) name=models.CharField(max_length=200) #Races #class how do I use the "models." for something like this? -
django: how to assign a logged in user to a post author
I've set the default post author to be null, and used the form_valid function to override the post author and assign to it the current logged in user. the form_valid() function is taken from the official django docs but for some reason its doesnt do anything. my django versions are: django-rest-framework = 3.12.2. django = 3.1.4 models.py class Recipe(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) author = models.ForeignKey(get_user_model() , on_delete=models.CASCADE, null=True) # title = models.CharField(max_length=150) description = models.TextField(blank=True) serializers.py class RecipeCreateSerializer(serializers.ModelSerializer): class Meta: model = Recipe fields = ('title', 'description') views.py class RecipeCreate(CreateAPIView): permission_classes = (permissions.IsAuthenticated, ) queryset = Recipe.objects.all() serializer_class = RecipeCreateSerializer def form_valid(self, form): form.instance.author = self.request.user return super(RecipeCreate, self).form_valid(form) hopefully someone out here will know how to fix this. thanks in advance -
How do I change relay connection limit in graphene django
In graphene-django I have a pagination limit set in my settings.py file like below. GRAPHENE = { 'RELAY_CONNECTION_MAX_LIMIT': 150, } Let's say a particular query returns 200 items (I don't know beforehand) and I want to display all of this data on a graph. How do I stop graphene from paginating it when returning the results? -
Run part of the View only once in Django
I am fairly new to Django and looking for best practice to run part of my view only once and never again during a session. Especially when page is reloaded or some other page was redirected to this page. My View looks something like this: def home_page(request): # This is the part I want to be executed once data = loadDataFucntion(some_cisco_device) # End of part . . # more code context = {'data': data} return render(request, 'home_template', context) What I am trying to accomplish is when home_template is reloaded or some other page in the app was redirected to home_page view, I don't want the LoadDataFunction to be executed and simply use the previously fetched data. -
Can someone help me understand what am I doing wrong ? My server will not run and gives this message
This is the terminal error message I keep getting. Can someone help me understand what am I doing wrong ? My server will not run and gives this message. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/urls/resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/patrickjobe/Desktop/personal_portfolio-project/personal_portfolio/urls.py", line 24, in <module> urlpatterns += static(settings.Media_URL, document_root=settings.MEDIA_ROOT) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/conf/__init__.py", line 83, in __getattr__ val = getattr(self._wrapped, name) AttributeError: 'Settings' object has no attribute 'Media_URL' this is how my URL.py file is set. from django.contrib import admin from django.urls import path from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += static(settings.Media_URL, document_root=settings.MEDIA_ROOT) this is my settings on my settings.py file. STATIC_URL = '/static/' Media_URL = '/media/' #set name to whatever you like. Media_Root = (BASE_DIR / 'db.sqlite3', 'media') -
How can I add a new database entry upon user registration with Django?
I'm starting to learn Django and have a class called Customer in my models. I'm importing django.contrib.auth to register users to the database, but I would like to also initialize a Customer object upon registration. I first attempted to override the save() method from the UserCreationForm and initialize a Customer object there: class UserCreationForm(forms.ModelForm): def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) customer = Customer(self) customer.save() if commit: user.save() return user But it did not seem to create a Customer object. Alternatively, is it better to extend the User class to have the Customer class fields? I initially thought I should keep authentication separate, which is why I created the Customer class. Thanks in advance! -
How do I add a foreign key field in a post method for Django Rest Framework
I am really sorry if I am being a noob, but how do I add a foreign key field with my post method. I need to mention the blog post, the user who made the comment with the post. But, the post and the user/owner are both foreign key fields in my models. With Postman it gives a Django Integrity error. models.py class Comment(models.Model) : text = models.TextField( validators=[MinLengthValidator(3, "Comment must be greater than 3 characters")] ) post = models.ForeignKey(Post, on_delete=models.CASCADE) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # Shows up in the admin list def __str__(self): return (self.post.title) serializers.py class CommentSerializer(serializers.ModelSerializer): owner = serializers.StringRelatedField() post = serializers.StringRelatedField() class Meta: model = Comment fields = ['id', 'text', 'created_at', 'post', 'owner'] views.py class CommentViewSet(viewsets.ModelViewSet): serializer_class = CommentSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] queryset = Comment.objects.all() filter_backends = [DjangoFilterBackend] filter_fields = ['post'] -
Django - view another user's profile - QuerySet Error 'matching query does not exist'
I'm trying to set up a basic blog on django where one may view the profile of any other user (simple for the time-being, I will update perms in due course). I've attempted to set it up so that url /testuser/ would take you to the profile of user with username = 'testuser'. The url seems to direct ok, however, I'm getting a QuerySet error 'matching query does not exist'. I know that testuser exists because I can access it in terminal using the same code as used in get_queryset below. Hence, I think there must be something wrong with my use of get_queryset in views.py, or similar. Code as follows. Thanks in advance for any help. views.py from django.views.generic.detail import DetailView from users.models import CustomUser class ProfileView(DetailView): template_name = 'profiles/self_profile.html' def get_queryset(username): return CustomUser.objects.get(username=username) def get_slug_field(self): return username urls.py urlpatterns = [ path('<str:slug>', ProfileView.as_view(), name='self_profile'), ] Thanks in advance for any help. -
Ordering by related object by related object in Django
I'm using django-taggit and django-taggit-templatetags2 for tagging and displaying tags in my templates. I'm also using the custom tagging option with django-taggit. class RNTag(TagBase): color = models.CharField(max_length=10) class Meta: verbose_name = _('Tag') verbose_name_plural = _('Tags') class RNTaggedItem(GenericTaggedItemBase): tag = models.ForeignKey(RNTag, on_delete=models.CASCADE, related_name="rn_tagged_items",) class PR(models.Model): . . . class RN(models.Model): pr = models.ForeignKey(PR, on_delete=models.CASCADE, related_name='rns') tags = TaggableManager(through=RNTaggedItem) This is working as expected. However, I'd like to list the items in my template a certain way, and this is where the problem begins. The ListView I'm using looks like this: class PRList(ListView): model = PR In the template, I'm doing this: {% for pr in pr_list %} {% if pr.rns %} <ul> {% for rn in pr.rns.all %} <li> {% for t in rn.tags.all %} <span class="badge bg-{{ t.get_color_display }}"> {{ t.name }} </span> {% endfor %} </li> {% endfor %} </ul> {% endif %} {% endfor %} How do I get this list of prs(of rns(of tags)) to order by tag color? As it is now, for one pr, the rns and their associated tags are ordered by rn. I've tried order_with_respect_to, ordering, on the models involved in various ways, but nothing is working for me. I suspect that without … -
Make django foreignkey varied
I want to make message model which handle 2 users. class User(AbstractUser): is_confirmed = models.BooleanField(default=False, choices=((True, 'True'), (False, 'False')), blank=True) verification = models.CharField(max_length=100, null=True, default=None, blank=True) pass_key = models.CharField(max_length=100, null=True, default=None, blank=True) language = models.IntegerField(default=0) def __str__(self): return self.username class Admin(User): extra = models.CharField(max_length=50, null=True, default="") ... class Client(User): extra2 = models.CharField(max_length=50, null=True, default="") ... class ChatMessage(models.Model): sender = models.ForeignKey(Admin, related_name = 'sender_user', on_delete=models.CASCADE) receiver = models.ForeignKey(Client, related_name = 'receiver_user', on_delete=models.CASCADE) message = models.CharField(max_length = 200) received_at = models.DateTimeField(auto_now_add = True) session = models.ForeignKey(Session, on_delete=models.CASCADE) is_read = models.BooleanField() how can I make the sender and receiver in a way that can be admin or client. -
Session based authentication to Django Rest Framework from Angular
The DRF documentation (https://www.django-rest-framework.org/api-guide/authentication/#authentication) states that Token authentication is appropriate for client-server setups, such as native desktop and mobile clients. and Session authentication is appropriate for AJAX clients that are running in the same session context as your website. Yet most of the tutorials and StackOverflow questions/answers about Django Rest Framework Authentication suggest using Token authentication in most of the cases, even with webapps. I'm implementing a webapp usingDjango/Django Rest Framework as the backend and Angular as the fron-end. Which authentication scheme should I use? What are the pros and cons of each? -
Is there a way to access nested python dictionaries in django template without template tag or database query?
Without using a custom template tag or database queries - what would be the best way ... or any way to display the following dict values in a template page without calling any key explicitly until getting to the final level (name, profession, fun fact): upcoming_meetings = { dateOne: { PersonOne:{ Name:"valueOne", Profession:"valueTwo", Fun_Fact:"valueThree" }, PersonTwo:{ Name:"valueOne", Profession:"valueTwo", Fun_Fact:"valueThree" } }, dateTwo: { PersonOne:{ Name:"valueOne", Profession:"valueTwo", Fun_Fact:"valueThree" }, PersonTwo:{ Name:"valueOne", Profession:"valueTwo", Fun_Fact:"valueThree" } } } I've gotten as far as trying the following combination but have only gotten as far as the "dates" level displaying in a formatted fashion and all other values displaying as unfiltered and unformatted dictionary values. {% for date, person in upcoming_meetings.items %} <h4>{{ date }}</h4> <p>{{ person }}</p> {% endfor %}