Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot assign "'cool_username'": "Comment.author" must be a "User" instance?
I'm working on a Django blog and I'm stuck here... I'm getting this error Cannot assign "'cool_username'": "Comment.author" must be a "User" instance. I have no idea where I'm making a mistake, please see my code below: this is views.py def post_detail(request, slug): post = get_object_or_404(Post, slug=slug) related_posts = post.tags.similar_objects()[:3] comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': if request.user.is_authenticated: comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.author = request.user new_comment.save() else: messages.warning(request, 'You need to be logged in to add a comment.') else: if request.user.is_authenticated: comment_form = CommentForm(initial={'author': request.user}) else: comment_form = CommentForm() context = {'post': post, 'related_posts': related_posts, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form} return render(request, 'post_detail.html', context) this is comment part post_detail.html {% if user.is_authenticated %} <!--comment form--> <div class="comment-form"> <h3 class="mb-30">Leave a Reply</h3> <form class="form-contact comment_form" action="{% url 'post_detail' post.slug %}" method="post"> {% csrf_token %} <div class="row"> <div class="col-12"> <div class="form-group"> {{ comment_form | crispy }} </div> </div> </div> <div class="form-group"> <button type="submit" class="button button-contactForm">Post Comment</button> </div> </form> </div> {% else %} <div class="alert alert-danger" role="alert"> Please log in to post a comment. </div> {% endif %} this is models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') body = models.TextField() … -
Django user permission by branch
If there is user belong to branch_1 and branch_2 but with different role/group in branch_1 he is HR manager but in branch_2 he is HR lets say with no edit permission or receives employee emails. I don't think its correct to create group or permissions for branch_1 and group for second one, and so on for every new relation between an user and a branch. branch a group should be abstract from that. What is the best approach to manage user permission per branch? Thank you. -
cs50 network javascript fetch
I'm stack with showing the like or unlike button and the likes number without refreshing the page, i should do it with javascript fetch call. Any idea how to solve it. This is my codes: class Like(models.Model): user_like = models.ForeignKey( User, on_delete=models.CASCADE, related_name="like_user") post_like = models.ForeignKey( NewPost, on_delete=models.CASCADE, related_name="like_post") def __str__(self): return f"{self.user_like} likes {self.post_like}" class Post(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="author", blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True) post = models.TextField(max_length=200, blank=True, null=True) liked = models.ManyToManyField(User, default=None, blank=True) def __str__(self): return f"{self.post}" def like(request, post_id): """ Set liked """ post = Post.objects.get(pk=post_id) user = User.objects.get(pk=request.user.id) if user in post.liked.all(): post.liked.remove(user) else: post.liked.add(user) like = Like(user_like=user, post_like=post) like.save() return JsonResponse({"likes": post.liked.all().count()}) <h6 class="card-subtitle mb-2 text-muted" id="count-likes">({{ post.liked.all.count }}) Likes</h6> <button type="submit" id="like-btn" class="btn btn-outline-info"> {% if user not in post.liked.all %} Like {% else %} Unlike {% endif %} </button>``` -
Django media file page not found
So, I'm trying to follow Django documentation about the static files and media files I have a clean Django installation and I want to add the media folder. What I've done? I've changed the urls.py inside the project (not the app) and the settings.py as below settings.py STATIC_URL = 'static/' MEDIA_URL = 'media/' MEDIA_ROOT = BASE_DIR / "media" STATICFILES_DIRS = [ BASE_DIR / "static", ] urls.py urlpatterns = [ path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) But I got the Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in web_project.urls, Django tried these URL patterns, in this order: admin/ ^media/(?P.*)$ The empty path didn’t match any of these. I've also tried adding the 'django.template.context_processors.media' into TEMPLATES and using os as below STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) but nothing changes What it could be? -
Django - How to get just two fields from foreigKey in DRF model/serializer
Here is my model and serializers classes: class Employee(models.Model): name = models.CharField(max_length=255) manager = models.ForeignKey('self', on_delete=models.RESTRICT, related_name='employee_manager') score = models.FloatField() updator = models.ForeignKey(User, on_delete=models.RESTRICT, related_name='employee_updator') class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = '__all__' Currently I'm getting this response: [ { "id":1, "name": "David", "manager": null, "score": 18.7, "updator": 15 }, { "id":2, "name": "Sara", "manager": 1, "score": 12.3, "updator": 15 } ] But I need to have 'id' and 'name' of manager like this: [ { "id":1, "name": "David", "manager": null, "score": 18.7, "updator": 15 }, { "id":2, "name": "Sara", "manager": { "id":1, "name":"David" }, "score": 12.3, "updator": 15 } ] I tried adding 'depth=1' to my serializer but it also returns 'employee_updator' details that I'm not interested in. Any help would be appreciated. Thanks. -
How do I get data from a form in django while the user is filling it out and show hidden fields
I'm having problems when getting data being filled in a form in django I'm wanting to create a form with hidden fields, but which are dependent on another field. If the previous field has been filled in, the hidden field is shown. -
How to use --rebuild correctly in Django+elasticsearch?
I have a table in my db which size is about 75 millions of records im trying to use command python manage.py search_index --rebuild But its finished after about 3 hours with exception django.db.utils.OperationalError: server closed the connection unexpectedly even when i use --parallel arg, so is there exists a way to rebuild an index? I wanna note that i do it locally not on server, just to test is it speeds up my search or not. And i also use django signals to update the index when the table updates, so this action will take so much time as well? -
"Relay access denied" in django app using namecheap private email
So I have a Django app that sends confirmation emails to users who want to register their account. It looks something like this views.py def send_activation_email(user, request): current_site = get_current_site(request) email_subject = "Activation Email" context = {"user": user, "domain": current_site, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': generate_token.make_token(user) } email_body = render_to_string('email/activate.html',context) email = EmailMessage(subject=email_subject, body=email_body, from_email=settings.EMAIL_FROM_USER, to=[user.email]) email.send() and with settings.py looking like this EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.privateemail.com' EMAIL_FROM_USER = 'verification@ianisdo.xyz' EMAIL_HOST_PASSWORD = '[redacted]' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_USE_SSL = False The problem is that, when I try to send a email when the user creates an account, I get this error SMTPRecipientsRefused at /register/ {'ianis.donica@gmail.com': (554, b'5.7.1 <ianis.donica@gmail.com>: Relay access denied')} What I know for sure is: that it's not a problem with the private namecheap email, from which I can still send emails just not from my website. I also know the problem is not due to gmail not liking my email, as the same error when the email is sent to a yahoo.com domain. I also know that the issue is not with the settings.py not connecting to the views.py I also know that all the details are entered correctly From my knowledge and talking to … -
ImportError: cannot import name 'views' from 'bot'
I'm trying to implement a bot into a website using django and I ran into the error above. this is how the directory looks like: directory this is the urls for chatbot from . import views from django.urls import path urlpatterns = [ path('chatbot/', views.chatbot_view, name='chatbot'), path('chatbot/', views.chatbot, name='chatbot'), ] and this is the views for chatbot from django.shortcuts import render from . chatbot import create_connection from . chatbot import close_connection from . chatbot import execute_query from . chatbot import add_answer from . chatbot import normalize_text from . chatbot import get_keywords from . chatbot import match_question from . chatbot import get_answer from . chatbot import add_greeting_answers from . import chatbot_script def chatbot_view(request): if request.method == 'POST': question = request.POST['question'] answer = chatbot_script.get_answer(question) return render(request, 'chatbot/chatbot.html', {'answer': answer}) else: return render(request, 'chatbot/chatbot.html') I have modified the views and urls in the directory of chatbot and when I try to modify the urls for the directory bot this is what happens: error image I tried copying the views file from chatbot to bot and make changes to the urls in bot hoping that would make it work rather than say page not found. -
Django admin.autodiscover fails to discover "primary" admin.py
My models won't show up in the admin panel, and I suspect it's because admin.py isn't being discovered. Also, all the models work as expected in the application; I can import two.MyModelB and use it in the shell, in my web-app, etc. root/settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'one', 'two', etc] root/urls.py: from django.contrib import admin print("### Running admin-autodiscover ###") admin.autodiscover() Note that I don't usually use admin.autodiscover(), but it was a suggestion I came across when I was searching for solutions to this. Including it (or not) makes no difference either way. root/admin.py: from django.contrib import admin from django.conf import settings from one.models import MyModelA from two.models import MyModelB print("### This should be discovered! ###") class MyModelAdmin(admin.ModelAdmin): readonly_fields = ('id',) # Register your models here. admin.site.register(MyModelA, MyModelAdmin) admin.site.register(MyModelB, MyModelAdmin) superuser confirmed: console output: (env) PS E:\Django> python manage.py runserver Watching for file changes with StatReloader Performing system checks... ### Running admin-autodiscover ### System check identified no issues (0 silenced). Django version 4.1.5, using settings 'root.settings' Starting development server at http://127.0.0.1:8000/ The statement from urls.py is output, but not the one from admin.py. I assume that indicates there's some malfunction with django.contrib.admin, but it's far beyond my knowledge. Curiously, making admin.py … -
Querying for model based on file name
I've got a filename: filename = 'myfile.txt' I'd like to be able to query for it. summernoteimages = UserFile.objects.filter( Q(file__name=filename) ) I'm getting the following error: Unsupported lookup 'name' for FileField or join on the field not permitted. -
My Tamil letters are not displaying in Pdf file in Django
views.py def pdf(request,songsheetname): username=request.user.username printsong=Songsprintform.objects.all().filter(username=username,removesong='0', addsheetstatus='0',songsheetname=songsheetname,songprintstatus='1') countsong=Songsprintform.objects.all().filter(username=username,removesong='0', addsheetstatus='0',songsheetname=songsheetname,songprintstatus='1').count() songid = [] for i in printsong: songid.append(i.songprintid) recentsongs=SongList.objects.all().filter(id__in=songid) template_path = 'pdf.html' context = {'recentsongs':recentsongs} response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="songs.pdf"' template = get_template(template_path) html = template.render(context) pisa_status = pisa.CreatePDF(html, dest=response) if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response django template <html> <head> <title>Page Title</title> <meta charset="utf-8"> <style> div { column-count: 2; column-width: 300px; } </style> </head> <body> <div class="col-md-6"> {% for i in recentsongs %} <p class="float-left">{{i.body |linebreaks}}</p> {% endfor %} </div> </div> </body> </html> This is my code... Here I'm converting my Django template(html) page into pdf. All are Working fine but here my content are in Tamil. But here it displays as an Square box instead of Tamil Letters .whenever my click my button on see that pdf file it always shown as an square box. I don't Know why.Please help me... -
How to implement a specific parser (Chinese) for PostgreSQL full text search in Django?
I want to implement PostgreSQL full text search in Django 4.0. for Chinese language. The question already arise in 2010 but there wasn't any suitable solution and they had to move to SQL Server. In 2015 a PostgreSQL extension for full-text search of Chinese appeared (here). Is it possible to implement that parser using Django? Any reference/pointers on how to do it really appreciated. -
Can't get full url of Image Field Django Rest
I have two serializers: class AlbumImageSerializer(serializers.ModelSerializer): url = serializers.SerializerMethodField('get_url') def get_url(self, obj): return obj.image.url class Meta: model = AlbumImage fields = ['id', 'url'] class PhotoAlbumSerializer(serializers.ModelSerializer): photos = AlbumImageSerializer(many=True, read_only=True) class Meta: model = Pet fields = ('id', 'name', 'photos') And i read that to display full url of image it's enough to pass a request context to serializer call, like: serialized = SomeSerializer(some, context={"request": request}) And when you use ViewSet you don't need to do anything, DRF will automatically pass the request context while initializing the serializer. I am using ViewSets like: class PhotoAlbumViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, GenericViewSet): serializer_class = PhotoAlbumSerializer but still my get-request returns response like: "url": "/media/images/photo.jpg" How can i get "url": "127.0.0.1:8000/media/images/photo.jpg" In my case? -
Download and export data to CSV
I have managed to develop an export button which allows users to download all approved orders `def orders_download(request): response=HttpResponse(content_type='text/csv') response['Content- Disposition']='attachment;filename="all_orders.csv"' query=Order.objects.all() writer=csv.writer(response) writer.writerow(['DESCRIPTION','COST','QUANTITY','TOTAL_COST','CATEGORY','STATUS','DATE_ORDERED']) return `response its downloading but not returning all rows as required. what is it am missing? have tried looping but its returning one row multiple times -
How to implement 3x3 grid for listview in django?
I have a ListView for a blog with fields of title, text and image in the shape of a card. I want to display them in a grid but the default renders these items in vertical format. How to implement grid for these items? -
Call js function every time DjangoForm is loaded?
I have next form: class ExampleForm(forms.ModelForm): class Meta: model = ExampleModel fields = ['field1', 'field2', 'field3'] widgets = {'field1': forms.Select(attrs={'onchange': 'onchangeJsFunction()'})} So far i have been able to add onchange property to my select field that calls 'onchangeJsFunction()' every time 'field1' value is changed. My next goal is to add a function that is going to be executed every time form is loaded, and i am not sure how to do it. I have tried adding onload property to a input field this way: ... widgets = {'field_2': forms.TextInput(attrs={'onload': 'onloadJsFunction();'})} ... but it does not give any results so far. How am i supposed to execute certain JS function every time my Django Form is loaded? -
How to run a java script (or some) with ajax from a separate file?
I have several ajax scripts in the base body django template. I want to run them in a separate js file, but the scripts do not work from a file. My script in the body template (this is a working code.): <!--Add product to the cart after press Add button--> <script> $(document).on('click', '#add-button', function (e){ e.preventDefault(); var prodid = $('#add-button').val(); $.ajax({ type: 'POST', url: '{% url "add_cart" %}', data: { product_id: $('#add-button').val(), quantity: $('#qty').val(), csrfmiddlewaretoken: '{{csrf_token}}', action: 'POST' }, success: function (json) { document.getElementById('cart_icon_count').innerHTML = json.qty; }, error: function(xhr, errmsg, err) {} }); }) </script> Than delete script from body and copy in js file: my_js.js $(document).on('click', '#add-button', function (e){ e.preventDefault(); var prodid = $('#add-button').val(); $.ajax({ type: 'POST', url: '{% url "add_cart" %}', data: { product_id: $('#add-button').val(), quantity: $('#qty').val(), csrfmiddlewaretoken: '{{csrf_token}}', action: 'POST' }, success: function (json) { document.getElementById('cart_icon_count').innerHTML = json.qty; }, error: function(xhr, errmsg, err) {} }); }) and in the body: <script src="{% static 'js/my_js.js' %}"></script> The usual java script function works this way, but for some reason this script does not. Any ideas for running one or more of these scripts from a separate file? -
django-filter, how to use for manytomanyfiled
how can use django-filters for ManyToManyField class PostFilter(django_filters.FilterSet): title = CharFilter(widget=forms.TextInput(attrs={ "class": "form-control", "placeholder": "ady"}), field_name="title", lookup_expr="icontains") tagList = ModelChoiceFilter(field_name="tagList", queryset=Tag.objects.all(), widget=forms.Select( attrs={"class": "form-control"})) class Meta: model = Post fields = ["title", "tagList"] exclude = ["image", "like", "seen", "share"] -
firebase-admin adding a random alphanumeric key to the realtime database when using push()
I am using the Python firebase-admin library to integrate Django rest framework and Firebase Realtime storage. I am using the push() function to create a new child node. However, the function adds an alphanumeric key to each child. Is there a way I can avoid that and add my own custom keys to the data? See example below: def post(self, request): """Function to handle post requests Args: request (_type_): _description_ """ # Get the data to be posted from the request name = request.POST.get('name') age = request.POST.get('age') location = request.POST.get('location') # Set the reference to the database ref = db.reference('/') # Push the data to the database ref.push({"user1" : { 'Name': name, 'Age': age, 'Location': location }}) return JsonResponse({"message": "Data posted successfully"}, status=200) When I run this, the node is created as follows { "data": { "-NNzIPh4SUHo6FLhs060": { "user1": { "Age": "20", "Location": "US", "Name": "Dummy name 2" } }, "user2": { "Age": "22", "Location": "count1", "Name": "Dummy 1" } } } The -NNzIPh4SUHo6FLhs060 key is created which I want to customize. -
Vs Code + Python : What means VS (Pylance) autocomplete suggestion for get_success_url()
When I define `get_success_url' in my views, if I accept Pylance Autocomplete suggestion, I got this : def get_success_url(self) -> str: return super().get_success_url() Didn't find anywhere how to use this. By my side, I'm use to do : def get_success_url(self, **kwargs): return reverse_lazy('name_space:url_name', kwargs={'pk': foo}) How to (can I) use pylance's suggestion to achieve the same result as my method -
i need to be solve these python dgango errors
Using the URLconf defined in Organic_Species.urls, Django tried these URL patterns, in this order: [name='index'] signup [name='signup'] admin/ ^media/(?P.*)$ The current path, signup.html, didn’t match any of these i need to solve these errors -
Cannot serve media files with nginx
I am using django-cookiecutter for project, I cannot serve media files with nginx: and not getting any errors, django works fine. I am new to docker, I think problem with volumes idk as django docker files are auto created. Searched some questions but didn't help. Dockerfile ARG PYTHON_VERSION=3.10-slim-bullseye FROM python:${PYTHON_VERSION} as python FROM python as python-build-stage ARG BUILD_ENVIRONMENT=production # Install apt packages RUN apt-get update && apt-get install --no-install-recommends -y \ # dependencies for building Python packages build-essential \ # psycopg2 dependencies libpq-dev COPY ./requirements . # Create Python Dependency and Sub-Dependency Wheels. RUN pip wheel --wheel-dir /usr/src/app/wheels \ -r ${BUILD_ENVIRONMENT}.txt FROM python as python-run-stage ARG BUILD_ENVIRONMENT=production ARG APP_HOME=/app ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV BUILD_ENV ${BUILD_ENVIRONMENT} WORKDIR ${APP_HOME} RUN addgroup --system django \ && adduser --system --ingroup django django RUN apt-get update && apt-get install --no-install-recommends -y \ # psycopg2 dependencies libpq-dev \ # Translations dependencies gettext \ # cleaning up unused files && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \ && rm -rf /var/lib/apt/lists/* # copy python dependency wheels from python-build-stage COPY --from=python-build-stage /usr/src/app/wheels /wheels/ # use wheels to install python dependencies RUN pip install --no-cache-dir --no-index --find-links=/wheels/ /wheels/* \ && rm -rf /wheels/ COPY --chown=django:django ./compose/production/django/entrypoint … -
Raw query must include the primary key from django
grade = request.GET.get('grade') year = request.GET.get('year') subject = request.GET.get('subject') marks_sheet1=Marks_sheet.objects.raw("select id,unique_id,student_name,attendance,%s FROM school_marks_sheet a, school_marks_details b WHERE term = 'Term1' and a.grade = %s and a.year=%s and a.unique_id = b.details_id_id order by student_name",[subject,grade,year]) I got this issue when I try this code. can anyone solve this. I want to take the output according to the query -
How to use Django get request value from sql query
I tried following code grade = request.GET.get('grade') year = request.GET.get('year') subject = request.GET.get('subject') marks_sheet=Marks_sheet.objects.raw("select id,unique_id,student_name,attendance,%s FROM school_marks_sheet a, school_marks_details b WHERE term = 'Term3' and a.grade = %s and a.year=%s and a.unique_id = b.details_id_id order by student_name",[subject,grade,year]) This query isn't work. How can I use subject name in select query