Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
show all likes count in each post django REST API
models.py class Post(models.Model): title = models.CharField(max_length=150) class PostLike(models.Model): like = models.CharField(max_length=20) user = models.ForeignKey(User,on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) Serializer.py class PostSerializer(serializers.ModelSerializer): likes = serializers.SerializerMethodField("like_count") class Meta: model = Post fields = ("__all__") def like_count(self,obj): total_like = self.context.get("like_count") return total_like views.py @api_view(["POST"]) def allpost(request): id = request.data post_list = Post.objects.all() like_count = PostLike.objects.filter(post_id = id ).count() post_serializer = PostSerializer(post_list,many=True,context={"like_count":like_count}) return Response(request,post_serializer.data) output: [ { "id": 1, "likes": 1, "title": "post 1", }, { "id": 2, "likes": 1, "title": "post 2", }, { "id": 3, "likes": 1, "title": "post 3", }, ] db id like post_id user_id 1 1 1 1 2 1 2 1 3 1 1 2 actually in my db likes are: post 1 have 2 likes post 2 have 1 like post 3 don't have any like i want to show this like this . but it's showing the first post likes for every post . how can i fix this .? i know the problem in the like_count in view . but i don't know what to put there instead of id . sorry for my poor English Thanks in advance -
Adding answer count field in Django Rest Framework
I have got 2 models, Questions and Answers. class Question(models.Model): question_subject = models.TextField() question_text = models.TextField(default=None, null=True, blank=True) slug = models.SlugField(max_length=128, unique=True, null=False, editable=False) created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) animal = models.ForeignKey('animals.Animal', on_delete=models.PROTECT) class Answer(models.Model): answer = models.TextField() created_at = models.DateTimeField(editable=False, default=timezone.now) updated_at = models.DateTimeField(default=timezone.now) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) question = models.ForeignKey('Question', on_delete=models.PROTECT) number_of_points = models.IntegerField(default=0) moderate_status = models.BooleanField(default=False) The answer is connected to the Question via question field(Foreign key), but now i'm creating API for this and i need to list all the questions and the answer_count related to them. Right now i have a simple class QuestionsSerializer(serializers.ModelSerializer): class Meta: model = Question fields = '__all__' class QuestionsList(generics.ListAPIView): queryset = Question.objects.all() serializer_class = QuestionsSerializer Do you have any idea how to display the count of answers in a Question? In django views i would use something like aggregate count, but it won't work in DRF. -
my form_valid method isn't working properly
I was working in a project and I am having trouble to understand why my form_valid method is not working for ProfileCreateView. I have created a profile model for user. This is the code: # views.py from django.views.generic import CreateView from .models import UserProfile from django.urls import reverse_lazy class ProfileCreateView(CreateView): model = UserProfile template_name = "profile/profile_create.html" fields = ('profile_picture', 'bio', 'occupation', 'hobbies', 'date_of_birth') success_url = reverse_lazy("login") def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) # template {% extends 'base.html' %} {% block title %}Create Your Profile{% endblock title %} {% load crispy_forms_tags %} {% block content %} <div class="container border border-success rounded mt-4 "> <h2 class="display-6 fst-italic mt-3 mb-3">Create Your Profile</h2> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy}} <button type="submit" class="btn btn-outline-primary mt-4 mb-4">Create my profile</button> </form> {% endblock content %} # models.py from django.db import models from django.contrib.auth import get_user_model import uuid from django.core.files.storage import FileSystemStorage class UserProfile(models.Model): author = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) profile_picture = models.ImageField(upload_to='images/') id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) bio = models.TextField(blank=True) occupation = models.CharField(max_length=100) hobbies = models.TextField(blank=True) date_of_birth = models.TimeField() def __str__(self): return self.author.username + ("'s profile") please tell me how to work this properly! -
TemplateDoesNotExist :/
I don't know why i keep getting this erro TemplateDoesNotExist at / home.html code settings.py `TEMPLATES = { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(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', 'django.template.context_processors.media', 'django.template.context_processors.static', ], 'loaders':[ 'django.template.loaders.filesystem.Loader', ] }, },` -
Django webapp // Commenting posts on a webpage
I'm currently building a webapp with Python's django framework. There is one task that I do not really know how to handle. Let's say my page displays different questions of users (like tweets on twitter). Now, I want to provide users with the ability to write answers to the different questions displayed. When the users clicks on an answer button below a particular question, a form is displayed below the question with a textarea that can be submitted. When the filled out form with text is submitted and sent to the backend, I need to create a database relationship between the newly created answer and the question. In order to find the corresponding question in the DB its ID is necessary (primary key). Here is my problem. I do not know where to get the ID from in a safe manner. An easy way would be to put the ID into the html part of the question and then use it with javascript, or to store the IDs as javascript variables. However, as the DOM and the values of javascript variables can be modified by users on the frontend, this does not appear secure to me. If a user changes … -
Django Rest Framework routing with primary key prefix
I'm using DRF DefaultRouter as follows. # urls.py router = DefaultRouter() router.register('book', BookingViewSet, basename='booking') router.register('book/<int:bk>/reservation', ReservationViewSet, basename='reservation') urlpatterns = [ path('', include(router.urls)), ] # view class ReservationViewSet(viewsets.ModelViewSet): serializer_class = ReservationSerializer queryset = Reservation.objects.all() # for testing only But when I visit the URL /book/1/reservation/ it says no url pattern found. lending/ ^book/<int:bk>/reservation/$ [name='reservation-list'] lending/ ^book/<int:bk>/reservation\.(?P<format>[a-z0-9]+)/?$ [name='reservation-list'] lending/ ^book/<int:bk>/reservation/(?P<pk>[^/.]+)/$ [name='reservation-detail'] lending/ ^book/<int:bk>/reservation/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='reservation-detail'] The current path, lending/book/1/reservation/, didn’t match any of these. I'm using bk to capture book id. -
How can I install pdftex on my app in Heroku?
Folling Create Pdf with Latex and Django My code in view: from django_tex.shortcuts import render_to_pdf from datetime import date def gerar_lista_turma(request, turma_id): if request.user.tipo_user() not in ['Admin', 'Professor']: return redirect('logout') template_name = 'base_lista.tex' context = { 'hoje': date.today().strftime("%d/%m/%Y"), 'escola': 'Name' } return render_to_pdf(request, template_name, context, filename=f'base.pdf') But i get the error: Exception Type: CalledProcessError Exception Value: Command 'pdflatex -interaction=batchmode texput.tex' returned non-zero exit status 127. Exception Location: /app/.heroku/python/lib/python3.9/subprocess.py, line 528, in run -
how to set specific value is first in order from the list in django or python
how to set specific value is first in order from the list in django or python "Ex: 'entity': [ OrderedDict([ ('id', 14), ( 'brand', OrderedDict([('id', 15), ( 'title', 'Golds Gym Long ' 'Branch') ]), OrderedDict([ ('id', 241), ( 'brand', OrderedDict([('id', 230), ( 'title', 'New York Fitness & ' 'Nutrition'), ]), OrderedDict([ ('id', 367), ( 'brand', OrderedDict([('id', 309), ( 'title', 'new distributors')])]); I expected result is given key value is first order, then ordering from list using sorted function in python expected result " -
I want to sort data with date_time after first processing the data with initial sorting of another column
I have football prediction data containing dataframe- df = df[['match_datetime', 'country', 'league', 'home_team', 'away_team', 'home_odds', 'draw_odds', 'away_odds', 'predicted_home_score', 'predicted_away_score']] I have to initially add two columns, predicted_home_score & predicted_away_score to get total predicted goals... df['total_predicted_goals'] = df['predicted_home_score'] + df['predicted_away_score'] Then I have to set_axis- df = df.set_axis(['Match_Datetime', 'Country', 'League', 'Home_team', 'Away_team','home_odds', 'draw_odds', 'away_odds','Predicted_home_score', 'Predicted_away_score', 'total_predicted_goals'], axis=1) Now I sorted the values using total_predicted goals - df1 = df.sort_values(by=["total_predicted_goals"], ascending= False) I only wanted the top 10 numbers so i can slit it into two to predict the top 5 as over 2.5 and the remainder as over 1.5 -- df1 = df1.drop(['home_odds', 'draw_odds', 'away_odds'], axis=1) df1 = df1.head(10) dt = ['Over 2.5', 'Over 2.5', 'Over 2.5', 'Over 2.5', 'Over 2.5', 'Over 1.5', 'Over 1.5','Over 1.5','Over 1.5','Over 1.5'] df1['Prediction'] = dt df2 = df1.drop(['Predicted_home_score', 'Predicted_away_score', 'total_predicted_goals'], axis=1) df2 = df2.style goals = df2.to_html() return render(request, 'over_goals.html', { 'goals': goals}) My problem is that the output date is not in seqeunce. def over_goals(request): df = pd.read_csv("media/csv/predictions_with_gridsearch.csv") df = df[['match_datetime', 'country', 'league', 'home_team', 'away_team', 'home_odds', 'draw_odds', 'away_odds', 'predicted_home_score', 'predicted_away_score']] df['total_predicted_goals'] = df['predicted_home_score'] + df['predicted_away_score'] df = df.set_axis(['Match_Datetime', 'Country', 'League', 'Home_team', 'Away_team','home_odds', 'draw_odds', 'away_odds','Predicted_home_score', 'Predicted_away_score', 'total_predicted_goals'], axis=1) df1 = df.sort_values(by=["total_predicted_goals"], ascending= False) df1 = … -
Django aggregate on JSONB field multiple levels deep
As the title says, I'm trying to aggregate a value in a JSONB field that's a couple of levels deep. For the model Payment, there's a JSONB field Payment.extra_data that contains a data structure like: { "invoice": { "extra": { "net_amount": 100, "tax_amount": 16.63, } } } and I'm trying to find the sum of the net_amount values. So far, I've got to doing: payment_qs = Payment.objects.annotate( net_amount=Func( F("invoice"), Value("extra"), Value("net_amount"), function="jsonb_extract_path_text", output_field=models.DecimalField(), ) ) which, if I then do payment_qs.values('meta_amount') on will give me: <PaymentQueryset [{'net_amount': Decimal('50.0')}]> However, if I try aggregating the queryset then I get: payment_qs.aggregate('net_amount') ProgrammingError: function sum(text) does not exist LINE 1: SELECT SUM("net_amount") FROM (SELECT jsonb_extract_path_te... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. I've tried setting the output field payment_qs.aggregate('net_amount', output_field=DecimalField()) but no luck. Any ideas? -
Sockets learning in 2022?
I am very beginner. Is learning websocket programming worth it in 2022? Now there are a lot of abstractions like websocket.io, django channels e.t.c which do the same thing as plain websockets. So learning websockets is waste of time? (unless high-performance required) -
Django - Counting filtered model instances per row in a template table
Let's say I have the following django models: class House(Model): author = ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE) title = CharField(max_length=200, default='') text = TextField(default='') rooms = IntegerField(null=True) class Room(Model): author = ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE) title = CharField(max_length=200, default='') text = TextField(default='') house = CharField(max_length=200, default='') furniture = IntegerField(null=True) class Furniture(model): author = ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE) title = CharField(max_length=200, default='') text = TextField(default='') room = CharField(max_length=200, default='') And I want to generate the following table in a template: Room In house Amount of furniture Living Room Summer house 5 Kitchen Summer house 8 Bedroom Summer house 2 Bathroom Main house 3 Where the column "Amount of furniture" counts the instances of the "furniture" model where the field "room" is equal to that of the entry in the column "room" for that row. I'm trying to figure out how to do this, and I've landed on a few different ways - ranked from most ideal/pythonic to least ideal/pythonic. Building some sort of mechanism into the model. This would be perfect, but I can't seem to find any obvious way to do it. Adding a function that generates a dictionary in the view in views.py. Would be easy to build (gather names of "room", make a for loop … -
Django field not passing through serializer
Using the Django REST Framework 2.2, I have a Person model as follows in models.py:: class Person(models.Model): id = models.CharField(max_length = 20, primary_key = True, blank = True) name = Models.CharField(max_length = 1024, blank = True) values = {} All data is stored in a Firestore database for saving and retrieving data via the REST API. Before new entries are made into the database, a serializer is used to validate incoming POST data. The route /person takes POST request data and runs it by the PersonCreateSerializer in views.py: def create_person(request): """ Route: /person Method: POST """ try: print(request.data) # Above print outputs: # <QueryDict: {'name': ['John Doe'], 'values': ['{ "height": 180 }']}> serializer = PersonCreateSerializer(data = request.data) serializer.is_valid(raise_exception = True) person = Person.create_person(request.data) ... except APIException as exception: return JsonResponse(exception.APIError, status = exception.status) serializers.py: class PersonCreateSerializer(CreateModelSerializer): class Meta: model = Person fields = "__all__" def validate(self, data): print(data) # Above print outputs: # OrderedDict([('name', 'John Doe')]) # Notice missing 'values' field. if not data.get("values"): # Ensure we have a values field within the data. raise APIException("ERROR_MISSING_FIELD", "Missing required field 'values'.", 400) return data The problem is however any value provided for the values dictionary is discarded when the serializer validate() … -
Is there way to build api using python to show counter clock of other website on your own website?
I want to show the below counter clock of this website (https://dailyclose.com/) on my website enter image description here Is it possible? -
Django logging with watchtower got an unexpected keyword argument in handler
I'm trying to implement django logging with AWS CloudWatch, after creating the user and entering the correct fields, following the guides scattered on the web, I still have an error: ValueError: Unable to configure handler 'watchtower': __init__() got an unexpected keyword argument 'boto3_session' This is my setting file (logging config): boto3_connect_session = Session( aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, region_name=AWS_REGION_NAME ) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'aws': { 'format': u"%(asctime)s [%(levelname)-8s] %(message)s [%(pathname)s:%(lineno)d]", 'datefmt': "%Y-%m-%d %H:%M:%S" }, 'simple': { 'format': '[%(asctime)s %(module)s] %(levelname)s: %(message)s' }, }, 'handlers': { 'watchtower': { 'level': 'DEBUG', 'class': 'watchtower.CloudWatchLogHandler', 'boto3_session': boto3_connect_session, # 'log_group': AWS_LOG_GROUP, # 'stream_name': AWS_LOG_STREAM, 'formatter': 'aws', }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/tmp/logger.log', 'formatter':'simple' }, }, 'loggers': { AWS_LOGGER_NAME: { 'level': 'DEBUG', 'handlers': ['watchtower'], 'propagate': False, }, 'local': { 'level': 'DEBUG', 'handlers': ['file'], 'propagate': False, }, }, } full error message: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib64/python3.6/logging/config.py", line 565, in configure handler = self.configure_handler(handlers[name]) File "/usr/lib64/python3.6/logging/config.py", line 738, in configure_handler result = factory(**kwargs) File "/usr/local/lib/python3.6/site-packages/watchtower/__init__.py", line 203, in __init__ super().__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'boto3_session' During handling of the above exception, another exception occurred: Traceback … -
Dynamically add field to a form python django
I want to have a Django form in which a user can add multiple stop_name,stop_longitude,stop_latitude using the Add more button inside. Let's suppose a user has 3 stop_names so he will have to click on the Add more twice. And on each add more above fields will populate again. I am new to Django so I need some help. This is my model class SupplyChainStops(models.Model): ingredient = models.ForeignKey(Ingredients, null=True, on_delete=models.CASCADE) stop_name = ArrayField(models.CharField(max_length=1024, null=True, blank=True)) stop_longitude = ArrayField(models.CharField(max_length=500, null=True, blank=True)) stop_latitude = ArrayField(models.CharField(max_length=500, null=True, blank=True)) -
Access a variable from template tag that takes arguments
I have a template tags that takes ID on template and returns a list, I want to check the list if the variable is available and make checkbox input checked. `_checkbox.html` {% load get_previous_response %} {% user_response question.id %} {# this returns a list of ids #} So I want to do something like this <input type="checkbox" {% if option.id in user_response %}checked{% endif %}> problem is the above won't work, I tried django templatetag `with template context` My main goal is I want to access the list returned by {% user_response question.id %}. -
Why css and js library shows me HTTP/1.1" 404 179 in django project
This is the error I am getting. the libraries are available at the specified location but it is showing 404. -
Django : Update column (pick column name dynamically) value
I want to update a table field by filtering the data and selecting a specific row, in below query "address1" is the field of User table which needs to be updated with value available in variable addr: User.objects.filter(user_id=uid).update(address1=addr) Above query works fine as I have given column name ="address1" in update option. But my requirement is I want update field to be dynamic, i.e. it can be address1,address2, address3 (this is stored in a variable) Let's say it is stored in add_field variable then I can't use below as it will try to find add_field column in User table which is not present there: User.objects.filter(user_id=uid).update(add_field=addr) Query : How can I pass field name through variable/dynamically to update option in mentioned line of code or through any other option. -
Site not working with url www in digital ocesns
My django site is hosted with digital ocean and i use digital ocean name server for my domain configuration. The domain below works https://example.com Why https://www.example.com do not work. www.example.com refused working too. This is a django built site with requirements.txt, procfile and uswgx. Do i need to configure another form of server like Apache, ngix or something else to make this www url work. Hope Am not getting something wrong in my digital ocean configuration? www works well when i host on Heroku but i can't access the www on digital oocean with my domain. I need urgent help pls. -
I want to sort my pandas dataframe using two different columns
I have a csv data that contains soccer predictions. I sorted it using sort_values(by=["total_predicted_goals"]. My problem now is to let the dates be sorted by descending or ascending order.Output[view.py`def over_goals(request): df = pd.read_csv("media/csv/predictions_with_gridsearch.csv") df = df[['match_datetime', 'country', 'league', 'home_team', 'away_team', 'home_odds', 'draw_odds', 'away_odds', 'predicted_home_score', 'predicted_away_score']] df['total_predicted_goals'] = df['predicted_home_score'] + df['predicted_away_score'] df = df.set_axis(['Match_Datetime', 'Country', 'League', 'Home_team', 'Away_team','home_odds', 'draw_odds', 'away_odds','Predicted_home_score', 'Predicted_away_score', 'total_predicted_goals'], axis=1) df1 = df.sort_values(by=["total_predicted_goals"], ascending=False) df1 = df1.drop(['home_odds', 'draw_odds', 'away_odds'], axis=1) df1 = df1.head(10) dt = ['Over 2.5', 'Over 2.5', 'Over 2.5', 'Over 2.5', 'Over 2.5', 'Over 1.5', 'Over 1.5','Over 1.5','Over 1.5','Over 1.5'] df1['Prediction'] = dt df2 = df1.drop(['Predicted_home_score', 'Predicted_away_score', 'total_predicted_goals'], axis=1) df2 = df2.style goals = df2.to_html() return render(request, 'over_goals.html', { 'goals': goals })`][2] -
I can access the website locally but can't access it through the internet After openning the port
I want to make my phone a Linux web server, by using the userLand application which gives you the ability to use ubuntu distribution on Andriod. I already installed Django and ran my server on port 8080 since port 80 is busy (seems logical that android is using it) and everything is good, it works when I try to access the website from another device on the local network. so I proceeded to the next step which is making the website accessible from all over the internet then I found that you need to make a port forwarding on the router to allow devices from outside the local network to access a device in the localnetwork . I followed the following steps : made the phone's IP static locally added the configuration needed for the port forwarding (phone's ip, port 8080, etc... ) found the public IP for my phone and used it and with port 8080 it is still not working: I can access the website locally but can't access it through the internet. I tried another method by using an already working server from the "AWebServer" application on google play but still the same problem. I tried temporarily … -
Next js with django api rendering data
I am working on a front end of a project and I am stuck for a while. I have created an api with django rest framework and I am trying to connect to a Nextjs front end. The data is to show on the front page that is why I call getInitialProps. Following is the code import styles from '../styles/Home.module.css'; import axios from 'axios'; const Home = ({ listings, error }) => { if (error) { return <div>An error occured: {error.message}</div>; } return ( <ul> {listings.map((listing) => ( <li key={listing.address}>{listing.title}</li> ))} </ul> ); }; Home.getInitialProps = async (ctx) => { try { const res = await axios.get('http://127.0.0.1:8000/api/listings/?page=4'); const rep = await res.data; console.log(rep.results); listings = rep.results; return { listings }; } catch (error) { return { error }; } }; export default Home; In the console log I get the data, which is in the bellow format: [ { index: 1734112, user: 11233, title: 'Classical style', address: 'address 23, city , country', bedrooms: '2', bethrooms: '1', price: '5803', list_type: 'rent' }, { index: 1722303, user: 32119, title: 'Pangrati On the Lake', address: 'address 28, city , country', bedrooms: '1', bethrooms: '1', price: '4800', list_type: 'rent' } ] But I get … -
How to cleanly migrate BooleanField to CharField
I have the following model: class Teacher(models.Model) tenured = models.BooleanField(default=False) I want to migrate this BooleanField to a CharField with additional options ['No', 'Pending', 'Yes']. Like so: class Teacher(models.Model) TENURE_CHOICES = [(choice,choice) for choice in ['No', 'Pending', 'Yes']] tenured = models.CharField(max_length=7, default='No', choices=TENURE_CHOICES) Now, as I have 1000+ records already present for this model I would like to migrate them from their Boolean value to the Yes'/'No value when migrating. How would I do this without having to store a backup of this table and reapply after migrations have taken place? Can I do this as part of the migration process? -
Date field is not getting saved in the admin database
models.py class Add_Timelog(models.Model): project=models.ManyToManyField(Project) client=models.ManyToManyField(Client) Job=models.ManyToManyField(Add_Job) #Date = models.DateField(max_length=100 ,auto_now_add=True,editable=True) Date= models.DateField(default = datetime.date.today) Hours=models.TimeField(null=True) def __str__(self): return str(self.Date) settings.py DATE_INPUT_FORMATS = ('%Y-%m-%d') When I posted a date in the api for the date field it is getting posted. But when I look that in the admin database it is showing as '%' in the date field, and if I tried to change the entry it is getting stored as 'undefined' and while saving the entries it is throwing an error as "enter a valid date". kindly help me to resolve this issue. Attached the screenshot of admin for your reference. enter image description here