Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - ModuleNotFoundError: No module named 'csvexport'
So I'm working on adding an admin function to a Django project so that I can export the model instances to csv. It is all working fine locally whilst using Docker. But when deploying I get this internal server error: It states that the package is not installed, but when accessing the Django shell (poetry run python3 manage.py shell) and importing the package (from csvexport.actions import csvexport) everything works fine. I'm stuck for quite some time now on this and cant figure out what is going wrong. Anyone had some kind of problem like this with poetry package managing? settings.py: INSTALLED_APPS = [ ... 'csvexport', ] model: from csvexport.actions import csvexport from django_summernote.admin import SummernoteModelAdmin class FundAdmin(SummernoteModelAdmin): ... actions = [csvexport] -
How Django Implement tier selection
Is that Django have any feature that can implement tier selection? the form like this, first, user select the first field says gender, then the next category field will list out all the category belongs to this gender says Male. -
multiple event targets on same parent element not working
I have been dealing with this problem for quite some time. It's been a great way to learn Javascript, but I'm just done and need help before I end up in prison for something dumb. I need the inline formset's delete checkbox checked before removing the parent element (form). I am using Django's inline formsets and refuse to use jquery to handle this because I want to learn good ol' vanilla Javascript. I have tried all kinds of combinations and solutions with nothing to show. {% load crispy_forms_tags %} {% load static %} {% block content %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" type="text/css" href="{% static 'css/availability_update_new.css' %}"> </head> <body> <form id="all-add-form" method="POST" enctype="multipart/form-data"> {% csrf_token %} <legend class="bottom mb-4">Profiles Info</legend> {{ sun_bool.sunday|as_crispy_field }} {{ sunday_formset.management_form }} {% for sun_form in sunday_formset %} {% for hidden in sun_form.hidden_fields %} {{ hidden }} {% endfor %} <div class="sun_time_slot_form"> {{ sun_form }} <button class="delete-sun-form" type="button" id="delete-sun-btn" onclick="one();"> Delete This Sunday Timeslot </button> </div> {% endfor %} <button id="add-sun-form" type="button" class="button">Add Other Sunday Times</button> <input type="submit" name="submit" value="Submit" class="btn btn-primary"/> </form> <script type="text/javascript" src="{% static 'js/add_timeslot.js' %}"></script> </body> </html> {% endblock content %} const sunForm = document.getElementsByClassName('sun_time_slot_form'); const mainForm … -
Invalid HOST header: 'ec2-13-233-105-50.ap-south-1.amazonaws.com:8000'. You need to add 'ec2-13-233-105-50.ap-south-1.amazonaws.com' to ALLOWED_HOSTS
I have been getting this error even when I added the public ipv4 address added to the allowed hosts. I don't know what I am doing wrong. This is My settings.py code. I'm trying to run this application in amazon ec2 instances. Using bitbucket code deploy pipeline. but my code giving this unusual error. """ Django settings for Cycatz project. Generated by 'django-admin startproject' using Django 4.0.5. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['ec2-13-233-105-50.ap-south-1.amazonaws.com:8000'] ENV = "dev" # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cycatzapp', 'rest_framework', 'corsheaders', 'ebhealthcheck.apps.EBHealthCheckConfig', 'drf_yasg' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', '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 = 'Cycatz.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', … -
Whats the best strategy to upload and process big macros file
I have a project which allow user to upload macros files, about 30Mb each file. After uploading a file I need to process it like open that workbook then pick a sheet then insert the data inside to database. I realize that just open the workbook with openpyxl is taking too much time. So what's the best way to do this, do I need to run it concurrently in the background or any other option and how to achieve that. I'm using Django btw. Thanks in advance -
Django shell history commands always come from top
I've been having issues in trying to use older Django shell history commands, be it from previous shell session or current. If I press UP arrow key, they show the first lines in the ~/.ipython/profile_default/history.sqlite, and not the last one I pressed enter on. A couple of things I've tried are: Removed ipython history file, touched it again but same problem. Re-installed Ipython in venv. Tried using shell from a different project. Tried using shell_plus from django-extensions. Nothing seemed to fix the issue. Does anyone have a clue how to fix this? -
Testing cursor.execute with sql script called
Function to test def get_adgroups_not_taked_share( campaign_ids: List[str], src_table: str, spend_src_table: str ) -> List[Tuple[str, str]]: loses_adgroups: List[Tuple[str, str]] = [] with RedshiftCursor() as cursor: cursor.execute( """ SELET some_data from some_table WHERE some_condition """ ) for row in cursor.fetchall(): loses_adgroups.append((row[0], str(row[1]))) return loses_adgroups There is a test for this function import pytest from my_ap import get_adgroups_not_taked_share @pytest.fixture def campaigns_redshift_cursor_mock(mocker): cursor_mock = mocker.MagicMock() cursor_mock.fetchall.return_value = [ ('hs_video544', '123123123', 100), ('hs_video547', '123123123', 50), ] rs_cursor_creator = mocker.patch('google_panel.logic.clean_creative.RedshiftCursor') rs_cursor_creator.return_value.__enter__.return_value = cursor_mock return rs_cursor_creator @pytest.mark.django_db def test_get_adgroups_not_taked_share( campaigns_redshift_cursor_mock, ): campaign_ids = ['1111', '2222', '3333'] result = get_adgroups_not_taked_share(campaign_ids, 'test_table', 'spend_src_table') assert result == [('hs_video544', '123123123'), ('hs_video547', '123123123')] Now I want to add a new feature to test the sql script. Checking that the correct sql query is being called. something like def test_get_adgroups_not_taked_share( campaigns_redshift_cursor_mock, ): ...... query = """SELET some_data from some_table WHERE some_condition""" campaigns_redshift_cursor_mock.execute.assert_called_with(query) But got E AssertionError: Expected call: execute('query') E Not called -
DJANGO FILTERING ON FORIEGN KEY PROPERTIES
I HAVE 2 MODELS class Cart(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE,blank=True, null=True) user = models.ForeignKey(User,on_delete=models.CASCADE,null=True, blank=True) quantity = models.IntegerField(default=1) class Item(models.Model): restaurant = models.ForeignKey(Restaurant,on_delete=models.CASCADE,null=True, blank=True) name= models.CharField(max_length=100) is_active = models.CharField(max_length=30,null=False,default=True) is_avaliable = models.CharField(max_length=30,null=False,default=True) price = models.CharField(max_length=30,null=False,default=0) WHERE cart is using restaurant as a foreign key in views.py def post(self,request,*args,**kwargs): userid = request.user.id res= request.data.get('restaurant', False) cartItem = Cart.objects.filter(user=userid,item__restaurant__contains=res) it is throwing an error saying raise FieldError( django.core.exceptions.FieldError: Related Field got invalid lookup: contains [02/Aug/2022 08:37:45] "POST /placeorder HTTP/1.1" 500 118627 what i want to do is Get all cart objects which has user id = userid and item.restaurant = restaurant id ... can someone help me i referred this page https://stackoverflow.com/questions/1981524/django-filtering-on-foreign-key-properties but i doesnt seems to work! -
How to make API post request when using django-countries package
I came across this package called django-countries and the the features it provides look nice. Now I'm trying to test it out in a react application but I'm having issues making API post request when trying to post a named country to the database. Instead of CharField I used countryField() provided by the package. I have tried several format to make post request from postman but I keep having the error:"country_name" is not a valid choice. One of the ways I have tried out is this: { "country": "country_name" } How do I go about it. Since I'm using react, will be better for me to use charField instead of using the django-countries package since I'll be using html select option to get the country of the user? -
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.