Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Check if request.POST field is empty
I have a form that may be submitted with some fields as blank/empty values, but when I run: if request.POST['field']: it always returns true, even if the field has not been filled in, how can I check if a field has been completed or left blank? -
I'm following Python Fullstack by Perrian data facing error with Faker libararies
raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. from faker import Faker import os os.environ.setdefault('DJANGO_SETTINGD_MODULE','first_project.settigs' ) import django django.setup() # rand numbers import random from first_app.models import AccessRecord,WebPage,Topic error :- facing django.setup() error file structure:- file Structure total code:- code -
fetching specific data from JSON with python
I want to fetch specific data form JSON . Right now I can fetch all of the data and convert it into JSON format. But I only want to fetch "home_team" and "away_team" of all the sets. My code to fetch all of the data is:` import json import requests reap = requests.get('https://app.sportdataapi.com/api/v1/soccer/matches?apikey=64572f90-88d6-11eb-8a43-7106c933e99d&season_id=496&date_from=2020-09-19&fbclid=IwAR2zkLfVHG1xyxCrKQdcvCqhYhyjp5vA2TtbAsXZ3R3pVFJKV3jnhgFdjG4') data = reap.json() print(data) And my JSON data is: {'query': {'apikey': '64572f90-88d6-11eb-8a43-7106c933e99d', 'season_id': '496', 'date_from': '2020-09-19', 'fbclid': 'IwAR2zkLfVHG1xyxCrKQdcvCqhYhyjp5vA2TtbAsXZ3R3pVFJKV3jnhgFdjG4'}, 'data': [{'match_id': 139415, 'status_code': 3, 'status': 'finished', 'match_start': '2020-09-19 13:30:00', 'match_start_iso': '2020-09-19T13:30:00+00:00', 'minute': None, 'league_id': 314, 'season_id': 496, 'stage': {'stage_id': 1, 'name': 'Regular Season'}, 'group': {'group_id': 222, 'group_name': 'Bundesliga'}, 'round': {'round_id': 18564, 'name': '1', 'is_current': None}, 'referee_id': 433, 'home_team': {'team_id': 3993, 'name': '1. FC Union Berlin', 'short_code': 'UNI', 'common_name': '', 'logo': 'https://cdn.sportdataapi.com/images/soccer/teams/100/2819.png', 'country': {'country_id': 48, 'name': 'Germany', 'country_code': 'de', 'continent': 'Europe'}}, 'away_team': {'team_id': 4075, 'name': 'FC Augsburg', 'short_code': 'FCA', 'common_name': '', 'logo': 'https://cdn.sportdataapi.com/images/soccer/teams/100/2814.png', 'country': {'country_id': 48, 'name': 'Germany', 'country_code': 'de', 'continent': 'Europe'}}, 'stats': {'home_score': 1, 'away_score': 3, 'ht_score': '0-1', 'ft_score': '1-3', 'et_score': None, 'ps_score': None}, 'venue': {'venue_id': 1870, 'name': 'An der alten Forsterei', 'capacity': 22012, 'city': 'Berlin', 'country_id': 48}}, {'match_id': 139451, 'status_code': 3, 'status': 'finished', 'match_start': '2020-09-19 13:30:00', 'match_start_iso': '2020-09-19T13:30:00+00:00', 'minute': None, 'league_id': 314, 'season_id': 496, 'stage': {'stage_id': 1, … -
post function is called twice django python
I am facing problem wherein post function of class view in django is called twice. I am doing a long operation in one of the sub functions. So after some time, post is again called. Please help me. How can I make it run once only. Thanks. -
i have a dynnamic html table so how can i add multiple rows with same name and id+1 in django database its only added first row in database
i have javascript to increment id as a +1 so how can i add those html rows into database i am trying to add those dynamiclly rows which is genrated by javascript but i am not able to add those rows please help me models.py class New_Order(models.Model): sno = models.AutoField(primary_key=True) hscode = models.CharField(max_length=50) Product_Category = models.CharField(max_length=50) Finish = models.CharField(max_length=50) Edge = models.CharField(max_length=50) Product_Name = models.CharField(max_length=50) Product_Nomenclature = models.CharField(max_length=50) Product_Type = models.CharField(max_length=50) Length = models.CharField(max_length=50) Breadth = models.CharField(max_length=50) Thickness = models.CharField(max_length=50) Patio_Pack = models.CharField(max_length=50) Crate = models.IntegerField() Measure = models.IntegerField() Measure_Unit = models.IntegerField() Pcs_or_Crate = models.IntegerField() Crate_Start = models.IntegerField() Crate_End = models.IntegerField() Crate_Buffer = models.IntegerField() Container_Qty = models.IntegerField() Percentage = models.IntegerField() Desc = models.CharField(max_length=50) Price = models.IntegerField() def __str__(self): return self.hscode i am trying through name but all name are same in dynamiclly table so those values not adding in database can you all please guide me how its possible views.py def pro(request): prod = Product_Catagory.objects.all() any = Finishe.objects.all() edg = Edge.objects.all() prodn = Product_Name.objects.all() prodnn = Product_Nomenclature.objects.all() prodt = Product_Type.objects.all() len = Length.objects.all() bre = Breadth.objects.all() thick = Thicknes.objects.all() pat = Patio_Pack.objects.all() context = {'prod':prod, 'any':any, 'edg':edg, 'prodn':prodn, 'prodnn':prodnn, 'prodt':prodt, 'len':len, 'bre':bre, 'thick':thick, 'pat':pat} if request.method == "POST": hscode = … -
How to use JQV map in Django?
I want to create a JQV country web for my dashboard. I have a Customer model and this model has a country field. This field is connected with a foreign key and I can get country codes and JQV map is accepting country codes. I created an array in my views and when I print it works. But when I put in the data field of the map chart, does not show anything. How can I fix it? models.py class Customer(models.Model): ... country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True, unique=False) class Country(models.Model): ... country_code = models.CharField(max_length=5) views.py def approval_context_processor(request): ... countries_iso = Customer.objects.values_list('country__country_code', flat=True).distinct() ... for cn in countries_iso: arr.append(cn) print(arr) // it works truely. else: pend_list = 0 submit_list = 0 context = { ... 'arr': arr } return context dashboard.html ... <div class="mapcontainer"> <div id="map-example" class="vmap" style="height: 400px"></div> </div> <script> var country_list = [] {% for country in arr %} country_list.push( '{{ country }}' ) {% endfor %} window.alert(country_list) //It works truely $('#map-example').vectorMap( { map: 'world_en', backgroundColor: 'transparent', borderColor: '#fff', borderWidth: 2, color: '#e4e4e4', enableZoom: true, hoverColor: '#35cd3a', hoverOpacity: null, normalizeFunction: 'linear', scaleColors: ['#b6d6ff', '#005ace'], selectedColor: '#35cd3a', selectedRegions: [country_list], showTooltip: true, onRegionClick: function(element, code, region) { return false; }, onResize: … -
Django Template comparing two lists of equal size
I have two lists of equal sizes like so: change_list = ['none', 'M', 'D', 'none] print_list = ['examples', 'app.py', 'list.fr', 'template'] I pass them through the view and I need to know what the value is on the first list so I can display the elements of the second one with a different color according to what's on the first list. For example, I need to display 'app.py' as orange in the template due to the 'M' in the first list. I've searched around and I have no idea how to do this. I tried to pass the len of the list as a range to the view like this: {% for i in len%} {% if changes_list.i == "M" %} <p style="color:orange;"> {{print_list.i}}</p> {% endif %} {% endfor %} But it didn't work. I'm not sure if I formulated the question correctly but I wasn't exactly sure how to explain this. Thank you in advance. -
django Rest Framework - extending user model
halo i'm having issue using django-restframework to extend user model with OneToOnfield, below is my codes and error message i'm getting a TypeError: _create_user() got an unexpected keyword argument 'school_name' shool when i try to create the user ###profile-serializer class schoolProfileSerializer(serializers.ModelSerializer): id = serializers.IntegerField(source='pk', read_only=True) parser_classes = (MultiPartParser, FormParser, ) email = serializers.CharField(source='user.email', read_only=True) username = serializers.CharField(source='user.username', read_only=True) badge = Base64Imagefield(max_length=None, use_url=True) date_established = serializers.DateField(format=None,input_formats=None) class Meta: model = Profile fields = ( 'email', 'id', 'username', 'school_name', 'address', 'badge', 'gender', 'level', 'motto') def create(self, validated_data): if 'profile' in validated_data: user_data = validated_data.pop('profile') user = CustomUser.objects._create_user(**validated_data) Profile.objects.update_or_create(user=user, **validated_data) return user ###profile-view class CreateProfileView(generics.CreateAPIView): parser_classes = (MultiPartParser,) serializer_class = schoolProfileSerializer queryset = Profile.objects.all() permission_classes = [permissions.AllowAny] profile-model class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) school_name = models.CharField(max_length=255) address = models.TextField() school_phone_number = models.CharField(max_length=25) school_email = models.EmailField() motto = models.CharField(max_length=255) @receiver(post_save, sender=CustomUser) def create_school_profile(sender, instance=None, created=False, **kwargs): if created: Profile.objects.get_or_create(user=instance) errorr-msg Traceback (most recent call last): File "/home/olaneat/Desktop/myFiles/project/django/api/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/olaneat/Desktop/myFiles/project/django/api/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/olaneat/Desktop/myFiles/project/django/api/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/olaneat/Desktop/myFiles/project/django/api/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/olaneat/Desktop/myFiles/project/django/api/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) … -
How to validate a request with nested json objects in django rest framework using serializers?
I have following request. { "customer_details": { "id": 6, // either id or below fields should be present to create new customer in database "name": "Name", "email": "email@example.com", "mobile": "1234567890", "company": "Company Name" // not mandatoy }, "delivery_address": { "id": 7, // either id or below fields should be present to create new address in database "title": "Delivery Address Title 1", "street": "Delivery Address Street 1", "suite": "Delivery Address suite 1", // not mandatoy "city": "Delivery Address city 1", "zipcode": "zipcode1", "county": "Dade", "state": "Delivery Address state 1" }, "billing_address": { "id": 8, // either id or below fields should be present to create new address in database "title": "Billing Address Title 1", "street": "Billing Address Street 1", "suite": "Billing Address suite 1", // not mandatoy "city": "Billing Address city 1", "zipcode": "zipcode2", "county": "Billing Address county 1", "state": "Billing Address state 1", "payment_method": "Cheque" } } How can I validate the above request using django serializers? -
Upvote action is performing for all the cards django
I am implementing a upvote/downvote system for my website. But while upvoting a particular project all the projects are getting upvoted. html code <div style="margin-left: 10px;margin-right: 10px;"> <div class="card-columns" > {% for marking in marking_maestro %} <div class="card "> <img class="card-img-top" src="" alt="Card image cap"> <div class="card-body"> <h5 class="card-title" name="title">{{marking.product_title}}</h5> <h5 class="card-title" name="title">{{marking.id}}</h5> <p class="card-text">Random text</p> <br> <div class="row" > <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bd-modal-lg-1">View more</button> &emsp; <a href="{% url 'invest' pk=marking.id %}";><button type="submit" class="btn btn-primary" data-toggle="modal" >Invest</button></a> </div> <br> <form method="POST" id="post-invest"> {% csrf_token %} <div class="row" > <input class="btn btn-outline-secondary" id="upvote_button" type="submit" name="upvote" value="upvote"> </div> </form> </div> <!-- for upvote --> <script> // upvote $(document).on('submit', '#post-invest',function(e){ e.preventDefault(); // amount = $('input[name="amount"]').val(); console.log("Upvote initiated="); var comment = "upvote"; $.ajax({ type:'POST', url:"{% url 'upvote' pk=marking.id %}", data:{ comment : comment, csrfmiddlewaretoken: '{{ csrf_token }}', action: 'post' }, success: function(xhr, errmsg, err){ window.location = "brand" }, error : function(xhr,errmsg,err) { $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+ " <a href='#' class='close'>&times;</a></div>"); console.log(xhr.status + ": " + xhr.responseText); } }); }); </script> </div> <div class="modal fade bd-modal-lg-1" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <center><h4>Title</h4></center> <img class="img-fluid" src="{% static 'assets/img/about/about.png' %}"> <br> <center><h4>Branding Video</h4></center> <div … -
How can a call a postgresql function from Django for live server?
Here is my postgresql function in server. CREATE OR REPLACE FUNCTION test.fn_wallet_statement(wallet text, s_date date, e_date date, p_table_name text, b_name text DEFAULT 'unknown'::text) RETURNS void LANGUAGE plpgsql AS $function$ declare v_sql_bank text :=''; v_sql1 text :=''; v_sql2 text :=''; v_sql_tmp text :=''; v_sql2_v2 text :=''; v_sql3 text :=''; ---------------------------------- v_bank text:=''; v_account_id numeric; v_closed_date date; v_closed_date_tmp date; v_closed_balance numeric; v_wallet varchar(12) := wallet; v_start_date timestamp := s_date; v_end_date timestamp := e_date; v_table_name text := p_table_name; v_excute_ind boolean; -- EXCEPTION v_error_msg text; begin v_excute_ind := true; v_end_date := v_end_date + interval '1 day'; --***********************************TESTING******************************************* raise notice 'DONE 1'; insert into test.test_user (username, wallet, current_balance) values ('user15', '01011991', 999999); raise notice 'DONE 2'; --****************************************************************************** EXCEPTION WHEN OTHERS THEN GET STACKED DIAGNOSTICS v_error_msg = PG_EXCEPTION_CONTEXT; END; $function$ ; Here is my python code in Django Portal. # POINTER @login_required(login_url = 'login') def wallet_statement(request, submit_type): run_proc_query = '''select * from test.fn_wallet_statement('017XXXXXXXXX','2020-11-11','2021-03-12','test.wallet_statement_portal_017XXXXXXXXX_007','BANK');''' run_proc_cursor = connection.cursor() run_proc_cursor.execute(run_proc_query) result = run_proc_cursor.fetchall() run_proc_cursor.close() I am unable to call the postgresql function from django. I checked that the function is not calling. But normal select query from a table working fine. Note: the same query in the DBeaver (IDE) is working and calling the function perfectly. -
different number of records in django pagination pages
I'm trying to paginate with different things to maximize elements, on the first page (5) and on all the others (maximum 6). I do like in this answer class MyPaginator(Paginator): def __init__(self, **kw): self.deltafirst = kw.pop('deltafirst', 0) Paginator.__init__(self, **kw) def page(self, number): number = self.validate_number(number) if number == 1: bottom = 0 top = self.per_page - self.deltafirst else: bottom = (number - 1) * self.per_page - self.deltafirst top = bottom + self.per_page if top + self.orphans >= self.count: top = self.count return Page(self.object_list[bottom:top], number, self) from django.core.paginator import Paginator from django.core.paginator import EmptyPage from django.core.paginator import PageNotAnInteger class NewsView(ListView): model = News template_name="mysite/news.html" paginate_by = 5 def get_context_data(self, **kwargs): context = super(NewsView, self).get_context_data(**kwargs) all_news = News.objects.all().order_by("-date_news") paginator = MyPaginator(all_news, self.paginate_by,deltafirst=1) page = self.request.GET.get('page') try: file_exams = paginator.page(page) except PageNotAnInteger: file_exams = paginator.page(1) except EmptyPage: file_exams = paginator.page(paginator.num_pages) context['all_news'] = file_exams return context But I get an error and I can't figure out what I'm doing wrong. The error itself paginator = MyPaginator(all_news, self.paginate_by,deltafirst=1) TypeError: __init__() takes 1 positional argument but 3 were given -
How Does Django Manager Orchestrate QuerySet?
This is a follow-up question from this post. For the sake of completeness and self-containment, I will include all necessary bits in this question. Consider a very simple example: # Models class Cart(models.Model): name = models.CharField(max_length=20) class Item(models.Model): name = models.CharField(max_length=20) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) # Execution class Test(TestCase): @classmethod def setUpTestData(cls): # Save a new cart c = Cart(name="MyCart") c.save() # Save two items to the cart t = Item(name="item1", cart=c) t.save() Item.objects.create(name="item2", cart=c) def simpleTest(self): i = Item.objects.get(id=2) # <--- breakpoint # Do something, but not important for this question I am using PyCharm to try to understand the inner workings of Django. If we put a breakpoint at the marked line and step into the method call get(). After we get a Manager from __get__ in ManagerDescriptor (due to .objects), the execution now goes to this class method in BaseManager: @classmethod def _get_queryset_methods(cls, queryset_class): def create_method(name, method): def manager_method(self, *args, **kwargs): return getattr(self.get_queryset(), name)(*args, **kwargs) # <--- Starts here manager_method.__name__ = method.__name__ manager_method.__doc__ = method.__doc__ return manager_method The execution stops at the marked line above. If we step into it, get_queryset() is first called, which returns a new QuerySet object, as expected. Note that the new QuerySet … -
How do I allow only the owner of a an item to do something with it?
Could anyone explain to me how to do it? I've been trying for a while without managing to do it. I am just trying to restrict permissions so that not anyone with the right link can edit/delete a particular object models.py: class Items(models.Model): author = models.ForeignKey( 'auth.User', on_delete=models.CASCADE, null=True) name = models.CharField(max_length=256) description = RichTextField(blank=True, null=True) url = models.URLField(null=True, blank=True) image = models.ImageField(null=True, blank=True) class Meta: ordering = ['name'] def __str__(self): return self.name and views.py class SiteList(ListView): model = Items class SiteUpdate(LoginRequiredMixin, UpdateView): model = Items form_class = SiteUpdateForm success_url = reverse_lazy('portfolio:sitelist') class SiteDelete(DeleteView): model = Items success_url = reverse_lazy('portfolio:sitelist') -
django template tag add double quotes to the url generated
In index.html : <a href={% url 'clm:clmmap' %}" class="button">Empezemos</a> A click in the button "Empezemos" generates a URL http://localhost:8001/clm/map/%22 (not found error is launched) when it should be http://localhost:8001/clm/map/ , without the %22 (double quote). the urls.py: urlpatterns = [ path('map/', CLMMapView.as_view(), name='clmmap'), and the views.py: class CLMMapView(TemplateView): template_name = 'clm.html' def get_context_data(self, **kwargs): ... so, why a double quote is added to the URL? -
No module named '_pywrap_tensorflow_internal' and website does not work
I try to import Tensorflow, but I get this error: Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper fp, pathname, description = imp.find_module('_pywrap_tensorflow_internal', [dirname(file)]) File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\imp.py", line 297, in find_module raise ImportError(_ERR_MSG.format(name), name=name) ImportError: No module named '_pywrap_tensorflow_internal' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in from tensorflow.python.pywrap_tensorflow_internal import * File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in _pywrap_tensorflow_internal = swig_import_helper() File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper import _pywrap_tensorflow_internal ModuleNotFoundError: No module named '_pywrap_tensorflow_internal' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<pyshell#1>", line 1, in import tensorflow File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow_init_.py", line 24, in from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python_init_.py", line 49, in from tensorflow.python import pywrap_tensorflow File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in raise ImportError(msg) ImportError: Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper fp, pathname, description = imp.find_module('_pywrap_tensorflow_internal', [dirname(file)]) File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\imp.py", line 297, in find_module raise ImportError(_ERR_MSG.format(name), name=name) ImportError: No module named '_pywrap_tensorflow_internal' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in from tensorflow.python.pywrap_tensorflow_internal import * File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in _pywrap_tensorflow_internal = swig_import_helper() File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line … -
Merge two redundant models in Django
I'm working on an online shop at the moment. The shop is written in Django, and was programmed by another person, so I spent days trying to make sense of what he did. At the moment the shop sells only two articles, on two different pages (meaning they have to be bought separately), so the shop is heavily oriented towards this situation. The problem is, the shop's owner expressed his interest in selling everything in one page in the near future, and in adding more products. And that's where my problems start. The model structure was something like this (extremely simplified): class Category1(BaseModel): name = models.CharField(max_length=32) class Category2(BaseModel): name = models.CharField(max_length=64) class Price1(BaseModel): category = models.ForeignKey(Category1, on_delete=models.CASCADE) price = models.DecimalField(max_digits=16, decimal_places=2) currency = models.CharField(max_length=3) class Price2(BaseModel): category = models.ForeignKey(Category2, on_delete=models.CASCADE) price = models.DecimalField(max_digits=16, decimal_places=2) currency = models.CharField(max_length=3) class Order1(BaseModel): [personal information fields] class Order2(BaseModel): [personal information fields] class Article1(BaseModel): price = models.ForeignKey(Price1, on_delete=models.CASCADE) order = models.ForeignKey(Order1, on_delete=models.CASCADE, related_name='articles') class Article2(BaseModel): price = models.ForeignKey(Price2, on_delete=models.CASCADE) order = models.ForeignKey(Order2, on_delete=models.CASCADE, related_name='articles') There is much more than this, of course, but this should be enough to show the relationships between the models. The complete structure of course makes more sense than this one. … -
Bootstrap modal not showing (taken from the official website) using Django
I have the following HTML code in Django template. I used the example from Boostrap website to create a button that shows a modal ,however, when I press the button, nothing happens. I'm not sure why nothing happens and also no error shows in the console. My 'static' folder contains: bootstrap.min.css and bootstrap.min.css.map. <!doctype html> <html lang="en"> <head> {% load static %} <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="{% static "css/bootstrap.min.css" %}" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <title>Dashboard</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="/"><img src="{% static "img/logo.png" %}" style='max-width:100px'></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-item nav-link" href="{% url 'admin:logout' %}?next=/" tabindex="-1" aria-disabled="true">Instances</a> </div> </div> </nav> <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> New Instance </button> <button type="button" class="btn btn-danger">Delete Instance</button> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> This is a test! </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> </body> </html> -
Django unable to revert migration that creates objects when a new field is added
I'm creating a table that should contain a fixed set of data, so not really user data. My initial migration creates the table with all the columns and I added RunPython code to populate the fixed data, something along these lines: from django.db import migrations, models import my_app.model.a_model def create_initial_data(apps, schema_editor): AModel = apps.get_model('my_app', 'AModel') AModel.objects.create( field_2='a value', ) AModel.objects.create( field_2='another value', ) class Migration(migrations.Migration): dependencies = [ ('my_app', '0008_a_migration'), ] operations = [ migrations.CreateModel( name='AModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('field_2', models.CharField(max_length=64, unique=True)), ], options={ 'db_table': 'a_model', }, ), migrations.RunPython(create_initial_data, reverse_code=migrations.RunPython.noop), ] However, if I add a field to the model AModel in a subsequent migration, say 0018_a_migration, I become unable to revert the migration 0008_a_migration with the python code that contains the new column (i.e. I have to comment out the new code to revert the old migration). A solution would be to not use ORM and just write SQL directly inside create_initial_data, I am aware. Is there another way of solving this issue, without writing raw SQL? -
How to calculate monthly fees , pending fees and payable amount in django?
Please help me. I'm planning to create a Student Mangement RestAPI in Django. Kindly suggest me how to create and how to solve this? Models.py :- class Batch(models.Model): batch_name=models.CharField(max_length=255) batch_date=models.DateTimeField(auto_now_add=True) batch_fees=models.DecimalField(max_digits=10, decimal_places=2) def __str__ (self): return self.batch_name class Teacher(models.Model): tech_name=models.CharField(max_length=255) tech_created_date=models.DateTimeField(auto_now_add=True) tech_join_date=models.DateField(blank=False) def __str__ (self): return self.tech_name class Student(models.Model): std_name=models.CharField(max_length=255) std_father_Name=models.CharField(max_length=255, blank=True) std_mother_Name=models.CharField(max_length=255, blank=True) std_date_of_birth=models.DateField(blank=False) std_join_date=models.DateField(blank=False) std_created_date=models.DateTimeField(auto_now_add=True) std_image=models.ImageField(upload_to='./static/prj_static_files/images', blank=True) std_batch=models.ForeignKey(Batch, on_delete=models.CASCADE) std_teacher=models.ForeignKey(Teacher, on_delete=models.DO_NOTHING) std_fees =models.DecimalField(max_digits=10, decimal_places=2) std_pending_fees =models.DecimalField(max_digits=10, decimal_places=2) i need to create monthly fees , pending fees and payable amount how to add batch_fees in to Calculate and put in to std_fees,std_pending_fees -
Django Rest Framework: Add hyperlink related field on sub model
Im trying to find out how I can add hyperlink related field from a relationship model. Lets say i have the following models: class Model1(models.Model): id = models.AutoField(primary_key=True) model2 = models.OneToOneField(Model2, db_column='model2_id', related_name='model2_set', on_delete=CASCADE) class Model2(models.Model): id = models.AutoField(primary_key=True) model3 = models.ForeignKey(Model3, db_column='model3_id', related_name='+', null=True, blank=True, on_delete=FOREIGNKEY_PROTECT) class Model3(models.Model): id = models.AutoField(primary_key=True) description = models.TextField(db_column='description', null=True, blank=True, verbose_name=_('Description')) and I have a serializer for both Model1 and Model3 but not Model2 I want to have the following output { "id":123, "model3":"http://example:123/api/model3/123" } but in my model1 serializer i cant simply call a hyperlinkrelated field for a sub model because it cannot identify the source class Model1ListSerializer(ValidateByModelSerializer): id = serializers.IntegerField(read_only=True) model3 = serializers.HyperlinkedRelatedField( source='model2__model3', queryset=Model3.objects.all(), view_name='model3_rest-detail' ) Whats the best way to achieve this? -
django installation not working in virtual environment
I created a virtual environment and installed django in it using pip. In a python shell in the v.e. I can import django and print its version, but when trying to start a project or do a django-admin --version I get the following error: bash: /usr/bin/django-admin: No such file or directory Here are the steps I took before: sudo apt-get install python3-venv python3 -m venv my_env source my_env/bin/activate sudo apt install python3-pip -y pip --version sudo apt install python3-django django-admin --version --> ModuleNotFoundError: No module named 'django' sudo apt remove python3-django pip install django --> Successfully installed asgiref-3.3.1 django-3.1.7 pytz-2021.1 sqlparse-0.4.1 django-admin --version --> bash: /usr/bin/django-admin: No such file or directory -
react's styling overriden in django template
I am trying to build a django / react hybrid app as per the guide here: https://www.saaspegasus.com/guides/modern-javascript-for-django-developers/integrating-javascript-pipeline/ and using react components from the @elastic/search-ui, specifically trying to replicate the following example in one of my django templates: https://codesandbox.io/s/getting-started-y9tnd So one of the django templates has the react search ui embedded and running from js bundle built using webpack. The problem is that it seems the search-ui's nice styling is overriden by the bootstrap styling I use for all django templates. Django template part: es_list_react.html {% extends "base_generic.html" %} {% block content %} Test React component <hr> {% load static %} <div id ='root'></div> <script src="{% static 'ui-react-build/index-bundle.js' %}"> </script> {% endblock %} base_generic.html <!DOCTYPE html> <html lang="en"> <head> ... {% load static %} <!-- Bootstrap core CSS --> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> ... </head> <body> ... </body> </html> React (search-ui) part: index.js import React from "react"; import ReactDOM from "react-dom"; import App from "./App"; ReactDOM.render(<App />, document.getElementById("root")); App.js ... import "@elastic/react-search-ui-views/lib/styles/styles.css"; ... What could be a root cause and a solution to the problem? The styling seems to be actually making it to the js bundle created by webpack: index-bundle.js ... ***/ "./node_modules/@elastic/react-search-ui-views/lib/styles/styles.css": /*!***************************************************************************!*\ !*** ./node_modules/@elastic/react-search-ui-views/lib/styles/styles.css ***! \***************************************************************************/ … -
Django admin annotation is multiplied if search_field (by related FK),
i have problem with multiplation of annotation... if i use search_field by email useremail__email (related fk of user model) ... then my annotation is multipled the problem is if the table with profileemails is joined (without search it works just good) in example: i have user named admin and emails.. admin1, admin2, admin3 then search is done by admin the result is sum * 3 (because 3 emails) my model: class Payment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) amount = models.IntegerField() class SubPayment(models.Model): payment = models.ForeignKey(Payment, on_delete=models.CASCADE) amount = models.IntegerField() class UserEmail(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) email = models.CharField(max_length=128) in admin i have User model where i want to display sum and count of subpayments: class UserAdmin(admin.ModelAdmin): list_display = ("username", "payment_count", "payment_sum") search_fields = ( 'useremail__email', 'username' ) def payment_count(self, obj): return obj.payment_count def payment_sum(self, obj): return obj.payment_sum def get_queryset(self, request, *args, **kwargs): queryset = super().get_queryset(request, *args, **kwargs).annotate( payment_amount=Sum('payment__amount'), payment_count=Count('payment__subpayment'), payment_sum=Sum('payment__subpayment__amount'), ) return queryset I tried use distinct=True , but it remove duplicite subpayments with same amount... tried on django 2.2 and 3.17 works good: works wrong: Any help? Thanks! -
wfastcgi-enable show massage like this "Ensure your user has sufficient privileges and try again."
I finished my Django website and I want to deploy it in window server 2008. I follow this tutorial https://www.youtube.com/watch?v=CpFU16KrJcQ&t=306s but stuck at wfastcgi-enable It show message like this