Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django admin log table is empty
tech geeks. Somehow my Superuser got deleted and some of my data is missing. To check whether somebody with superuser credentials did it. I wanted to check Django admin logs but when I checked the django_admin_log table it was empty. Can u guys tell me how can I check who deleted my data or a way to get back my data? -
Django view skips checking permission classes
I'm trying to filter lists according to: the user can work with all of their lists the user can use safe methods on public lists I have this code: In views.py: class LinkListViewSet(viewsets.ModelViewSet, generics.ListAPIView, generics.RetrieveAPIView): queryset = LinkList.objects.all() serializer_class = LinkListSerializer permission_classes = [IsOwnerOrPublic] In permissions.py: class IsOwnerOrPublic(BasePermission): def has_permission(self, request, view): return request.user and request.user.is_authenticated def has_object_permission(self, request, view, obj): return obj.owner == request.user or ( obj.public and (request.method in SAFE_METHODS)) The problem is, I believe the view just skips checking the permission classes and returns all lists, and I am not sure why, or how to fix it. -
what are the limitations of accessing an environment variable in cmd prompt
I have declared an environment variable named DB_PASSWORD in the windows command prompt, when I run echo %DB_PASSWORD% it returns the exact value I just set but when I run another command prompt in the same directory alongside the first command prompt and try to access the variable, It does not give me the variable I set, My question is how does the environment variables work on this particular issue and how I can access a variable in all Instance of windows command prompt because sometimes I found it useful having more than one instance of cmd opened side to side commands images -
SyntaxError: cannot assign to literal when passing simple string
I'm passing simple string but giving can not assign to literal model = "/model-best", disable=['tokenizer'] print(model) -
Pyhtho Django. the messaa is from python file and i want to show it in HTML his code is working but I want the message will show as pop up or alert
Pyhtho Django. the messaa is from python file and i want to show it in HTML his code is working but I want the message will show as pop up or alert Register {% if messages %} {% for result in messages %} <b style="color: green;">{{result}}</b> {% endfor %} {% endif %} -
How to use django.contrib.humanize filter in DRF serializers
is it possible to use the Django humanize filter for drf on the serializers i have tried putting naturaltime in the to_representation method like below def to_representation(self, instance): representation = super(ListUsersSerializer, self).to_representation(instance) representation['last_login'] = instance.last_login(naturaltime) but it didn't work -
How to fix Apps aren't loaded yet error in Django
I am a beginner in Django and SQL. We have four tables Including Category, Seller, Product, Product_Seller. Each product has one category. each seller can sell a product. Suppose you do not sell the same product multiple times and each seller sells each product at most once. We want to find products that have more than 5 sellers. and we want to find the second category that has the largest number of products. I want to run the SQL code in Django. I have configured the setting for using ORM, but when I run the program it has a 'Apps aren't loaded yet' error. please let me know how can I fix it. here is the code: import os import sys import django from django.conf import settings INSTALLED_APPS = [ 'orm', 'myapps', ] DATABASES = { 'default': { 'ENGINE' : 'django.db.backends.mysql', 'NAME' : 'db', 'USER' : 'admin', 'PASSWORD' : '', 'HOST' : 'localhost', } } settings.configure( INSTALLED_APPS = INSTALLED_APPS , DATABASES = DATABASES , ) django.setup() if __name__ == "__main__": from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) import manage from orm.models import Label if __name__ == '__main__': Label.objects.create(name='test') print(Label.objects.get(name='test')) from django.db import models from django.db import connection class Category(models.Model): title = models.CharField(max_length=128) … -
Django channels cannot receive chat message
I am new to django websocket channel. I have followed a tutorial and something doesn't work on the code. I am trying to understand and use the django channel and created a group room to broadcast a message to a particular group. Now from the code below, it shows no error but doesn't broadcast or response the message that I am trying to test. Here is the full code: import django django.setup() import json import traceback from functools import wraps from urllib import parse as urlparser from asgiref.sync import sync_to_async from channels.generic.websocket import AsyncJsonWebsocketConsumer from django.contrib.auth.models import User from django.utils import timezone from django.conf import settings class QueueConsumer(AsyncJsonWebsocketConsumer): @sync_to_async def _get_headers(self): return dict(self.scope['headers']) async def connect(self): get_dept_code = self.scope['url_route']['kwargs']['deptcode'] self.room_name = get_dept_code self.room_group_name = f'room_{self.room_name}' await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): print("Disconnected") await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, json_data): response = json.loads(json_data) event = response.get("event", None) data = response.get("data", None) if(event == 'EVENT_CALL'): await self.channel_layer.group_send(self.room_group_name, { 'type': 'chat_message', 'message': "hello", 'event': "EVENT_CALL", }) # Receive message from room group async def chat_message(self, res): r_headers = await self._get_headers() if not r_headers.get(b'origin') or (r_headers.get(b'origin') and not self._check_origin(r_headers.get(b'origin'))): return False await self.send(bytes_data=json.dumps({"payload": res}).encode()) -
Update Django 2.14 to 3.x Any reasons?
Just want to get suggestions and your expertise, guys. I have a small Django project with 2.2.14 version and got suggestions from dependancy_bot to update it to the new 2.2.24 version. At the same time I`m reviewing Django-related books and blogs, and now more commonly mentioned the new 3.x versions. So, is it worth migrating, and what is your story? P.S. My current project focus on REST framework API and low-code platform mobile App interaction, with simple blogging and view-generated pages from embedded SQLite. In mind Dash integration and light-ML cloud services. -
How can I separate button operation in javascript and Django?
I made sign up form page using Django. When I fill in the register form, data is included in database. But, when I click the email check button, register button also is clicked and the page is reloaded. How can I separate these two button? $('.email-check-btn').click(function (){ const email = $('#email').val() if (email === ''){ alert('please check the form') } $.ajax({ type: 'GET', url: 'email-check?email=' + email, datatype: 'json', success: function (response){ if (response.result !== 'success') { alert(response.data) return } if (response.data === 'exist') { alert('that email is already exist!') $('#email').val('').focus() } else { alert('good, you can use it!!') } } }) }) def email_check(request): try: user = get_user_model().objects.get(email=request.GET['email']) except Exception as e: user = None result = { 'result': 'success', 'data': 'not exist' if user is None else 'exist' } return JsonResponse(result) def sign_up(request): if request.method == 'GET': user = request.user.is_authenticated if user: return redirect('/main') else: return render(request, 'sign_in_and_up.html') elif request.method == 'POST': user_id = request.POST.get('username', '') password = request.POST.get('password', '') password2 = request.POST.get('password2', '') nickname = request.POST.get('nickname', '') email = request.POST.get('email', '') if password != password2: return render(request, 'sign_in_and_up.html', {'error': 'check your password'}) else: if user_id == '' or password == '' or nickname == '' or email … -
How can I create a proper sql statement from this django model?
I'm trying to insert data retrieved by scraping into the DB created by the following models. However, I realized that using django's bulk_create or the external library based on it, bulk_create_or_update, is likely to make the logic too complex. (I felt that orm should be used for simple CRUD, etc.) So I'm thinking of using Row SQL to save the data, for both maintainability and speed. I'm not familiar with sql at all, so I'd like to get some advice from you guys. What SQL code is preferable to this? Each page to be scraped has multiple pieces of information, and there are multiple pages in total. I'd like to scrape all the pages first, add them to a dictionary, and then save them in a batch using sql, but I don't know the best way to do this. from django.db import models from django.forms import CharField # Create your models here. # province class Prefecture(models.Model): name=models.CharField("都道府県名",max_length=10) # city class City(models.Model): prefecture = models.ForeignKey(Prefecture, on_delete=models.CASCADE, related_name='city') name=models.CharField("市区町村名",max_length=10) # seller class Client(models.Model): prefecture = models.ForeignKey(Prefecture, on_delete=models.CASCADE, related_name='client',null=True,blank=True) city = models.ForeignKey(City, on_delete=models.CASCADE, related_name='client',null=True,blank=True) department = models.CharField("部局",max_length=100) # detail class Project(models.Model): name = models.CharField("案件名",max_length=100) serial_no = models.CharField("案件番号",max_length=100,null=True,blank=True) client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='project') # …