Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Page not found (404) No MenuCategories matches the given query
I created a Django application, the essence is this: data is added through the admin panel, which is then displayed on the main page. I added the data, but they are not displayed on the page; instead an error is displayed: Page not found (404). No MenuCategories match the given query. How can this be fixed? Here is my code in models.py: from django.db import models class MenuCategories(models.Model): name = models.CharField(max_length=50) parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) explicit_url = models.CharField(max_length=100, blank=True, null=True, unique=True) def __str__(self): return self.name def children(self): return self.menucategories_set.all() def get_elder_ids(self): if self.parent: return self.parent.get_elder_ids() + [self.parent.id] else: return [] -
Django: No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model in django?
after updating some fields in my model and hit the update button, i get this error that says No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model. I have am redirecting too after the update is done, but it seem not to be redirecting to that url anylonger, NOTE: the url still exists and works fine what could the problem be here? class ProductInline(): form_class = PredictionForm model = Predictions template_name = "core/create/create_bet.html" def form_valid(self, form): named_formsets = self.get_named_formsets() if not all((x.is_valid() for x in named_formsets.values())): return self.render_to_response(self.get_context_data(form=form)) self.object = form.save(commit=False) self.object.user = self.request.user self.object.current_amount = self.object.amount self.object.save() for name, formset in named_formsets.items(): formset_save_func = getattr(self, 'formset_{0}_valid'.format(name), None) if formset_save_func is not None: formset_save_func(formset) else: formset.save() messages.success(self.request, "Your bet have been created.") return redirect('core:dashboard') def formset_variants_valid(self, formset): """ Hook for custom formset saving.. useful if you have multiple formsets """ variants = formset.save(commit=False) # self.save_formset(formset, contact) # add this, if you have can_delete=True parameter set in inlineformset_factory func for obj in formset.deleted_objects: obj.delete() for variant in variants: variant.predictions = self.object variant.save() class PredictionUpdate(ProductInline, UpdateView): def get_context_data(self, **kwargs): ctx = super(PredictionUpdate, self).get_context_data(**kwargs) ctx['named_formsets'] = self.get_named_formsets() return ctx def get_current_object(self, id): prediction = Predictions.objects.get(id=id) … -
Django Docker ElasticBeanstalk fails
I'm new to docker and eb deployment, I want to deploy django with docker on eb here's what I did so far created a Dockerfile # Pull base image FROM python:3.9.16-slim-buster # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apt-get update &&\ apt-get install -y binutils libproj-dev gdal-bin python-gdal python3-gdal libpq-dev python-dev libcurl4-openssl-dev libssl-dev gcc # install dependencies COPY . /code WORKDIR /code/ RUN pip install -r requirements.txt # set work directory WORKDIR /code/app then in docker-compose.yml version: '3.7' services: web: build: . command: python /code/hike/manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 volumes: - .:/code it runs locally, but on deployment it fails and when I get to logs, it says pg_config is required to build psycopg2 from source. like it's not using the Dockerfile, I read somewhere I should set Dockerrunder.aws.json but I've no idea what to write in it! -
Django: How to populate model field value using another field in django model?
I want to auto-populate a Model field with data from another field, according to the value of that field, i will then auto add a new value the empty field. class Predictions(models.Model): amount = models.DecimalField(max_digits=999999999, decimal_places=2, default=0.00) current_amount = models.DecimalField(max_digits=999999999, decimal_places=2, default=0.00) def save(self, *args, **kwargs): if self.amount: self.current_amount = self.current_amount super(Predictions, self).save(*args, **kwargs) As you can see i have overridden the save method and assigned the value of current_amount to amount, Now the problem is this, when a user want to update this model, i don't want the current_amount to still be set to the amount, some calculation would be done on the curren_amount, so i want the new values for current_amount to remain. So I thought of doing this in the create view and not override the save method This is what i came up with NOTE: I am peforming some other operations in the code, so it might be a little long (the code). class ProductInline(): form_class = PredictionForm model = Predictions template_name = "core/create/create_bet.html" def form_valid(self, form): named_formsets = self.get_named_formsets() if not all((x.is_valid() for x in named_formsets.values())): return self.render_to_response(self.get_context_data(form=form)) # self.object = form.save() # new_form = form.save(commit=False) # new_form.user = self.request.user # self.object = new_form.save() self.object … -
ValueError at /state/ Field 'id' expected a number but got 'None'
I am getting this error and i have tried typecasting to change it to an integer but it still gives an error. I don't know what's wrong with the code and i am stuck here from past 30 minutes. Can someone help? urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', cview.Insertrecord), path('country/', lview.Insertrecord), path('state/', lview.Insertrecord_state), ] models.py class customer_state(models.Model): parent_id=models.ForeignKey(customer_location, on_delete=models.CASCADE) name=models.CharField(max_length=100) status=models.CharField(max_length=100, default='nil') added_by=models.CharField(max_length=100, default=1) updated_by=models.CharField(max_length=100, default=1) created_on=models.CharField(max_length=100) updated_on=models.CharField(max_length=100) class Meta: db_table="customer_state" def __str__(self): return self.name def save(self, *args, **kwargs): self.created_on = get_current_datetime_str() self.updated_on = get_current_datetime_str() super().save(*args, **kwargs) views.py def Insertrecord_state(request): # Define the parent_id variable parent_id = None if request.method=='POST': if request.POST.get('parent_id')...... and request.POST.get('updated_on'): parent_id = request.POST.get('parent_id') parent_location = customer_location.objects.get(id=parent_id) saverecord=customer_state() saverecord.parent_id=parent_location saverecord.name=request.POST.get('name') saverecord.save() messages.success(request,"Record Saved Successfully..!") return render(request, 'state.html', {'parent_id': parent_id}) else: # Return the form with the parent_id variable return render(request,'state.html', {'parent_id': parent_id}) state.html <div class="container-sm"> <form method = "POST"> {% csrf_token %} <div class="row mb-3" style="display:none"> <label for="inputEmail3" class="col-sm-2 col-form-label">Parent ID</label> <div class="col-sm-10"> <input type="text" value="{{ parent_id }}" name="parent_id" class="form-control" id="inputEmail3" required/> </div> </div> . . </form> -
How to check if the user already rated through template or view function django
So In my list_detail.html I have included the create_starr.html file where my star rating form is placed. Now I can Rate a post with a user only once (which I want). But if a user already rated then it goes to the else condition (goes to the create_starr.html file) But the thing I wanna do is if a user already rated. in post_detail.html I want it to show for example if a user rated 5, I want to show 5 stars in the place of postable star rating form(non editable) in list_detail.html page. But dont know how can I approach that. NOOB HERE. in my models class List(models.Model): title = models.CharField(max_length=120) genre = models.ManyToManyField('Genre') creator = models.ForeignKey(User,on_delete=models.SET_NULL,blank=True, null=True) posted = models.DateTimeField(auto_now_add=True) content = RichTextField(null=True,default=' ') type = models.CharField(max_length=10,default="Movie") spoiler_choices = [(False, 'No'),(True, 'Yes')] spoiler = models.BooleanField(default=False,null=True, choices = spoiler_choices) slug = models.SlugField(max_length= 300,null=True, blank = True, unique=True) def __str__(self): return f'{self.title}|{self.creator}' def save(self, *args, **kwargs): self.slug = slugify(self.title + str(self.posted)) super(List,self).save(*args, **kwargs) class Starr(models.Model): user = models.ForeignKey(User,models.CASCADE) list = models.ForeignKey(List,models.CASCADE) rate = models.PositiveIntegerField(default=0) class Meta: unique_together = ["user", "list"] def __str__(self): return self.user.username + " | " + self.list.title + " | " + str(self.rate) in my views class TheirDetailView(DetailView): … -
Bootstrap modal is not popping up on chrome though working well on microsoft edge
i have used a bootstrap modal in my project .All is working well except modal. when i was using microsoft edge modal is popping up with good manner but something wrong with the google chrome. now how can i get the modal pop up on chrome with best user experience Though it is working while i removed "fade" from the class, it popped up with a dark background, i think this is not a good user experience -
In Django is it possible to add url directory instead of url file
is it possible to use urls directory instead of using url file normaly we do like path("", include("app.urls"), name="") # urls is urls.py but is it possible to add a directory not the urls.py file path("", include("app.folder"), name="") # inside the folder urls.py file lives -
Django static are not getting load on AWS using Nginx
i have a website build on Django. everything is working fine on local machine but the static file are not getting load on production. Django project is running fine on Debug=False I did install whitenoise==6.2.0 the error django settings SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ["*"] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ "http://54.234.143.251", ] CSRF_TRUSTED_ORIGINS = [ "http://54.234.143.251", ] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", # app "applipsync", "store", # packages "whitenoise.runserver_nostatic", "rest_framework", "django_q", "allauth", "allauth.account", "allauth.socialaccount", "crispy_forms", ] CRISPY_TEMPLATE_PACK = "bootstrap4" MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", #add whitenoise "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "core.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [BASE_DIR / "templates"], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ] WSGI_APPLICATION = "core.wsgi.application" # EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' ACCOUNT_EMAIL_REQUIRED = True # Make email verification mandatory to avoid junk email accounts ACCOUNT_EMAIL_VERIFICATION = "mandatory" EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = "" EMAIL_HOST_PASSWORD = "" AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` … -
ModuleNotFoundError: No module named 'menu'
I'm developing a django application, but when I try to start the server, I get an error: ModuleNotFoundError: No module named 'menu'. Here is my code in settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'menu', ]` ``` Here is the project structure: My files I don't understand what I'm doing wrong. -
Django - How to store two different models in a single database table with same column name
I have two models country and state. And the columns which i used for them is as follows: from django.db import models from datetime import datetime # Create your models here. def get_current_datetime_str(): now = datetime.now() return now.strftime("%Y-%m-%d %H:%M:%S") class customer_location(models.Model): parent_id=models.CharField(max_length=100) name=models.CharField(max_length=100) status=models.CharField(max_length=100, default='nil') added_by=models.CharField(max_length=100, default=1) updated_by=models.CharField(max_length=100, default=1) created_on=models.CharField(max_length=100) updated_on=models.CharField(max_length=100) class Meta: db_table="customer_location" def __str__(self): return self.name def save(self, *args, **kwargs): self.created_on = get_current_datetime_str() self.updated_on = get_current_datetime_str() super().save(*args, **kwargs) self.parent_id = 0 super().save(*args, **kwargs) Now i want to set parent id as 0 if a country is entered. And i want to set the parent id as auto incremented id of country if state is entered. The main problem i am facing is to store both of them in single table. How can i do that? Example of Database Schema: -
How can i get 2nd data from requests.post
views.py class Box_Mission_Update(APIView): authentication_classes = [SessionAuthentication , BasicAuthentication] permission_classes = [IsAuthenticated,] def post(self,request,format=None): try: data = request.data update_time = datetime.strftime(datetime.now(),"%Y-%m-%d %H:%M:%S") if data['CEID'] == 203: x=Box_Mission.objects.filter(mission_no=data['CommandID']).latest('created_at') Box_Mission.objects.filter(code=x.code).update(mission_status=2) BoxSubMission.objects.filter(box_mission=x,mission_id='S3').update(end_time=update_time) print('mission_done') return JsonResponse({'code': 0,"description":'mission updated','detail':''}) except Exception as e: event = Error(str(e)) return JsonResponse({"code":event.code,"detail":event.description},status=event.status,safe=False) post requests def update_command_info_203(self, data): try: self.mission_report.clear() self.mission_report={ "CommandID":self.list_Command_Info[index]['CommandID'], "CEID":203, } r = requests.post(f'http://{Mcs["HOST"]}:{Mcs["PORT"]}/api/box_mission/update',data=json.dumps(self.mission_report),auth=HTTPBasicAuth(Mcs["ACCOUNT"],Mcs["PASSWORD"]),headers={'Content-Type': 'application/json'},timeout=1) self.mission_report.clear() except Exception as error: print("203 message fail to update.",error) pass function above will requests.post the data 2 times, the 2nd data will be at 1 min later, how can i only trigger my views.py with the 2nd data i receive? -
issue with configuring django_ace
i'm trying to create a web application that incorporates a light-weight ide but i am having trouble integrating a code editor with syntax highlighting with django. when i try to use the ace widget configurations, none of the settings i add seem to work but the widget is still rendered. views.py from django.shortcuts import render from . import forms # Create your views here def index(request): return render(request, 'main.html', context={'ace_editor': forms.EditorForm}) forms.py from django import forms from django_ace import AceWidget class EditorForm(forms.Form): text = forms.CharField(widget=AceWidget( mode="java", theme="twilight", wordwrap=False, width="5000px", height="300px", minlines=None, maxlines=None, showprintmargin=False, showinvisibles=False, usesofttabs=True, tabsize=None, fontsize=None, toolbar=True, readonly=False, showgutter=True, behaviours=True, )) main.html <p>hi</p> {{ ace_editor }} output -
Why does this Django filter query return empty list?
In my Vechicle table: Vechicle.objects.all().first().tags.slugs() <QuerySet ['car', 'awd']> when I test it in python manage.py shell >>> from django.db.models import Q >>> q_objects = Q(tags__slug='car') >>> q_objects &= Q(tags__slug='awd') >>> q_objects <Q: (AND: ('tags__slug', 'car'), ('tags__slug', 'awd'))> >>> from partpicker.models import Car >>> Car.objects.all().filter(q_objects) <QuerySet []> -
DJANGO RF - Include the SerializerMethodField when nesting a serializer in another serializer
I have a serializer on my UserProfile model. It includes a SerializerMethodField "userGlobalPoints" : class UserProfileSerializer(serializers.ModelSerializer): userGlobalPoints = serializers.SerializerMethodField() def get_userGlobalPoints(self, obj): (*** calculation ***) return userGlobalPoints class Meta: model = UserProfile fields = '__all__' In my Post serializer, I want to nest, for each post, informations about the post's author. So I include fields from the UserProfile model (there is a ForeignKey relation in the Post model). I would like to add the userGlobalPoints field. But I can't figure out how I can nest this field in the serializer. It looks like the usual syntax for nesting a serializer does not work on SerializerMethodField fields. This is my PostSerializer: class PostSerializer(serializers.ModelSerializer): pk = serializers.ReadOnlyField() authorNickname = serializers.CharField(source='postAuthor.userNickname', read_only=True) authorProfileWithGlobalPoints = UserProfileSerializer(many=False, read_only=True) class Meta: model = Post fields = ['pk','authorNickname','postText', 'postTimestamp', 'authorProfileWithGlobalPoints'] Any help on how to achieve this would be apreciated! -
django inline_formset get pk from foreign key item before save to make a form validation
django noob here, well i´ve be dealing with this for over a day and i cant figure out, so decide to post, any help, thanks! have this project and i want to validate this formset, this formset have a select with product list, and quantiy, i need to validate if when saving new data, that the product selected have o not stock enough and raise a form validation error, but i cant figure out how to get the pk from the related model, already read several articles but cant make it work this models.py class Product(models.Model): product_id = models.AutoField(primary_key=True) description = models.CharField(max_length=50) stock = models.IntegerField(default='0') def __str__(self): return self.description + '(' + str(self.stock)+')' def save(self, *args, **kwargs): self.description = self.description.title() super(Product, self).save(*args, **kwargs) class Invoice(models.Model): invoice_id = models.AutoField(primary_key=True) client_id = models.ForeignKey(Client, on_delete=models.CASCADE) date = models.DateTimeField() status = models.BooleanField(default=True) def __str__(self): return str(self.invoice_id) class InvoiceItem(models.Model): invoice_id = models.ForeignKey(Invoice, on_delete=models.CASCADE) product_id = models.ForeignKey(Product, on_delete=models.CASCADE) qty = models.IntegerField(default='0') price = models.DecimalField(max_digits=10, decimal_places=2, default=0) class Meta: constraints = [ models.UniqueConstraint( fields=['invoice_id', 'product_id'], name='unique invoiceitem') ] these are my forms.py class InvoiceForm(forms.ModelForm): class Meta: model = Invoice exclude = ['status'] labels = { 'client_id': ('Cliente'), 'date': ('Fecha'), } widgets = { 'date':forms.DateInput( attrs={'type': 'date'}, ), … -
Django upload multiple images with one input Method Not Allowed (POST): /images/
HI I have just built an HTML-form in which the user can upload multiple images but I am getting Method Not Allowed (POST): /images/ all the time. In the image_list.html the images should be shown. Thanks for your help models.py class ImageModel(models.Model): images = models.ImageField(upload_to='products/') forms.py class ImageForm(ModelForm): class Meta: model = ImageModel fields = ['images'] widgets = { 'images': FileInput(attrs={'multiple': True}), } views.py class ImageFormView(FormMixin, TemplateView): template_name = 'image_form.html' form_class = ImageForm def form_valid(self, form): # Save the images to the database form.save() # Redirect to the image list view return redirect('image_list') class ImageListView(ListView): model = ImageModel template_name = 'image_list.html' context_object_name = 'images' image_form.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary">Submit </form> image_list.html {% load static %} {% for image in images %} <img src="{{image.images.url}}" alt=""> {% endfor %} urls.py urlpatterns = [ path('images/', views.ImageFormView.as_view(), name='image_form'), path('', views.ImageListView.as_view(), name='image_list'), ] -
Django Models to Client
So I'm a kid trying Django for the first time, and I'm trying to convert one of my old Python games (a board game called Ludo) into the client side of this. For this, I need to call every instance of the model Goti (defined in the models.py part of Django). I need to do this in the template.html file. How should I do that? For reference, it would be calling all instances of Goti, and pushing it into a list called gotis[] so that I don't have to keep calling every instance. As I said earlier, how do I do that? -
502 gateway error | gunicorn and nginx server not working
Everything was working correctly I run gunicorn and nginx and my website was working perfectly but after making some changes in gunicorn.service my website is now giving 502 gateway error I undo the changes and make gunicorn.service file as it is but still now it is not working If someone know solution for this please answer this. /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target /etc/systemd/system/gunicorn.service GNU nano 4.8 /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/bankproject/Live-Banking-Solutions-Applications ExecStart=/home/ubuntu/bankproject/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ bankproject.wsgi:application [Install] WantedBy=multi-user.target /etc/nginx/sites-available/myproject server { listen 80; server_name 54.199.217.173; client_max_body_size 20M; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/bankproject/Live-Banking-Solutions-Applications; } location /media/ { root /home/ubuntu/bankproject/Live-Banking-Solutions-Applications; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } Nginx error.log file 2022/12/25 21:36:31 [error] 1147#1147: *1 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 106.195.3.113, server: 54.199.217.173, request: "GET /admin/ HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/admin/", host: "54.199.217.173" 2022/12/25 21:36:34 [error] 1147#1147: *1 connect() to unix:/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream, client: 106.195.3.113, server: 54.199.217.173, request: "GET /admin/ HTTP/1.1", upstream: "http://unix:/run/gunicorn.sock:/admin/", host: "54.199.217.173" -
Need Advice in Javascript - New font family for every div
I'm making a post site, but I'm trying to make each post have it's own individual font family. You can see here with the cursive font, it is assigning it properly, but to all of a class. I need to break each post into it's own individual iteration. Since I am doing it on load, i can't seem to grab their Id's or Attributes easily and put them into an array. my current solution is something like this, full code below The randfontlist doesn't return a normal object, it returns something I've never seen before, like the entire post or something. Does anyone have a smart solution to iterate through the items with .randfont tag? Thank you randfontlist = $('.randfont').toArray() randfont_idlist = $('.randfont').attr("id").toArray() $(`.randfont`)[i].addClass(random) .html {% for poopfact in poopfacts %} <div class="col"> <div class="row"> <p>{{ poopfact.date }} </p> <p class="randfont randfont{{poopfact.id}}" id="{{poopfact.id}}">{{ poopfact.fact }}</p> <p> {{ poopfact.author }}</p> </div> .script $( document ).ready( function() { $('.randfont').load(randomizeFonts()) function randomizeFonts() { let fonts = ['caveat', 'indieflower', 'nanum', 'pacifico', 'pmarker', 'tangerine']; const randfonts = $('.randfont') for (let i = 0; i < randfonts.length; i++) { var random = fonts[Math.floor(Math.random() * fonts.length)]; //get the ids of those items and put it into another … -
Creating a list from django model
Hello I am working on a Django project for a job portal. I want to create a model to store a list of requirements which will be rendered in the html page. Please any idea how I can make this possible ? I haven't tried anything yet, I need bright ideas please... -
How to change add and remove tags with JS in django template
I have a quiz Django app which consists of two parts. One is showing 10 sentences with their audio to remember, one per page, and the second is asking questions for the same set of sentences. First part was set up with js function which creates pagination in my html the following way: <button id="prev">prev</button> <button id="next">next</button> <script> var my_objects = `{{ my_objects|safe}}:` #list of items from my view function function paginate(action) { console.log(action) if (action ==='next') { page_number++; } else{ page_number--; } audio.src = `path/to/audio`; $('#dd').empty(); $('#dd').append('<li><h1>'+ my_objects[page_number].fields['content'] +'</h1></li>'); $('#dd').append(audio); $('#dd').append(translation); $('#page_number').val(page_number); } document.addEventListener('DOMContentLoaded', function() { document.querySelector('#next').onclick = function() { paginate('next'); #same goes for 'prev' button. } }) </script> Now when the user paginated through all the sentences I want to show the continue button and if the user clicks it, start the second part. The second part has absolutely same page except I need to hide content of my objects and leave only audio or vise versa and add textarea tag for the user's input. After that I need to loop over my objects again - now in the form of questions. I need to do that without page re-rendering. I tried to make it with tag disabling … -
How to get only the most recent post from each user, ordered by created date
I'm trying to create a social media site in Django where the homepage will display a list of each friend's most recent post, with the newest at the top. At the moment I'm ignoring the friendship functionality and just displaying posts from all users. My current code gets the most recent post from users, but doesn't then order that list by created date. views.py: class PostList(generic.ListView): model = Post # Gets the most recent post from each user # However, the returned set is not ordered by created_on queryset = Post.objects.order_by('author', '-created_on').distinct('author') template_name = 'home.html' I can't change the order_by call as it throws this error: SELECT DISTINCT ON expressions must match initial ORDER BY expressions I know it's possible because I did it ~5 years ago but I don't know what approach I took then and the code is lost. -
Which is better way to rotate logs of Django Application, logging Module of Python or Logrotate of linux?
I want to rotate my logs of Django application, I am able to rotate the logs (based on size) successfully with logging module of python but its causing issue because same log file is getting accessed by celery process and other processes and because of that sometimes application is writing logs in debug.log.1 instead of debug.log file (assume my log file name is debug.log). I suspect this is because my celery process and django server (uwsgi server) is running by different user and because of permission issue it is behaving like that. I am thinking of using logrotate of linux to rotate my log instead of using python class logging.handlers.RotatingFileHandler Can anyone help me in choosing the best way to rotate the log also if you can help me understand why my application is suddenly writing logs in debug.log.1 file instead of debug.log that would be great. -
why i get this Error: missing 1 required positional argument: 'request'
urls.py path("approve_questions/", Approve_questions.posst, name="muster"), # i wann call this function(Approve_questions.posst) in a class path("approve_questions/", Approve_questions.as_view(), name="approve_questions"), class Approve_questions(ListView): form = QuesModel.objects.filter(flaag__exact="False") def get(self, request, *args, **kwargs): form = self.form context = {"form": form} return render(request, "approve_question.html", context) def posst(self, request): return print("anim") how i call about urls.py a function in a class. In this case i wanna call posst but i get the Error: Approve_questions.posst() missing 1 required positional argument: 'request' How i can fix that? Thank you Guys!!!