Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
form fields do not get filled in DJANGO
I have this model: class Tarea(models.Model): numtar = models.AutoField(primary_key=True) cliente = models.ForeignKey(User, related_name='user_cliente', null=True, on_delete=models.DO_NOTHING) acargo = models.ForeignKey(User, related_name='user_acargo', null=True, on_delete=models.DO_NOTHING) asignado = models.ForeignKey(User, related_name='user_asignado', null=True, on_delete=models.DO_NOTHING) descorta = models.CharField(max_length=140) deslarga = models.TextField(max_length=8195) estado = models.ForeignKey(Estado, null=True, on_delete=models.SET_NULL) tipo = models.ForeignKey(Tipos, null=True, on_delete=models.SET_NULL) prioridad = models.ForeignKey(Prioridad, null=True, on_delete=models.SET_NULL) creacion = models.DateTimeField(default=timezone.now) revision = models.DateTimeField(auto_now=True) cierre = models.DateTimeField(null=True, blank=True) # objects = models.Manager() # el gestor por defecto de objetos leídos # listado = ReqMgr() # Mi gestor de lecturas class Meta: verbose_name = "Tarea" verbose_name_plural = "Tareas" and this view: @login_required(login_url='/login') def newincid_view(request): form = newincidForm() form.estado = Estado.objects.get(estado='Abierta') form.tipo = Tipos.objects.get(tipo='Incidencia') form.creacion = timezone.now() if request.method == 'POST': form = newincidForm(request.POST) if form.is_valid(): instancia = form.save(commit=False) instancia.save() return redirect('vacia') return render(request, 'incid/newincid.html', {'form': form}) and this form: class newincidForm(ModelForm): class Meta: model = Tarea exclude = ['numtar', 'revision', 'cierre'] def __init__(self, *args, **kwargs): super(newincidForm, self).__init__(*args, **kwargs) self.fields['descorta'].widget.attrs['class'] = 'form-control no-resize' self.fields['deslarga'].widget.attrs['class'] = 'form-control no-resize autogrowth' The form gets rendered and I fill all the fields but I always get and error "field is required" for "estado", "tipo" and "creacion". Of course form.is valid is never True and nothing gets written. Why is it? -
Django 'endfor', expected 'endblock'
I am attempting to learn Django but keep receiving the error " 'endfor', expected 'endblock'. Did you forget to register or load this tag? " when I add the {% for key,value in price.DISPLAY.items %} {{ key }} {% endfor %} part of the code. How can I fix this? Any help would be great thanks. home.html {% extends 'base.html' %} {% block content %} {% for key,value in price.DISPLAY.items %} {{ key }} {% endfor %} <br /> <br /> {{ price.DISPLAY }} <div class="jumbotron"> <h1 class="display-4">Welcome</h1> </div> <div class="container"> <div class="row"> {% for info in api.Data %} <div class="card" style="width: 18rem"> <img src="{{info.imageurl}}" class="card-img-top" alt="{{info.source}}" /> <div class="card-body"> <h5 class="card-title">{{info.title}}</h5> <p class="card-text">{{info.body}}</p> <a href="{{info.url}}" class="btn btn-secondary" target="_blank" >Read more</a > </div> </div> {% endfor %} </div> </div> {{ api.Data }} {% endblock content %} -
Unsuccessfully trying to migrate my app using python manage.py migrate
Unsuccessfully trying to migrate my app using python manage.py migrate then python manage.py makemigration but nothing is showing up in the terminal. python manage.py migrate python manage.py makemigrations Migrations for 'my_app': ^CBrittanys-Air:cragslist_app brittany$ python manage.py migrate Traceback (most recent call last): File "manage.py", line 35, in "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Brittanys-Air:cragslist_app brittany$ python manage.py migrate Traceback (most recent call last): File "manage.py", line 39, in execute_from_command_line(sys.argv) NameError: name 'execute_from_command_line' is not defined Brittanys-Air:cragslist_app brittany$ python manage.py migrate Brittanys-Air:cragslist_app brittany$ python manage.py makemigrations -
How can I divide the request.POST to fit 2 distinct forms in django?
I would like to know whether it is possible to divide the request.POST attribute in django in order to fill 2 or more distinct forms. Because my Main model operates in a form that it is related to 2 child models with a ManyToManyField(), I want to create more instances of this model using forms. A quick Example: class ChildModelOne(models.Model): title_one = models.CharField(max_length = 64) list = models.ManyToManyField(otherModel, blank = True, default = None) def __str__(self): return self.title_one class ChildModelTwo(models.Model): title_two = models.CharField(max_length = 64) list = models.ManyToManyField(otherModel, blank = True, default = None) def __str__(self): return self.title_two class ParentModel(models.Model): name = models.CharField(max_length = 128, default = 'My Name', null = True, blank = True) p_modelOne = models.ForeignKey(ChildModelOne, on_delete = models.CASCADE,default = None, blank = True, null = True ) p_modelTwo = models.ForeignKey(ChildModelTwo, on_delete = models.CASCADE,default = None, blank = True, null = True ) and now my forms: class Register_ChildModelOne(forms.ModelForm): class Meta: model = ChildModelOne fields = ['title_one', 'list'] class Register_ChildModelTwo(forms.ModelForm): class Meta: model = ChildModelTWo fields = ['title_two', 'list'] class Register_ParentModel(forms.ModelForm): class Meta: model = Routine fields = [ 'name','p_modelOne', 'p_modelTwo'] and in my templates the forms are inherited as follows : context { 'form_One' : Register_ChildModelOne(), 'form_Two' … -
Django redirect within method
I have the following: def wiki(request,title): entries = [] entry = util.get_entry(title) if entry != None: markdowner = Markdown() entry = markdowner.convert(entry) entries.append(entry) return render(request, "encyclopedia/entry.html", { "title": title, "entries": entries, }) def search(request): search=request.GET.get('q') entries = util.list_entries() for entry in entries: if search == entry: ######################################### entries = [] entry = util.get_entry(search) markdowner = Markdown() entry = markdowner.convert(entry) entries.append(entry) return render(request, "encyclopedia/entry.html", { "title": search, "entries": entries, }) ####################################### possible=( [str for str in entries if (search in str )] ) print(possible) return render(request, "encyclopedia/search.html") if search == entry: is there some way to redirect to or call wiki(request,title)? and thereby be able to eliminate the code between the hash marks? -
access to the coupon information in the webbook in stripe
I am using coupon in stripe checkout session. it works fine but I need to store the information once checkout successfully completed in my server. I am thinking of either of the following potential solutions: 1- pass the info to webhook: @csrf_exempt def stripe_webhook(request, **myextrainfo**): 2- somehow find the used coupon info in the webhook event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) I don't know if the first is doable and about the second, I can almost retrieve all the information like customer, product, total, subtotal but I cannot find coupon info. here is information that I can retrieve: session = event['data']['object'] line_items = stripe.checkout.Session.list_line_items(session['id'], limit=1) print(line_items) print(line_items["data"][0]["price"]["id"]) print(line_items["data"][0]["price"]["product"]) print(line_items["data"][0]["price"]["recurring"]["interval"]) print(line_items["data"][0]["price"]["recurring"]["interval_count"]) I appreciate if someone can help me. -
Heroku + Django : Restarting a dyno every 15 min
I have a Django website hosted on Heroku. I need to restart 1 dyno "clock" every 15 minutes. Through Heroku CLI, this can be done through the command line: heroku dyno:restart clock.1 But I can't seem to automate it from within the Django app. I don't know if a Django scheduled job/management command can execute a Heroku CLI command. Currently my back-up solution is to have : one .bat to 1) Activate my venv 2) execute heroku dyno:restart clock.1 one Windows Task Scheduler to launch my .bat every 15 min. (Yes... my laptop has been on for months now) What I want is a cronjob inside my Django app, which would restart this dyno every 10 min. Or anything like that ? -
Docker Flask File not running
Been a while since I used docker and having issues getting my Flask server up and running, the django one in running file. I'm sure I'm doing something wrong related to my directory. Can anyone help me and identify the issue? Failure is: backend_1 | python: can't open file '/backend/manage.py': [Errno 2] No such file or directory frontend_1 | Traceback (most recent call last): frontend_1 | File "frontend/app.py", line 4, in <module> frontend_1 | from frontend.utils import register_request, login_request frontend_1 | ModuleNotFoundError: No module named 'frontend' pycharmprojects_backend_1 exited with code 2 pycharmprojects_frontend_1 exited with code 1 This is my directory structure: ├── backend │ ├── db.sqlite3 │ ├── DjangoRestfulApi │ │ ├── asgi.py │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── __init__.cpython-39.pyc │ │ │ ├── settings.cpython-36.pyc │ │ │ ├── settings.cpython-39.pyc │ │ │ ├── urls.cpython-36.pyc │ │ │ ├── urls.cpython-39.pyc │ │ │ ├── wsgi.cpython-36.pyc │ │ │ └── wsgi.cpython-39.pyc │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── Dockerfile │ ├── manage.py │ ├── requirements.txt │ └── users │ ├── apps.py │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-36.pyc │ │ … -
How to update and delete comments in Django
I am struggling with updating and deleting comments created by users, I have created Class Based Views for the comments but I am not sure how to proceed as I am getting errors The error I am currently receiving is: FieldError at /blog/sdsdssds/update_comment/ Cannot resolve keyword 'slug' into field. Choices are: content, created, id, post, post_id, updated, user, user_id Any ideas how to fix this error and what is the reason for it? Here is models.py class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField(max_length=300, validators=[validate_comment_text]) Here is the views.py class PostCommentCreateView(LoginRequiredMixin, CreateView): model = Comment form_class = CommentForm def form_valid(self, form): post = get_object_or_404(Post, slug=self.kwargs['slug']) form.instance.user = self.request.user form.instance.post = post return super().form_valid(form) def form_invalid(self, form): return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('blog:post-detail', kwargs=dict(slug=self.kwargs['slug'])) class PostCommentUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Comment fields = ['content'] # What needs to appear in the page for update template_name = 'blog/post_detail.html' # <app>/<model>_<viewtype>.html def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) def form_invalid(self, form): return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('blog:post-detail', kwargs=dict(slug=self.kwargs['slug'])) def test_func(self): comment = self.get_object() if self.request.user == comment.user: return True return False class PostCommentDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Comment template_name = 'blog/postcomment_confirm_delete.html' # <app>/<model>_<viewtype>.html def test_func(self): comment = … -
How can I find the current users primary key to check if it matches a notes pk?
I am working on an application that stores data on different artists, venues, and notes the user can create for shows. I am currently trying to implement a feature to delete an existing note based off it's PK and the users PK associated with that note. I have most the work done but I don't know how they are storing the current logged in users PK to check before deleting. Here is what I have so far and links for reference: https://github.com/claraj/lmn/blob/master/lmn/views/views_notes.py # Note related paths path('notes/latest/', views_notes.latest_notes, name='latest_notes'), path('notes/detail/<int:note_pk>/', views_notes.note_detail, name='note_detail'), path('notes/for_show/<int:show_pk>/', views_notes.notes_for_show, name='notes_for_show'), path('notes/add/<int:show_pk>/', views_notes.new_note, name='new_note'), path('notes/detail/<int:show_pk>/delete', views_notes.delete_note, name='delete_note'), https://github.com/claraj/lmn/blob/master/lmn/urls.py # Delete note for show @login_required def delete_note(request, show_pk): # I need to grab the existing note PK and user PK associated with that note # Then check if the current user matches the PK associated with that note to delete or return a 403 status code. if note.user == request.user: note.delete() return redirect('latest_notes') else: return HttpResponseForbidden https://github.com/claraj/lmn/blob/master/lmn/templates/lmn/notes/note_list.html # Grabs PK for specific note <form action="{% url 'delete_note' note.pk %}" method="POST"> {% csrf_token %} <button type="submit" class="delete">Delete</button> </form> -
django.db.utils.ProgrammingError: relation "knox_authtoken" does not exist
I'm getting "django.db.utils.ProgrammingError: relation "knox_authtoken" does not exist" error. Actually I'm writing an API in django using restframework. And I'm getting 500 Internal server error over the line AuthToken.objects.create(user)[1] and my import for the AuthToken is from knox.models import AuthToken And my error logs are: Traceback (most recent call last): File "C:\Users\meesn\PycharmProjects\marketkonnectapi\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "knox_authtoken" does not exist LINE 1: INSERT INTO "knox_authtoken" ("digest", "token_key", "salt",... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\meesn\PycharmProjects\marketkonnectapi\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\meesn\PycharmProjects\marketkonnectapi\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\meesn\PycharmProjects\marketkonnectapi\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\meesn\PycharmProjects\marketkonnectapi\venv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\meesn\PycharmProjects\marketkonnectapi\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\meesn\PycharmProjects\marketkonnectapi\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\meesn\PycharmProjects\marketkonnectapi\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\meesn\PycharmProjects\marketkonnectapi\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\meesn\PycharmProjects\marketkonnectapi\auths\views.py", line 43, in post token = AuthToken.objects.create(user)[1] File "C:\Users\meesn\PycharmProjects\marketkonnectapi\venv\lib\site-packages\knox\models.py", line 20, in create instance = super(AuthTokenManager, self).create( File "C:\Users\meesn\PycharmProjects\marketkonnectapi\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\meesn\PycharmProjects\marketkonnectapi\venv\lib\site-packages\django\db\models\query.py", line 447, in create obj.save(force_insert=True, … -
How to step wise post data to an object using the Django-Rest Framework?
I want to post an object with Django-Rest Framework to my backend. The object contains multiple nested objects, and the user inserts this information setp-wise via a React JS frontend. class Story (models.Model): title = models.CharField(max_length=100,blank=False) content = models.TextField(blank=False) date_posted = models.DateTimeField(default=timezone.now) place = models.ForeignKey(Place, on_delete=models.PROTECT, null=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) images = models.FileField(upload_to='audio_stories/',validators=[validate_file_extension_image], blank=False) audio = models.FileField(upload_to='audio_stories/',validators=[validate_file_extension_audio], blank=False) I now wonder how it is possible to send the data to the server step by step. Is there a way to initiate a story object at the very beginning of the creation process to generate its primary key and then add the other data to this key step by step, e.g. images and audio? I've already searched for the right term in the Django documentation, but I'm having difficulties to approach this topic. I am happy for any clarification. -
Login form using django
I'm doing a Python user login, using Django. I'm trying to create authentication my way, checking in my db if username exists and password is correct. When I type username and password,and both are correct, login does nothing, just reload login page. The same issue happens when I type wrong username and/or password, login page just reload, but in this case should show an error message. These are my forms.py and views.py: forms.py def login_view(request): title = 'LOGIN' if request.user.is_authenticated: return redirect('board.html') if request.method =='POST': form = UserLoginForm(request=request, data=request.POST) if form.is_valid(): username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.info(request, "You are now logged in as {username}") return redirect('/') else: messages.error(request, "Invalid username or password.") else: messages.error(request, "Invalid username or password.") form = UserLoginForm() return render(request=request, template_name="/login.html", context={"form": form}) views.py class UserLoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError('No user found with this username') if not user.check_password(password): raise forms.ValidationError('Wrong password') if not user.is_active: raise forms.ValidationError('This user is not active') return super(UserLoginForm, forms).clean(*args, **kwargs) Where am I wrong? I'm … -
Making multiple filters in function filter() (Django)
What I want to do is to have multiple values to filter out the data. I want to have ResourcePost objects with resource_category with values of user.helpseekerprofile.rc1 user.helpseekerprofile.rc2 and user.helpseekerprofile.rc3. So I tried like below: def message_list_view(request): user = request.user def filter_watchlist(post): filtered = ResourcePost.objects.all().filter(resource_category=user.helpseekerprofile.rc_1)\ + ResourcePost.objects.all().filter(resource_category=user.helpseekerprofile.rc_2)\ + ResourcePost.objects.all().filter(resource_category=user.helpseekerprofile.rc_3) if post in filtered: return True else: return False post_list = ResourcePost.objects.all().filter(filter_watchlist).order_by("-date_created") page = request.GET.get("page", 1) paginator = Paginator(post_list, 20) try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) timestamp_now = datetime.datetime.now() context = { "mapbox_access_token": "pk." + os.environ.get("MAPBOX_KEY"), "timestamp": timestamp_now, "posts": posts, } return render(request, "donation/messages_home.html", context) However, TypeError came out saying "cannot unpack non-iterable function object". How can I fix this? -
Creating an API with query string parameters
This code was used to create an API that could be searched through with start and end parameters. import time from django.http import JsonResponse from django.shortcuts import render # Create your views here. def index(request): return render(request, "posts/index.html") def posts(request): # Get start and end points start = int(request.GET.get("start") or 0) end = int(request.GET.get("end") or (start + 9)) # Generate list of posts data = [] for i in range(start, end + 1): data.append(f"Post #{i}") # Artificially delay speed of response time.sleep(1) # Return list of posts return JsonResponse({ "posts": data }) It's pretty basic and I am trying to replicate it but I would like to use this with a QuerySet of posts. I'm finding it quite difficult to work my way around this though. My first attempt: def posts_search(request): start = int(request.GET.get("start") or 0) end = int(request.GET.get("end") or (start + 9)) posts = Post.objects.all() data = [] for i in range(start, end + 1): for post in posts: data.append(post) time.sleep(1) return JsonResponse({ "posts": data }) But I got this TypeError: Object of type Post is not JSON serializable So for my second attempt, I altered the JsonResponse so it reads: return JsonResponse([post.serialize() for post in data], safe=False) On … -
Django insert pandas dataframe into model filefield
Closed. This question needs details or clarity. It is not currently accepting answers. Add details and clarify the problem you’re solving. This will help others answer the question. You can edit the question or post a new one. Closed 12 hours ago. (Private feedback for you) in Django I have multiple dataframes I want to insert df into the model as file field ( the target to add download links in html to down load those dataframes as Excel files ) I tried the below in model file from django.db import models class Script_files_mod(models.Model): title = models.CharField(max_length=500,blank=True,null=True) type_operation = models.CharField(max_length=500,blank=True,null=True) attachment = models.FileField(upload_to='attachments/',) inside view.py from django.core.files.base import ContentFile from .models import Script_files_mod df1= df.to_csv() updated_file = ContentFile(df1) Script_files_mod.objects.create(title='BB',type_operation='before_merge',updated_file ) but file return empty -
CSS on my index.html is not showing any changes. Static image is also not appearing on my help.html. All details are available in question
This is my site on PythonAnywhere: http://fatimatestpro.pythonanywhere.com/ I have a static folder under my main project folder. I have done setting for static files in settings.py, My folder tree is emailpro --emailpro ----settings.py --emailapp --templates ----emailapp ------index.html --static ----images ------djangoguitar.jpg ----css ------first.css In settings.py, I have created STATIC_DIR = os.path.join(BASE_DIR, 'static') variable and passed it at bottom as STATIC_URL = '/static/' STATICFILES_DIRS =[ STATIC_DIR, ] My first.css has following code: h1{ color: red; } body { background-color: coral; } and index.html has the following code: <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <link rel="stylesheet" href="{% static "css/first.css" %}"> <meta charset="utf-8"> <title>Index</title> </head> Also my static image is also not working. With the same above mentioned settings, I am displaying the image in help.html. the code is below: <!DOCTYPE html> {% load staticfiles %} <html lang="en" dir="ltr"> <head> <link rel="stylesheet" href="images/djangoguitar.jpg"> <!"{% static "css/first.css" %}">> <meta charset="utf-8"> <title> Help </title> </head> Can someone help me in displaying image and CSS changes? Thanks -
Cannot fix Django NoReverseMatch error despite URL being withing urls.py
Before I go into detail, here is the line from the html document that results in the error, as well as views.py and urls.py: <input class="search" type="text" name="q" placeholder="Search Encyclopedia" action="{% url 'encyclopedia:findpage' %}" method="get"> (Yes there is a space betweeen url and 'encyclopedia:findpage') views.py findpage function: def findpage(request, name): pages = util.list_entries() wanted_pages = set() wanted_page = None for page in pages: if not wanted_page and page == name: wanted_page = util.get_entry(name) continue if name in page: wanted_pages.add(page) if wanted_page: return render(request, 'encyclopedia/page.html', { "title": name, "entry": wanted_page }) if wanted_pages and not wanted_page: return render(request, 'encyclopedia/index.html', { "entries": wanted_pages }) else: return render(request, 'encyclopedia/noresults.html') urls.py: from django.urls import path from . import views app_name = "encyclopedia" urlpatterns = [ path("", views.index, name="index"), path("<str:name>", views.wikipage, name="wikipage"), path("<str:name>", views.findpage, name='findpage'), path("create", views.newpage, name="newpage") ] When I run the Django project, I get a NoReverseMatch at /. The error from the webpage reads: In template /home/quinn/Desktop/cs50web/pset1/wiki/encyclopedia/templates/encyclopedia/layout.html, error at line 17 Reverse for 'findpage' with no arguments not found. 1 pattern(s) tried: ['(?P<name>[^/]+)$'] Line 17 is the piece of html I left at the top of this page. I've checked numerous sources in an attempt to fix this, but I cannot figure … -
How to fix error in creating nested comment?
I'm working on creating comment api for my project. this is my comment model: class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='comments') parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True,blank=True, related_name='replys') body = models.TextField() created = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.user} - {self.body[:30]}' class Meta: ordering = ('-created',) my serializers: class CommentSerializer(serializers.ModelSerializer): loadParent = serializers.SerializerMethodField("loadPrentData") def loadPrentData(self, comment): comments = Comment.objects.filter(parent=comment) comments_ser = CommentSerializer(comments, many=True).data return comments_ser class Meta: model = Comment fields = ['id', 'user', 'product', 'parent', 'body', 'created', 'loadParent'] class ProductSerializer(serializers.ModelSerializer): comments = serializers.SerializerMethodField("loadProductComments") def loadProductComments(self, _product): _comments = Comment.objects.filter(product=_product, parent__isnull=True) _comments_ser = CommentSerializer(_comments, many=True, read_only=True).data return _comments_ser class Meta: model = Product fields = ['id', 'category', 'name', 'slug', 'image_1', 'image_2', 'image_3', 'image_4', 'image_5', 'description', 'price', 'available', 'created', 'updated', 'comments'] lookup_field = 'slug' extra_kwargs = { 'url': {'lookup_field': 'slug'} } and this is my view for creating comment: @api_view(['POST']) def AddComent(request, parent_id=None): parent = request.data.get("parent_id") serializer = CommentSerializer(data=request.data) if serializer.is_valid(): if parent is not None: comment = Comment.objects.create(user=request.user, product=serializer.validated_data['product'], parent_id=serializer.validated_data['parent'], body=serializer.validated_data['body']) else: comment = Comment.objects.create(user=request.user, product=serializer.validated_data['product'], body=serializer.validated_data['body']) comments_ser = CommentSerializer(comment,many=False, read_only=True).data return Response(comments_ser, status=status.HTTP_200_OK) return Response(status=status.HTTP_400_BAD_REQUEST) when i go to the url i can not create comment this page shows and i can't post comment : this is … -
How to return list of dictionaries in the string representation format defined in Django Model?
I have a queryset, which returns the data I want after the application of a filter. This queryset gives me the data only given in __str__() method of the model. (However the type of the structure is <class 'django.db.models.query.QuerySet'> which I do not want.) Currently, I can only return a queryset, If I try using a serializer, it returns all kinds of metadata which I did not include in __str__() method of my class. .values() creates dictionaries that also includes metadata like "id" which I did not include in str() method of my class. I need a way to transform my QuerySet into a list of dictionaries (dictionaries which include model data given in __str__() method of the model class) -
Python Django : adding constrained field value into CBV view without all fields displayes
I am using a ClassBasedView, and asking Django to remove some fields in the auto-generated form (letting out : owner / owner_card_nb ) : class BristolCreateView(LoginRequiredMixin, CreateView): model = Bristol fields = [ "catalogue" , "recommanded_age" , "title" , "url" , "path_illustration" , "description" ] #letting out : owner / owner_card_nb I have to calculate the field owner_car_nb when the form is sent to the server. owner_card_nb= Bristol.objects.filter(owner=self.request.user) How can I push this data into the form which has been displayed in the html without the owner, neither the owner_car_nb value ? I tried several methods : Adding get_initial to the CBV : class BristolCreateView(LoginRequiredMixin, CreateView): def get_initial(self): return {'owner': self.request.user.id, 'owner_card_nb': 1} But the webpage still fails : IntegrityError at /bristol/create NOT NULL constraint failed: bristol_bristol.owner_id using form_valid : def form_valid(self, form): form.instance.created_by = self.request.user form.instance.owner_card_nb= Bristol.objects.filter(owner=self.request.user) return super(BristolCreateView, self).form_valid(form) But the webpage still fails : IntegrityError at /bristol/create NOT NULL constraint failed: bristol_bristol.owner_id What do I do wrong ? How can we set up values in a CBV form for non-displayed fields ? -
Check if element is in a model - Django templates
i'm trying to make a like button. And everything works fine except for the fact that i can't check (inside the template) if something is already liked by the user. In other words, i can't check for an existing row in the database. Im trying this for the template: If the user likes the post. That post shows a filled heart, otherwise it shows only a heart contour {% for post in posts %} {% if post in likelist %} <i class="fa fa-heart like" data-id="{{ post.id }}" id="like-{{ post.id }}" style="color:red;"></i> {% else %} <i class="fa fa-heart-o like" data-id="{{ post.id }}" id="like-{{ post.id }}" style="color:red;"> </i> {% endif %} {% endfor %} But the if statement is giving always False, even when the user actually likes the post. Here is the model: class Likelist(models.Model): user = models.ForeignKey('User', on_delete=models.CASCADE, related_name='liker') likes = models.ForeignKey('Posts', on_delete=models.CASCADE, related_name='likes') def __str__(self): return f"{self.user} likes {self.likes}" And i'm passing the context in views.py through render return render(request, "network/profile.html", { #[...]some other contexts "posts": Posts.objects.filter(user=user_id).order_by('-timestamp'), "likelist": Likelist.objects.filter(user=request.user), }) If i try to print it in a HTML tag ( {{likelist}} or {{posts}} ) the querysets appears so the context is passing fine. I don't know why the … -
Django static files don't load on production
I'm developping a Django project on windows but my production server is an ubuntu vps. All worked fine untill I add static files. It works fine on develoment (windows), but on production, I have [WARNING]: Not Found: /static each time I try to load a page. So the site works, there's just no css nor images on production. I've tryed the solutions given here : Django - Static file not found or here : Django: Not Found static/admin/css But none of them worked on my side. Here is my tree : my project In my settings.py, I have STATIC_URL = '/static/' I also have this kind of headers in my htmls to load static files: html Is there a different way of doing when adding static files on ubuntu rather than on windows ? -
How can i solve Django error Field 'id' expected a number but got ObjectId('5fb024de125430062daac949').?
I'm using django and mondogb for my project and keep getting this error then trying to register a new user. Here's my code: forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.forms import ValidationError class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = {"email", "username", "password1", "password2"} def clean_email(self): email = self.cleaned_data['email'] if not email.endswith('@student.upt.ro'): raise ValidationError('Email domain is not valid') return email def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.set_password(self.cleaned_data['password1']) user.is_active = False if commit: user.save() return user views.py def login_and_registration(request): register_form = NewUserForm() login_form = AuthenticationForm() if request.method == "POST": if 'login' in request.POST: login_form = AuthenticationForm(request=request, data=request.POST) print('login_form', login_form) if login_form.is_valid(): print('LOGIN HERE') username = login_form.cleaned_data.get('username') password1 = login_form.cleaned_data.get('password') user = authenticate(username=username, password1=password1) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}") return redirect('home') else: print(login_form.errors) messages.error(request, "Invalid credentials.") else: print(login_form.errors) messages.error(request, "Invalid credentials.") elif 'register' in request.POST register_form = NewUserForm(request.POST) if register_form.is_valid(): user = register_form.save() login(request, user) print(register_form.errors) messages.success(request, "Registration successful.") return redirect(reverse(home)) else: messages.error(request, "Unsuccessful registration. Invalid information.") context = {'login_form': login_form, 'register_form': register_form} return render(request, 'StartPage/reglog.html', context) After I complete the form and press submit I get the following … -
Django ORM postgresql type casting
I am trying to use Django's reverse generic relation for accessing and filtering related objects via Django's ORM. See below declared models: from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models class Status(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Package(models.Model): name = models.CharField(max_length=500) status = models.ForeignKey(Status, on_delete=models.PROTECT) hst_entries = GenericRelation("testapp.StatusHistory", related_query_name="package") def __str__(self): return self.name class StatusHistory(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT) object_id = models.TextField() object = GenericForeignKey("content_type", "object_id") status = models.ForeignKey(Status, on_delete=models.PROTECT) entry_added = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.content_type} - {self.object_id}: {self.status.name}" As you see there is generic relation between Package and StatusHistory models. For accessing related packages from StatusHistory model I tried: StatusHistory.objects.filter(package__name__startswith="pack") And result: ProgrammingError: operator does not exist: text = integer LINE 1: ...kage" ON ("myapp_statushistory"."object_id" = "myapp... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. I understand that PostgreSQL is complaining about type mismatch between object_id (of StatusHistory model) and id (of Package model) fields. This mismatch can be solved by PostgreSQL cast operator :: as below: ### WRONG join myapp_package on (myapp_statushistory.object_id = my_app_package.id) ### RIGHT join myapp_package on (myapp_statushistory.object_id = my_app_package.id::varchar) Is there possible way to make …