Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with Google Charts using Python Django
Started getting this problem once I tried using 2 graphs at the same time on my html+css template. I'm doing arrays like this on my views.py file (sending to the html file as context variable): array1 = [["x axis", "y axis"] , ["a", 0] , ["b", 3], ["c", 1]] array2 = [["x axis", "y axis"] , ["j", 1] , ["k", 5], ["l", 8]] Then I'm showing my graphics like this: <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {'packages':['bar']}); google.charts.setOnLoadCallback(drawChart1); function drawChart1() { var data1 = google.visualization.arrayToDataTable({{ array1|safe }}); var options1 = { chart: { title: 'This', subtitle: 'That', }, backgroundColor: '#FFFFFF', bars: 'horizontal' // Required for Material Bar Charts. }; var chart1 = new google.charts.Bar(document.getElementById('barchart_material1')); chart1.draw(data1, google.charts.Bar.convertOptions(options1)); } </script> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {'packages':['bar']}); google.charts.setOnLoadCallback(drawChart2); function drawChart2() { var data2 = google.visualization.arrayToDataTable({{ array2|safe }}); var options2 = { chart: { title: 'this', subtitle: 'that', }, backgroundColor: '#FFFFFF', bars: 'horizontal' }; var chart2 = new google.charts.Bar(document.getElementById('barchart_material2')); chart2.draw(data2, google.charts.Bar.convertOptions(options2)); } </script> <div class="card_view"> <div id="barchart_material1" style="width: 700px; height: 300px;"></div> </br> </br> <div id="barchart_material2" style="width: 700px; height: 300px;"></div> </br> </br> </div> But then I get a "Undefined renderer" kinda problem. Any help? -
Keep getting MIME error when trying to attatch css file Django
I know this question has been asked before but I have tried to implement the answers to those forums but none have worked for me so far. Here is my folder: Files Here is my html file: {% include 'main.html' %} {% load static %} <head> <link rel="stylesheet" type="text/css" href="projects.css"/> </head> <body> <h1 style="text-align: center">Projects</h1> <h1>{{projects}}</h1> {% for project in context %} {% with 'jweb/images/'|add:project.image as project_photo %} <div class="card-wrap"> <div class="card"> <h2 class="card-header">{{project.title}}</h2> <div class="card-image"> <img src="{% static project_photo %}"> </div> </div> </div> {% endwith %} {% endfor %} </body> {% include 'pagebottom.html' %} Here is my css: .card-wrap{ width: auto; } .card{ background: blue; padding:3rem; border:none; box-shadow: 0 2px 5px 0 rgb(0,0,.2); border-radius: .25rem; } .card-image{ min-width: 0; min-width: 0; } .card-image > img{ height:100%; width:100%; object-fit:contain; } Here is my settings.py: import os import mimetypes mimetypes.add_type("text/css", ".css", True) from pathlib import Path # 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.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "django-insecure-zzk5%zz_)k%47o$9+-hocf_2azb@wj@)k89b=^18xk*80g!ekq" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = … -
First view in DJANGO tutorial -> Page not found (404)
I was doing tutorial "Writing your first Django app, part 1" and I got stuck in "Write your first view". I have fulfil all instructions regardings files. When I go to http://127.0.0.1:8000/ then I can see "The install worked successfully! Congratulations!" but if I go to http://localhost:8000/polls/ then I see: Page not found (404) Request Method: GET Request URL: http://localhost:8000/polls/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ The current path, polls/, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. In this case according instructions I should see "Hello, world. You're at the polls index". I attached 2 files content and 2 interesting screens (why does it emphasize?). views.py urls.py views.py from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the polls index.") urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] I was looking answer in Stack Overflow (also in hints) or YouTube but unfortunately without success. Interesting but in another computer it works, but on my … -
HTML table styling is behaving strange when generated with python, table in table?
I am generating a table in HTML from a Django model, and although the table headers and rows seem to be correct, the table is displaying strangely, with a seemingly differently formatted table as parent element. What is causing this behavior? I was not able to find supporting documentation... <style> table,th,td { border:2px solid green; border-spacing: 10px; } <div class="container"> <table id="labrequestoverview"> <tr> {% for item in model_headers %} <th>{{ item |capfirst }}</th> {% endfor %} </tr> {% for all_rows in query_results %} <tr> {% for every_column in all_rows %} <td>{{ every_column }}</td> {% endfor %} </tr> {% endfor %} </table> </div> -
what is best practices in having too many dynamic html elements in a single templates in django
pretty new to django and coding...I am currently building a page that has serveral independenent divs that get updated from a single click event. I have all these different divs(features) on a single page and I am starting its looking bad, cluttered. will dividing these different divs affect the functionality of the main page since i intend to have all these elements update dynamically independent of each other. and if it's possible, will it affect perfomance? I have a page full of divs that work. I am trying to break these divs into multiple html template elements using the extend feature in django {% extends 'template_name.html' %} will this work? -
Match with Django import_export with multiple fields
I would like to import a CSV in Django. The issue occurs when trying to import based on the attributes. Here is my code: class Event(models.Model): id = models.BigAutoField(primary_key=True) amount = models.ForeignKey(Amount, on_delete=models.CASCADE) value = models.FloatField() space = models.ForeignKey(Space, on_delete=models.RESTRICT) time = models.ForeignKey(Time, on_delete=models.RESTRICT) class Meta: managed = True db_table = "event" class Space(models.Model): objects = SpaceManager() id = models.BigAutoField(primary_key=True) code = models.CharField(max_length=100) type = models.ForeignKey(SpaceType, on_delete=models.RESTRICT) space_date = models.DateField(blank=True, null=True) def natural_key(self): return self.code # + self.type + self.source_date def __str__(self): return f"{self.name}" class Meta: managed = True db_table = "space" class Time(models.Model): objects = TimeManager() id = models.BigAutoField(primary_key=True) type = models.ForeignKey(TimeType, on_delete=models.RESTRICT) startdate = models.DateTimeField() enddate = models.DateTimeField() def natural_key(self): return self.name def __str__(self): return f"{self.name}" class Meta: managed = True db_table = "time" Now, I create the resource that should find the right objects, but it seems it does not enter into ForeignKeyWidget(s) at all: class AmountForeignKeyWidget(ForeignKeyWidget): def clean(self, value, row=None, **kwargs): logger.critical("<<<<< {AmountForeignKeyWidget} <<<<<<<") name_upper = value.upper() amount = Amount.objects.get_by_natural_key(name=name_upper) return amount class SpaceForeignKeyWidget(ForeignKeyWidget): def clean(self, value, row, **kwargs): logger.critical("<<<<< {SpaceForeignKeyWidget} <<<<<<<") space_code = row["space_code"] space_type = SpatialDimensionType.objects.get_by_natural_key(row["space_type"]) try: space_date = datetime.strptime(row["space_date"], "%Y%m%d") except ValueError: space_date = None space = Space.objects.get( code=space_code, type=space_type, source_date=space_date ) return … -
Get key, values from Queryset in Django
I want to create a chart using chart js in my Django application. I made a query from my Shift object to get employers' org name and count of job openings that each employer has published. The result is like this: queryset = Shift.objects.values('employer__org_name').annotate(count=Count('id')) #id is job id and employer org name is a foreign key from Employer object. query result: <QuerySet [{'employer__org_name': 'employer1_org', 'count': 10}, {'employer__org_name': 'employer2_org', 'count': 9}]> There are two employers in the dataset. The first one called "employer1_org" which has published 10 jobs in total, and the second one called "employer2_org", it has published 9 jobs. In the chart, the x axis would be "employer__org name" and y axis is "count of job openings". Perhaps I should get data like this? {"employer1_org":10},{"employer2_org":9} or what is your suggestion? This is my view: def chart(request): queryset = Shift.objects.values('employer__org_name').annotate(count=Count('id')) # to be filled # return render(request,'chart.html') -
Why does adding more fields to this widget lead to a keyError?
I'm working on a form in my Django project. I wanted to add a bootstrap class to my input fields. I tried to do this with the following code: class CategoryForm(ModelForm): class Meta: model = Category fields = '__all__' labels = { "sub_category":"Sub category (if any):" } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['category_name','sub_category','category_info','category_video'].widget.attrs.update({'class':'form-control'}) But when I load the page I get this: KeyError at /academy/category_form ('category_name', 'sub_category', 'category_info', 'category_video') Is this not possible? Do I have to add a new line for every field in my form? So like this: def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['category_name'].widget.attrs.update({'class':'form-control'}) self.fields['sub_category'].widget.attrs.update({'class':'form-control'}) self.fields['category_info'].widget.attrs.update({'class':'form-control'}) .... This would make for some long lines of code if I have to do this for every form which does not make sense of follow DRY. -
Django ORM Query to find average between timestamps
I am struggling to figure out how to structure a query. I have three models that I inherited, tickets, comments, and actions: class Ticket(models.Model): date = models.DateTimeField(default=datetime.datetime.now, blank=True) subject = models.CharField(max_length=256) description = models.TextField() And class Comments(models.Model): date = models.DateTimeField(default=datetime.datetime.now, blank=True) comment = models.TextField() action = models.ForeignKey(Label, on_delete=models.CASCADE, limit_choices_to={'group__name': 'action'}, related_name='action_label') ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) And class Label(models.Model): name = models.CharField(max_length=50) group = models.ForeignKey(LabelGroup, on_delete=models.CASCADE) My goal is to get an average timespan between Ticket.date (opened) and the latest Comment.date of type Label.name = containment. Lastly, I want to pass in a date range (start_date, end_date) to limit to only tickets within that time period. Ultimately, I want to return: { avg_time_to_contain: 37, avg_time_to_recover: 157 } from a DRF view. The query set I have so far is: queryset = Comments.objects.filter(ticket__date__gte=start_date, ticket__date__lte=end_date).filter(action__name__icontains="containment").distinct(ticket).aggregate(avg_containment=Avg(F(date)- F(ticket__date))) I am getting an error, saying incident is not defined. I believe that is due to my distinct function but I am having a hard time getting my brain to translate into what I am after. Pseudo code for the query (in my thinking), Grab comments that have tickets (FK) with dates between start / end date Filter by the action (FK) name having the work containment … -
How should i set DJANGO_SETTINGS_MODULE, django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_BACKEND
i'm just start to learn Django and during create a priject i get a problem: "django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_BACKEND..." I met description fo this problem on Staciverflow but i don't understand in which file i should set DJANGO_SETTINGS_MODULE??? Please, give me detail description I tried set this environment variable in my virtualenv which i use for my project in "activate" file, but it did'nt help me. Maybe my question is stupid but i really don't understand, sorry -
Chrome ignores <a> tag's target argument when link is programmatically "clicked"
I have a project that is implemented with Django, Dojo and JS. I've been banging my head against this issue all week and cannot find any hints online as to what the problem might be. Hopefully someone here has either run into this issue as well and can shed some light on the problem. I have an unordered list <ul> similar to the following: `<ul> <li><a target="displayArea" id="pre-select" href="foo.html>Foo</a></li> <li><a target="displayArea" href="bar.html">Bar</a></li> <li><a target="displayArea" href="baz.html">Baz</a></li> </ul>` ``` elsewhere in the code is the target iframe: ``` `<iframe style="border: none;" name="displayArea" id="displayArea" width="100%" height="95%" title="Report Area"></iframe>` ``` When I mouse over and click "Foo" it works as expected, "Foo" is displayed in the iframe shown above. If, however, I execute the following script which is immediately after the \</ul\> in the code: ``` `<script> window.document.getElementById('pre-select').click(); </script>`` ``` "Foo" is not displayed in the iframe, instead it briefly appears in the host window frame then disappears. I'm not sure why there is a difference clicking directly on the link as it appears in the \<ul\> or executing the \<script\> that does the "click" programmatically. Any insight would be greatly appreciated... As stated in the problem description I expected the link to appear … -
Local server won't go through my URL pattern on my local server
I'm new to Django and I'm facing a problem that I can't solve despit my research... I'v already made small django projects without this error but since I reformat my computer (I can't see the link but that's context!) i'm having this problem. So when I'm running a django project this is what my browser shows me despite others urls in my project Django doesn't go trhough my urls I'v tried with an almost empty project but a least one more url and still have the same page. urls.py in the main file (src/mynotes/urls.py): from django.contrib import admin from django.urls import path, include urlpatterns = [ path('index/', include('dbnotes.urls')), path('admin/', admin.site.urls), ] settings.py in the main project (src/mynotes/settings.py): INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dbnotes' ] urls.py in the app (src/dbnotes/urls.py): from django.urls import path from . import views urlpatterns = [ path("", views.homepage, name="homepage"), ] views.py in the app (src/dbnotes/views.py): from django.http import HttpResponse def homepage(request): return HttpResponse("Hello, world. You're at the polls index.") Even stranger, when i change "path('admin/', admin.site.urls)" I still get the admin page with the same route. Even if i change 'admin/' or admin.site.urls. It looks like my local server display an over … -
Django doesn't connect to postgresql database using docker-compose
Yes i know this question has been asked, and the usual error is making the DB_HOST = docker service name, in my case db. Here's my docker-compose.yml: version: "3" services: db: image: postgres:latest restart: always ports: - "54320:5432" expose: - "54320" volumes: - ./database-data:/var/lib/postgresql/data/ # persist data even if container shuts down environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres # POSTGRES_HOST_AUTH_METHOD: trust django: build: ./api restart: always command: ["python", "manage.py", "runserver", "0.0.0.0:8000"] volumes: - ./api:/app/api ports: - "8000:8000" depends_on: - db raddl_admin: build: ./frontend/raddl_admin stdin_open: true # docker run -i tty: true # docker run -t command: ["npm", "start"] ports: - "3000:3000" volumes: - ./frontend/raddl_admin:/app/frontend/raddl_admin - /app/frontend/raddl_admin/node_modules volumes: database-data: # named volumes can be managed easier using docker-compose Logging the django service gives: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "db" (172.18.0.2) and accepting TCP/IP connections on port 54320? So it's clearly trying to connect to db on that port and my environment vars are set for the django instance. I can even ping my db service from my django service: docker exec -it 1f764333ace2 bash | ping db PING db (23.221.222.250): 56 data bytes 64 bytes from 23.221.222.250: icmp_seq=0 ttl=50 time=42.055 ms … -
Which technique for database design is better for performance?
I need to create a Django PostgreSQL Database with a field in multiple tables to use it like a filter for the users, but I don't know what technique to use for performance. I can create a table with the field and make a foreign key for every table. class Tablefilter(models.Model): filter_field = models.Field() class Tablefilted(models.Model): table_filter = models.ForeignKey(Tablefilter) Or in my models just create a extend for that field in every model. class Tablefilter(models.Model): filter_field = models.Field() class Tablefilted(Tablefilter): field = models.Field() -
Django Value Error "seek of closed file" using PIL for image resize when updating a record
I have the following model: class Players(models.Model): team = models.ForeignKey(Teams, verbose_name=_('Team'), on_delete=models.CASCADE) player_name = models.CharField(_('Player Name'),max_length=200) player_description = models.TextField(_('Player Description')) player_image = models.ImageField(_('Profile Pic'),upload_to='upload/player_image', null=True, blank=True) player_social = models.CharField(_('Social Media Tag'),max_length=200) class Meta: verbose_name = _("Players") verbose_name_plural = _("Players") def __str__(self): return self.team.team_name + ' - ' + self.player_name def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.player_image: image_resize(self.player_image, 250) The last function will call another for image resizing taking the file and an expected max width: # Use PIL to resize images; set target width on each def image_resize(image, tgt_width): img = PIL.Image.open(image) img.load() width, height = img.size target_width = tgt_width h_coefficient = width/tgt_width target_height = height/h_coefficient img = img.resize((int(target_width), int(target_height)), PIL.Image.ANTIALIAS) img.save(image.path, quality=100) img.close() image.close() My view for updating is as follows: @method_decorator(superuser_required, name='dispatch') class PlayerUpdateView(UpdateView): model = Players template_name = 'scoreboard/players/player_update.html' form_class = PlayersForm context_object_name: str = 'player' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) team_id = Players.objects.get(pk=self.kwargs['pk']).team.id context["team"] = Teams.objects.get(pk=team_id) return context def form_valid(self, form): form.save() return super().form_valid(form) def get_success_url(self): team_id = Players.objects.get(pk=self.kwargs['pk']).team.id return reverse_lazy('team_detail', kwargs={'pk': team_id}) It doesn't matter if I provide a new image file or not, I get the same "seek of closed file" error: File "D:\00_www\hts-score\overlay\scoreboard\models.py", line 62, in save image_resize(self.player_image, 250) File "D:\00_www\hts-score\overlay\scoreboard\models.py", … -
Django3 Paginator with function based view
class ProductList(ListView): model = Product paginate_by = 8 def company_page(request, slug): ... product_list = Product.objects.filter(company=company).order_by('-pk') paginator = Paginator(product_list, 4) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'product/product_list.html', { ..., 'product_list': product_list, 'page_obj': page_obj }) views.py <nav aria-label="Pagination"> <ul class="pagination justify-content-center my-5"> {% if page_obj.has_previous %} <li class="page-item mx-auto lead"> <a class="page-link" href="?page={{page_obj.previous_page_number}}" tabindex="-1" aria-disabled="true"> Newer</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" href="#" tabindex="-1" aria-disabled="true"> Newer</a> </li> {% endif %} {% if page_obj.has_next %} <li class="page-item mx-auto lead"> <a class="page-link" href="?page={{page_obj.next_page_number}}"> Older</a> </li> {% else %} <li class="page-item disabled mx-auto lead"> <a class="page-link" href="#!"> Older</a> </li> {% endif %} </ul> </nav> product_list.html Pagination works well on ProductList view but it doesn't on company_page view. The Newer & Older buttons work but the page keeps showing every product_list objects. -
Django REST Framework - Custom action to use different serializer class, empty result
I'm trying to define a custom action which will use a different serializer class, but I'm getting an empty result from that action and I'm not sure why. I've based my action definition code on the DRF documentation, but there may be something that I'm missing, since this is new to me. I have a simple example based on Authors & Books to demonstrate this. Here is my viewset code, and the action where I think the solution may lie: class AuthorViewSet(viewsets.ModelViewSet): queryset = Author.objects.all() serializer_class = AuthorSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['first_name', 'last_name'] @action(detail=False, serializer_class=AuthorNoBookListSerializer) def no_booklist(self, request): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): return Response(serializer.data) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I have two serializers: One with each author's list of books, and one without: class AuthorSerializer(serializers.ModelSerializer): book_list = serializers.ListField(source='books') class Meta: model = Author fields = ('id', 'first_name', 'last_name', 'book_list') class AuthorNoBookListSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ('id', 'first_name', 'last_name') If I swap out serializer_class = AuthorSerializer for serializer_class = AuthorNoBookListSerializer in the viewset, I can see that both serializers work fine: Using AuthorSerializer: HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "count": 4, "next": null, "previous": null, "results": [ { "id": … -
/bin/bash: line 1: gunicorn: command not found
can anyone help us with this problem I am trying to deploy Django application on the railway but got an error /bin/bash: line 1: gunicorn: command not found my gunicorn path /usr/local/lib/python3.10/dist-packages python path ['', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/root/.local/lib/python3.10/site-packages', '/usr/local/lib/python3.10/dist-packages', '/usr/local/lib/python3.10/dist-packages/drupwn-1.0.3-py3.10.egg', '/usr/local/lib/python3.10/dist-packages/prompt_toolkit-2.0.7-py3.10.egg', '/root/droopescan', '/usr/lib/python3/dist-packages', '/usr/lib/python3.10/dist-packages'] I tried to add a path but I am not able to do it. Can anyone please help me to solve this problem? -
Error while working on the site in Django
This is a continuation of the previous question. When I continued to work on the site and when I wanted to test the site through "python manage.py runserver" in the C:\mysite\site\miniproject directory, the following error pops up: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Program Files\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Program Files\Python36\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Program Files\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Program Files\Python36\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Program Files\Python36\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Program Files\Python36\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files\Python36\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Program Files\Python36\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 674, in exec_module File "<frozen importlib._bootstrap_external>", line 781, in get_code File "<frozen importlib._bootstrap_external>", line 741, in source_to_code File "<frozen … -
Django: Handling of duplicated values on unique rows
I have a row of data and in it consist of Protein object. Protein Object has unique protein_id (not PK) and rows of data can have repeatable protein object. So when a user creates a row of data say Data: {'protein_id':ABC123} if the given protein_id already exists in database, we'll use that protein object. I am able to create the protein object when it does not exist in database. But when it already exist, I am getting "protein with this protein id already exists.". I understand that this happens because I am creating new protein object with the same protein_id and protein_id has a unique=True attribute. But what I am not understanding is (Refer below for details) why I am unable to get the object if exist or why is the exception getting thrown (Not sure whats the logic behind). Models.py class Protein(models.Model): protein_id = models.CharField(max_length=256, null=False, blank=False,unique=True) sequence = models.CharField(max_length=40000,blank=True) Serializer.py class ProteinSerializer(serializers.ModelSerializer): class Meta: model = Protein fields = ['protein_id',"sequence"] def create(self,validated_data): protein_data = validated_data.pop('protein') protein = None try: protein = Protein.objects.get(protein_id=protein_data['protein_id']) except Protein.DoesNotExist: protein = Protein.objects.create(**protein_data) return protein What I have tried here is a try-except where the serializer will first get the protein object in database … -
Django : get context data dynamically
I'm working on a music web app and trying to display chart (with Chart.js) for genres by family (ie indie Rock genre is in the rock family). I have 14 families (Rock, Metal, Jazz, etc...) and want to be able to select one of them to display how many albums for each genre of the family selected. So here's my code: My View, in which I send metal, rock and hip hop families genres and album number in the context : class StatsAlbumView(ListView): model = Album queryset = Album.objects.all() template_name = "statistic/album.html" context_object_name = "albums" def get_queryset(self): queryset = super().get_queryset() self.filterset = AlbumFilter(self.request.GET, queryset=queryset) return self.filterset.qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) all_families = api.get_all_families() context['all_families'] = all_families metal, albums_metal = api.get_album_by_family_genres("Metal") context['metal'] = metal context['albums_metal'] = albums_metal rock, albums_rock = api.get_album_by_family_genres("Rock") context['rock'] = rock context['albums_rock'] = albums_rock hip_hop, albums_hip_hop = api.get_album_by_family_genres("Hip-Hop") context['hip_hop'] = hip_hop context['albums_hip_hop'] = albums_hip_hop context['form'] = self.filterset.form return context My api file in which I get the data I need : def get_album_by_family_genres(family): genres = Genre.objects.filter(family=family) albums = Album.objects.all() albums_from_family = [] for album in albums: album_list_genre = list(album.genre_primary.all()) for genre in album_list_genre: if genre in genres: albums_from_family.append(album) print(albums_from_family) if albums_from_family: list_genres, list_albums_number = get_album_by_primary_genre(albums_from_family, family) … -
How to use function of a class as decorator which itself takes a parameter in python?
I tried this below snippet as an experiment as how decorators can be used in various scenario , here without s variable the the whole code is working but when I add an argument in decorator function is shows error message. class dec(object): def __init__(self, str1, str2): self.str1 = str1 self.str2 = str2 print(f"printing from init via ----- str1={self.str1} , str2={self.str2}") def onef(self,f,s): print(f"printing from init via onef ----- str1={self.str1} , str2={self.str2}") print("onef --------- up") f() print(f"printing s = {s}") print("onef --------- down") d=dec(str1='Hey',str2='hi') @d.onef(s='in onef ok !') def f(): print("The F --- function") error message printing from init via ----- str1=Hey , str2=hi Traceback (most recent call last): File "C:\Users\Anuj\Desktop\decorators.py", line 16, in <module> @d.onef(s='in onef ok !') TypeError: dec.onef() missing 1 required positional argument: 'f' Previously tried this one. class dec(object): def __init__(self, str1, str2): self.str1 = str1 self.str2 = str2 print(f"printing from init via ----- str1={self.str1} , str2={self.str2}") def onef(self,f): print(f"printing from init via onef ----- str1={self.str1} , str2={self.str2}") print("onef --------- up") f() print("onef --------- down") d=dec(str1='Hey',str2='hi') @d.onef def f(): print("The F --- function") It worked. Answer printing from init via ----- str1=Hey , str2=hi printing from init via onef ----- str1=Hey , str2=hi onef --------- up … -
How to use js on change event with formset django?
There are task types in the field I created with formset. I want to create a new form for the user according to the task types selection. For example, when the user selects the product purchase, I want to copy the same form again. Based on my research i found out that i need to use on change for this but I have no idea how to implement it. Here is my forms : class UserTaskForm(forms.ModelForm): class Meta: model = UserTask fields = ['user_id','task_types_id','store_house_id','description'] UserTaskFormFormSet = modelformset_factory( UserTask, fields=('user_id','task_types_id','store_house_id','description',), extra=1, ) here is my html : {% extends "main/layout.html" %} {% load crispy_forms_tags %} {% block content %} <div class="row"> <div class="col-md-6 offset-md-3"> <h3 align="center">Add New Task</h3> <hr> <form id="form-container" method="POST"> {% csrf_token %} {{ user_task_form.management_form }} {% for user_form in user_task_form %} <div class="usertask-form" id="usertask-form"> {{user_form | crispy}} </div> {% endfor %} {{ formset.management_form }} {% for form in formset %} <div class="tasksources-form" id="tasksources-form"> {{form | crispy}} </div> {% endfor %} <button id="add-form" class="btn btn-success">+Add More Product</button> <br> <br> <button type="submit" class="btn btn-outline-info">Add New Task</button> </form> </div> </div> <script> let tasksourcesForm = document.querySelectorAll(".tasksources-form") let container = document.querySelector("#form-container") let addButton = document.querySelector("#add-form") let totalForms = document.querySelector("#id_formset-TOTAL_FORMS") let formNum = tasksourcesForm.length-1 … -
Extending django-graphql-auth to constrain username, passwords and emails
I am using Django v 3.2 and django-graphql-auth v 0.3.16 I have a custom User (and User Manager) defined like this: models.py class CustomUser(AbstractUser): USERNAME_FIELD='username' EMAIL_FIELD='email' # ... objects = CustomUserManager() managers.py class CustomUserManager(BaseUserManager): # ... def create_user(self, email, password, **extra_fields): if not is_valid_email(email): raise ValueError(_('Bad email')) username = extra_fields.get('username') if not is_acceptable_username(username)): raise ValueError(_('You cannot use this username')) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) settings.py # .... AUTH_USER_MODEL='myapp.CustomUser' schema.py import graphene from graphql_auth import mutations from graphql_auth.schema import MeQuery, UserQuery class AuthMutation(graphene.ObjectType): register = mutations.Register.Field() verify_account = mutations.VerifyAccount.Field() class Query(UserQuery, MeQuery, graphene.ObjectType): pass class Mutation(AuthMutation, graphene.ObjectType): pass schema = graphene.Schema(query=Query, mutation=Mutation) I try to register a new user through the following mutation: mutation { register( email: "memyself@somebad-domain.com", username: "badword1", password1: "1234", password2: "1234" ) { success errors token } } And I get the following response: { "data": { "register": { "success": true, "errors": null, "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImJhZHdvcmQxIiwiZXhwIjoxNjY5OTEzNDIzLCJvcmlnSWF0IjoxNjY5OTEzMTIzfQ.TZ-copVrhUUsuLpozi18THjprGMnAGsBwpnyWORc16M" } } … -
Django How To Add Number From Other Object
How can i add an int value inside of a field in multiple object to be displayed in another object. Lets say that i need to add all of the item that the customer have ordered previously and store them inside of all_previous_orders. Result.json [ { "customer_name": "John Doe", "order": [ { "order_name": "fruit", "how_many_order": 10, }, { "order_name": "car", "how_many_order": 1, }, ], "all_previous_orders": 11 }, ] Models.py class Customer(models.Model): customer_name = models.CharField(max_length=100) class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) order_name = models.CharField(max_length=100) how_many_order = models.IntegerField(default=0) Serializers.py class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = '__all__' class CustomerSerializer(serializers.ModelSerializer): orders = OrderSerializer(many=True, read_only=True, required=False) class Meta: model = Customer fields = '__all__'