Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When inserting a lot of data : No 'Access-Control-Allow-Origin' header is present on the requested resource
I'm working on a React Django API project, I'm using postgreeSQL as Database, and I deployed my website using nginx and gunicorn, I have a problem on my deployed website when I try to insert a lot of data (add studies), I'm getting this error: Access to XMLHttpRequest at 'http://192.168.85.126:8000/api/new-study/' from origin 'http://192.168.85.126' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. PS: I'm not getting this error when I try to add less data, in my development environment I can add whatever data I want, the problem is only happening in production -
Saving parsed json data to a sqlite database tables collection. Regular updates with schedule
Within my Django project, which will be a website, there is an app that will collect odds data from API's of different bookmakers. So far I have set up the requests and parsed the data that I want to collect and store for one bookmaker. I have it in its own .py file which you can see below. I would like to store each block of data in a separate table within a SQLite database within the app of the project. bluebet_au.py code: import json # Bluebet Rugby League Odds API. link = 'https://affiliate-api.bluebet.com.au/json/reply/MasterCategoryRequest?EventTypeID=102&WithLevelledMarkets' \ '=true&WithLevelledMarkets=true ' # Request data from link as 'str' data = requests.get(link).text # convert 'str' to Json data = json.loads(data) # HEAD TO HEAD ODDS for win_odds in data['MasterCategories'][0]['Categories'][0]['MasterEvents']: h2h_market_competition = win_odds['CategoryName'] h2h_market_event_id = win_odds['MasterEventId'] h2h_market_event_title = win_odds['MasterEventName'] h2h_market_start_time = win_odds['MaxAdvertisedStartTime'] h2h_market_market_type = win_odds['Markets'][0]['BetDetailTypeCode'] h2h_market_home_team = win_odds['Markets'][0]['OutcomeName'] h2h_market_home_team_win_odds = win_odds['Markets'][0]['Price'] h2h_market_away_team = win_odds['Markets'][1]['OutcomeName'] h2h_market_away_team_win_odds = win_odds['Markets'][1]['Price'] print('{}, {}, {}, {}, {}, {}, {}, {}, {}'.format(h2h_market_competition, h2h_market_event_id, h2h_market_event_title, h2h_market_start_time, h2h_market_market_type, h2h_market_home_team, h2h_market_home_team_win_odds, h2h_market_away_team, h2h_market_away_team_win_odds)) # HANDICAP ODDS for handicap_odds in data['MasterCategories'][0]['Categories'][0]['MasterEvents']: handicap_market_competition = handicap_odds['CategoryName'] handicap_market_event_id = handicap_odds['MasterEventId'] handicap_market_event_title = handicap_odds['MasterEventName'] handicap_market_start_time = handicap_odds['MaxAdvertisedStartTime'] handicap_market_market_type = handicap_odds['Markets'][2]['BetDetailTypeCode'] handicap_market_home_team = handicap_odds['Markets'][0]['OutcomeName'] handicap_market_home_team_win_handicap = handicap_odds['Markets'][2]['Points'] handicap_market_home_team_win_odds = handicap_odds['Markets'][2]['Price'] handicap_market_away_team … -
HTML variable in <a> for href
In my HTML, I want to have the text of a href to be the same as the variable each_files_configs. Whatever I try seems to come out as a literal. {% for each_files_configs in files_configs %} <p></p> <a href="{% url 'download_file' %}">document.write(each_files_configs)</a> {% endfor %} I have also tried <var> and all it does is change the text to italics. -
How to get relational model of data in django?
I'm querying user data. And I'm getting the following output in response. { "id": 33, "username": "dummy", "email": "dummy@test.com", "role": 49, "is_active": true, "staff": true, "admin": false, "last_login": "2022-07-27T06:41:03.709582Z", "update_time": "2022-08-02T07:53:11.241320Z", "create_time": "2022-07-26T14:34:35.161434Z" } As you can see, this user model is in foreign relation with a role with an id 49. I want to get all the details of the role in JSON with accounts instances. How can I do that ? e.g : { "id": 33, "username": "dummy", "email": "dummy@test.com", "role": { "id":49 "projects":true, "notifications":true, "emails":true, "update_time": "2022-08-02T07:53:11.241320Z", "create_time": "2022-07-26T14:34:35.161434Z" }, "is_active": true, "staff": true, "admin": false, "last_login": "2022-07-27T06:41:03.709582Z", "update_time": "2022-08-02T07:53:11.241320Z", "create_time": "2022-07-26T14:34:35.161434Z" } My Views for this API. @api_view(['GET']) @permission_classes([IsAuthenticated]) def all_platform_user_list(request): if request.method == 'GET': users = User.objects.get_all_platform_users() total_count = len(users) total_page = total_page_counter(total_count) paginator = CustomPagination() paginator.page_size = 20 result_page=None try: result_page = paginator.paginate_queryset(users, request) except: pass serializer = CreateAccountsSerializer(result_page, many=True) return Response({"message": "Here are results","total_page":total_page,"total_count":total_count, "data": serializer.data},status=status.HTTP_200_OK) else: return Response({"message": "No User"},status=404) -
How to post with multiple images in django rest framework(DRF)?
I wanted to request several images at once, so I found them on Google and wrote the code. However, image url is not added to the image list as a result of POST in postman. The image does not enter the my vcode media folder. please...help me... The setup was completed as follows. settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') models.py from django.db import models from django.contrib.auth.models import User class Story(models.Model): title = models.CharField(max_length=50) content = models.TextField() createdAt = models.DateTimeField(auto_now_add=True, null=True) updatedAt = models.DateTimeField(auto_now=True, null=True) def __str__(self): return self.title class StoryImage(models.Model): story = models.ForeignKey(Story, on_delete=models.CASCADE, related_name='image') image = models.ImageField(upload_to='images/', blank=True, null=True) serializers.py from rest_framework import serializers from .models import Story, StoryImage class StoryImageSerializer(serializers.ModelSerializer): image = serializers.ImageField(use_url=True) class Meta: model = StoryImage fields = ['image'] class StorySerializer(serializers.ModelSerializer): images = serializers.SerializerMethodField() def get_images(self, obj): image = obj.image.all() return StoryImageSerializer(instance=image, many=True, context=self.context).data class Meta: model = Story fields = '__all__' def create(self, validated_data): instance = Story.objects.create(**validated_data) images_data = self.context['request'].FILES for image_data in images_data.getlist('image'): StoryImage.objects.create(story=instance, picture=image_data) return instance views.py from django.shortcuts import render from rest_framework import viewsets from .models import Story from .serializers import StorySerializer class StoryViewSet(viewsets.ModelViewSet): queryset = Story.objects.all().order_by('-createdAt') serializer_class = StorySerializer urls.py from django.contrib import admin from django.urls … -
How to import export works in foreign key - django
I do have two models 1) patient profile, to get patient First and last name, default id and 2) Medinfo, medical information of patient used default id of patient model as foreign key. I am trying to use django import export for bulk upload data.. in patient profile model i can able to upload data without any trouble, but when I trying upload data in medinfo model, I am getting error. I do understand due to using foreinkey as field I am getting trouble here to import data. How to do it? Note: pat_ID is also a primary key of Medinfo model. class Patientprofile(models.Model): pat_Fname = models.CharField(max_length=100) pat_Lname = models.CharField(max_length=100, blank=True) def __str__(self): return str(self.id) class MedInfo(models.Model): # Medical Information fields Notes = models.TextField(max_length=2000, blank=True) pat_ID = models.OneToOneField(patientprofile, on_delete=models.CASCADE,unique=True, primary_key=True) def __int__(self): return self.pat_ID -
How redirect after download file?
I want redirect to back page after submit form and download file. I have a form in html: <div> <form action="." method="POST" enctype="multipart/form-data"> {{ form.as_p }} {% csrf_token %} <button type="submit">Download CSV</button> </form> </div> After submit my django views: def import_csv(self, request): if request.method == "POST": csv_file = request.FILES["csv_file"] decoded_file = csv_file.read().decode('utf-8') io_string = io.StringIO(decoded_file) reader = csv.reader(io_string) complite_data = [] for row in reader: complite_data.append(row) response = HttpResponse( content_type='text/csv', headers={ 'Content-Disposition': 'attachment; filename="somefilename.csv"'}, ) writer = csv.writer(response) for data in complite_data: writer.writerow(data) return response -
To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is of:ne sn't an available database backend or couldn't be imported
'django.db.backends.postgresql.psycopg2' i isn't an available database backend or couldn't be imported. Check the above excepti. db\utils.py", line 126, in load_backendon. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is of:ne of: sn't an available database backend or couldn't be imported. Check the above exception. To use o 'mysql', 'oracle', 'postgresql', 'sqlite3' -
create admin panel for a model with generic foreign key in Django
Here is my model and I want to register a Django admin for it. I want to display the related objects automatically when a user selects a content type. Do you have any solution for it? class UserAccessContent(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') order = models.ForeignKey(Order, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) def __str__(self) -> str: return self.content_object.title and here is my admin class. It seems that autocomplete_lookup_fields doesn't work! I don't know why. @admin.register(UserAccessContent) class UserAccessContentAdmin(admin.ModelAdmin): readonly_fields = ['content_object'] list_display = ['id', 'user', 'content_object', ] list_display_links = ['id'] list_per_page = 20 search_fields = ['user'] autocomplete_lookup_fields = { 'content_object': [['content_type', 'object_id']], } -
Reading a file from the database
I have a react frontend app which takes a file and a template name as input and POSTs the form to a Django RestAPI endpoint. The template contains information about how the file should be processed, like SQL table name, should it append the file or override the table and stuff like that, basically metadata. I want this process to be a background process so the user doesn't have to wait the process to finish. My current process for this is that I POST the form(the file and the template) to a table from the API. I have a cronjob which runs every minute and checks the table whether it has a new upload or not, and if it does it processes the file based on the conditions given in the template. My problem is is that I used to do this from the backend, but I rewrote my whole app to be frontend rendered with react. And now the file gets uploaded directly to the database from the form, while from the backend I uploaded it to my server, and I only had a path to the file in the database, and I don't know how to access the … -
Partial sum based on the values of another field
Given a model like this (example for the purpose of generalization): Group Value 1 2 1 5 1 64 2 1 2 4 How could I make a sum for each group and obtain the results for the sum of each group instead of the total sum of all the groups? Until now I had done sums like this: total_value = myModel.objects.aggregate(sum=Sum('value')) The result would be: 2 + 5 + 64 + 1 + 4 = 76 Expected result (list or dict if possible): Group 1: 71 Group 2: 5 Any help will be appreciated -
how can i set property data to model field in django
class Project(models.Model): index = models.IntegerField() @property def index(self): function = self.function.name frac = self.fraction.name operation = self.operation.name if function == 'Production' and operation == '2C': return frac*9 What im trying to do is set the returned value from index property to index field.Dont mind the function,frac and operation variables -
Second level relationships (similar to Rails's has_many :through)
I have the below model setup (irrelevant parts removed): class Client(models.Model): name = models.CharField(max_length=200, unique=True) class Vehicle(models.Model): client = models.ForeignKey(Client, on_delete=models.PROTECT, related_name="vehicles") vin = models.CharField(max_length=200, unique=True) class Chip(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.PROTECT) serial_number = models.CharField(max_length=200, unique=True) Is there a simple way to get all Chips belonging to a specific Client (through the Vehicle table)? Something similar to has_many :through in Rails? Like to be able to call sth like: client = Client.objects.first() chips = client.chips.all() -
Css not showing on heroku after making some changes [closed]
I added some link in my Django project base.html and I try to redeploy,my css stylings aren't coming up again -
Django filter get parent model based on child model value
class Apps(models.Model): app_name = models.CharField(max_length=200) app_type = models.CharField(max_length=200) app_link = models.CharField(max_length=200) class FavouriteApps(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) app = models.ForeignKey(Apps,on_delete=models.CASCADE) I need to get all favourite apps details from 'Apps' table based on the logged in user. Example App Table app_name app_type app_link AppA type1 linkA AppB type1 linkB AppC type2 linkC Favourite Table user app userA AppA userB AppA userA AppC So when UserA logged in I need to fetch userA favourite apps details using foriengkey relationship. Here it is AppA and AppC are favourite apps for userA -
Username Color - Django
So, for the project that I'm working on, I'm going to have a couple different groups that have different access to to things. I want show distinction on my website by changing the color of the username per group, or by adding a font-awesome icon beside it. How would I go about implementing this? I've looked on stackoverflow and haven't seen a clear answer. -
ReadOnlyError in Django apllication with Redis and DjangoCannels
I have a Django app using DgangoChannels, Djangochannelrestframework. It establishes a websocket connection with ReactJS frontend. As channel layers I use Redis like that CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("redis", 6379)], }, }, } Redis and Django runs in docker. My redis docker setup is redis: image: "redis:7.0.4-alpine" command: redis-server ports: - "6379:6379" networks: - nginx_network When I run my app on production server everything works for 5-8 hours. But after that period, if Django app trying to send a message via ws if falls with the error ReadOnlyError at /admin/operations/operation/add/ READONLY You can't write against a read only replica. Request Method: POST Request URL: http://62.84.123.168/admin/operations/operation/add/ Django Version: 3.2.12 Exception Type: ReadOnlyError Exception Value: READONLY You can't write against a read only replica. Exception Location: /usr/local/lib/python3.8/site-packages/channels_redis/core.py, line 673, in group_send Python Executable: /usr/local/bin/python Python Version: 3.8.13 Python Path: ['/opt/code', '/usr/local/bin', '/usr/local/lib/python38.zip', '/usr/local/lib/python3.8', '/usr/local/lib/python3.8/lib-dynload', '/usr/local/lib/python3.8/site-packages'] Server time: Tue, 02 Aug 2022 08:23:18 +0300 I understand that it somehow connected with Redis replication, but no idea why if falls after period of time and how to fix it -
Nested Serializer save post foreign key in django
In my project, the relationship between Product and Group is ManytoOne. When I tried to post a new product, it cannot work. I'm sure there are more issues with this code and I will appreciate a detailed answer, because I am new to Django and Python. Thank you in advance. models.py class Group(models.Model): productType = models.CharField(max_length=100) intervalTime = models.IntegerField() created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True,editable=False) def __str__(self): return self.productType class Product(models.Model): productName = models.CharField(max_length=255) color = models.CharField(max_length=255) group = models.ForeignKey(Group, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True,editable=False) def __str__(self): return self.productName serializers.py class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('id','productType','intervalTime') class ProductSerializer(serializers.ModelSerializer): group = GroupSerializer(many=False) class Meta: model = Product fields = ('id','productName','color','group') def create(self, validated_data): group = validated_data.pop('group') product = Product.objects.create(**validated_data) for group_instance in group: Group.objects.create(**group_instance, product=product) return product views.py @api_view(['POST']) def createProduct(request): serializer = ProductSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) -
Creating an object in nested serializer giving an error of bad request "owner is required"?
This is my first time dealing with nested serializers and it gives me an error "owner" is required while creating a post. Why is that? class CreatePostView(APIView): permission_classes = [IsAuthenticated] parser_classes = [MultiPartParser] def post(self, request, *args): user = request.user data = request.data data['owner'] = user print(data) serializer = PostSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) PostSerializer: class PostSerializer(serializers.ModelSerializer): owner = UserSerializer() comments = CommentSerializer(many=True, read_only=True) class Meta: model= Post fields = ("id", "img", "posted_at", "caption", "owner", "comments") Post model: class Post(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") img = models.ImageField(upload_to=post_img_url, default="default.jpg", max_length=200) caption = models.CharField(max_length=100, null=True, blank=True) posted_at = models.DateTimeField(auto_now_add=True, blank=True) objects = models.Manager() current_user_posts = CurrentUsersPosts.as_manager() class Meta: ordering = ("-posted_at",) def __str__(self): return f"{self.img} posted by {self.owner} at {self.posted_at}" console: <QueryDict: {'owner': ['9'], 'img': [<InMemoryUploadedFile: treeHouse.jpg (image/jpeg)>]}> Bad Request: /api/posts/upload/ [02/Aug/2022 11:14:01] "POST /api/posts/upload/ HTTP/1.1" 400 37 -
In Django templates, can I write a function or a custom tag to generate a dropdown, so I can reuse the same code in other templates?
I want my django templates models agnostic. Django view will massage the model data and send a list to the template ['item_1', 'item_2', 'item_3', .... 'item_n] In the template, I want to convert this list of items into a HTML dropdown. But since I shall be having this kind of behavior at many places I would like to reuse the code that is transforming the list into the dropdown. How may I do that? -
Django ImproperlyConfigured/ No Patterns / Circular Import Error
I have one base DJango code and recently written a separate Django code (search_me below). Both are working fine separately but while merged the two code then it is giving following Error: ERROR: "django.core.exceptions.ImproperlyConfigured: The included URLconf 'covid19.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import." Base urls.py: from django.conf.urls import url, include from django.contrib import admin from firstApp import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url('admin/', admin.site.urls), url('^$',views.homepage,name='homepage'), url(r'^covid19',views.indexPage,name='index'), url(r'^selectcountry',views.indicountrydata,name='index'), url(r'^segmentation/',include('segmentation.urls')), url(r'^search_me/',include('search_me.urls')), #url(r'^search_me/',views.search_view,name='search_view'), #path(r'^search_me',include('search_me.urls',namespace='search_me')) ] urlpatterns += staticfiles_urlpatterns() search_me urls.py # from django.urls import path from django.conf.urls import url, include from . import views app_name = 'search_me' # urlpatterns = [ # path('', views.search_view , name='search'), # ] urlpatterns = [ url(r'^$', views.search_view, name='search'), ] -
merge dictionary based of condition match
I have a list of multi dictionary currently looks like "results": [ { "message_code": 1002, "module": "Farm Added", "title": { "en": "Farm Added Successfully!" }, "message": { "en": "Time to add Crops to your farm!" }, "icon_link": { "en": null }, "image_link": { "en": null } }, { "message_code": 1002, "module": "Farm Added", "title": { "hi": "खेत सफलतापूर्वक जुड़ गया है!" }, "message": { "hi": "अभी अपने खेत में फसल जोड़ें|" }, "icon_link": { "hi": null }, "image_link": { "hi": null } }, { "message_code": 1003, "module": "Pending task today", "title": { "en": "Check out today's Tasks NOW!" }, "message": { "en": "Tasks are important for your crop health!" }, "icon_link": { "en": null }, "image_link": { "en": null } }, { "message_code": 1003, "module": "Pending task today", "title": { "hi": "आज का कार्य अभी देखें!" }, "message": { "hi": "आपकी फसल के स्वास्थ्य के लिए कार्य महत्वपूर्ण हैं!" }, "icon_link": { "hi": null }, "image_link": { "hi": null } }, I want to merge the dictionary "title", "image", "icon" and "message", columns based on the condition when the "message_code" matches with the other "message_code" and get the desired out as "results": [ { "message_code": 1002, "module": "Farm Added", "title": … -
Django in processing extra method in views.py
I am new to Django, and having a difficulty soting out a problem. My code is processing extra method in views.py even without being called.Below is an example:- When I am cliking on Home button on my page. Landing Page: I am being redirected to correct view method i.e., index. IndexMthod in views.py: After loading the page my code is hitting another method edit content, without being called with a param favicon.io Concern Method which is my concern. Though it is not affecting my django app, but still it's annoying to see extra method being called everytime. Please let me know, if I have done something wrong here or if any more info is required from my end. Thanks in advance. -
How to include a file in Django as a Background cover
So basically, I'm new to Django and I have been experimenting with Django in building my website portfolio. I decided to experiment with Django if I could use python, JS, Bootstrap, CSS and HTML at the same time, all went well till I came to an obstacle which has been a hassle to overcome. Initially, in my static folder, I have a folder called CSS that contains a file of CSS as main.css and another folder within the Static folder, called Images which contains some Jpg images. So after writing my code in my base folder as home.html, I then proceeded to the main.css folder and wrote: *{ margin: 0; padding:0; box-sizing: border-box; } main { font-family: Heebo,sans-serif; } .Landing { min-height: 100vh; background:url("./images/Laptop.jpg"); background-size: cover; } So basically where the initial problem is(Where I labeled #4), when I host my server I was expecting the image to come up in the background of the website, but it didn't. I then proceeded to think it should be a URL or calling problem, so instead of using a URL I tried: <img src="{% static 'images/Laptop.jpeg' %}" > But this at #4 didn't show up on the background of the page either, … -
Django fixture append to existing data
I have a table which contains some data already. Can a fixture be created with new data records and be appended to the existing data in the table, without specifying a pk explicitly?