Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to render multiple matplotlib graph in django templates
in my views.py def Home(request): covid19 = COVID19Py.COVID19() data = covid19.getAll(timelines=True) virusdata = dict(data['latest']) values = list(virusdata.values()) print(values) names = list(virusdata.keys()) print(names) plt.bar(range(len(virusdata)), values , tick_label= names) buffer = BytesIO() plt.savefig(buffer, format='png') buffer.seek(0) image_png = buffer.getvalue() buffer.close() graphic = base64.b64encode(image_png) graphic = graphic.decode('utf-8') context = { 'graphic':graphic,'virusdata':virusdata } location = covid19.getLocationByCountryCode("IN") loc_data = location[0] virusdata1 = dict(loc_data['latest']) values1 = list(virusdata1.values()) print(values1) names1 = list(virusdata1.keys()) print(names1) plt.bar(range(len(virusdata1)), values1 , tick_label= names1) buffer = BytesIO() plt.savefig(buffer, format='png') buffer.seek(0) image_png = buffer.getvalue() buffer.close() graphic1 = base64.b64encode(image_png) graphic1 = graphic1.decode('utf-8') ind = {'virusdata1':virusdata1,'graphic1':graphic1 } context.update(ind) return render(request,"crona/index.html",context) in my templates {% block body %} <div class="jumbotron"> <p class="display-6 ">worldwide <span style="font-size:16px;" class="text-danger"></span></p> <div class="row"> {% for key , value in virusdata.items %} <div class="box"> <h4 class="display-6 text-center">{{ key }}</h4> <h2 class="text-primary text-center">{{ value }}</h2> </div> {% endfor %} <img src="data:image/png;base64,{{ graphic|safe }}"> </div> </div> <p class="display-6 ">India <span style="font-size:16px;" class="text-danger"></span></p> <div class="row"> {% for key , value in virusdata1.items %} <div class="box"> <h4 class="display-6 text-center">{{ key }}</h4> <h2 class="text-primary text-center">{{ value }}</h2> </div> {% endfor %} <img src="data:image/png;base64,{{ graphic1|safe }}"> </div> </div> <hr class="my-4"> <div > </div> {% endblock %} How to render multiple matplotlib graph in django templates How to render multiple matplotlib … -
Django: Cast CharField to Integer if possible
I have the following code to cast a field my_field into integer for sorting. self.object_list = self.object_list.annotate(order_field=Cast('my_field', IntegerField())) \ .order_by('order_field') The problem is that some data fields may be non-numeric, due to which it throws an error. Is there a way to Cast only if possible? I am looking for two cases - Return the full object_list, ordering those which are possible and keeping the others in the front/end. Return only the object_list where my_field can be casted to integer -
I got this error while uploading django project to pythonware
25/03/2020 https://www.pythonanywhere.com/user/rohanhirwe32/files/var/log/rohanhirwe32.pythonanywhere.com.error.log https://www.pythonanywhere.com/user/rohanhirwe32/files/var/log/rohanhirwe32.pythonanywhere.com.error.log 1/1 2020-03-25 08:19:48,249: Error running WSGI application 2020-03-25 08:19:48,263: ModuleNotFoundError: No module named 'bootstrap4' 2020-03-25 08:19:48,263: File "/var/www/rohanhirwe32_pythonanywhere_com_wsgi.py", line 15, in 2020-03-25 08:19:48,264: application = get_wsgi_application() 2020-03-25 08:19:48,264: 2020-03-25 08:19:48,264: File "/usr/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2020-03-25 08:19:48,264: django.setup(set_prefix=False) 2020-03-25 08:19:48,264: 2020-03-25 08:19:48,265: File "/usr/lib/python3.6/site-packages/django/init.py", line 24, in setup 2020-03-25 08:19:48,265: apps.populate(settings.INSTALLED_APPS) 2020-03-25 08:19:48,265: 2020-03-25 08:19:48,265: File "/usr/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate 2020-03-25 08:19:48,265: app_config = AppConfig.create(entry) 2020-03-25 08:19:48,265: 2020-03-25 08:19:48,266: File "/usr/lib/python3.6/site-packages/django/apps/config.py", line 90, in create 2020-03-25 08:19:48,266: module = import_module(entry) 2020-03-25 08:19:48,266: *************************************************** 2020-03-25 08:19:48,266: If you're seeing an import error and don't know why, 2020-03-25 08:19:48,267: we have a dedicated help page to help you debug: 2020-03-25 08:19:48,267: https://help.pythonanywhere.com/pages/DebuggingImportError/ 2020-03-25 08:19:48,267: *************************************************** 2020-03-25 08:19:50,917: Error running WSGI application 2020-03-25 08:19:50,917: ModuleNotFoundError: No module named 'bootstrap4' 2020-03-25 08:19:50,918: File "/var/www/rohanhirwe32_pythonanywhere_com_wsgi.py", line 15, in 2020-03-25 08:19:50,918: application = get_wsgi_application() 2020-03-25 08:19:50,918: 2020-03-25 08:19:50,918: File "/usr/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2020-03-25 08:19:50,918: django.setup(set_prefix=False) 2020-03-25 08:19:50,919: 2020-03-25 08:19:50,919: File "/usr/lib/python3.6/site-packages/django/init.py", line 24, in setup 2020-03-25 08:19:50,919: apps.populate(settings.INSTALLED_APPS) 2020-03-25 08:19:50,919: 2020-03-25 08:19:50,919: File "/usr/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate 2020-03-25 08:19:50,919: app_config = AppConfig.create(entry) 2020-03-25 08:19:50,919: 2020-03-25 08:19:50,920: File "/usr/lib/python3.6/site-packages/django/apps/config.py", line 90, in create 2020-03-25 08:19:50,920: module = import_module(entry) 2020-03-25 … -
Converting Tokenize2 JSON Searchfunction from PHP into Python
Hey I´m trying to convert a searchfunction code written in PHP from a Jquery Plugin called Tokenizer2 into Python. These are 2 Links to the Plugin: https://dragonofmercy.github.io/Tokenize2/config.html https://www.jqueryscript.net/form/Dynamic-Autocomplete-Tag-Input-Plugin-For-jQuery-Tokenize2.html (there ist the PHP code from) I have tested everything with PHP locally and it is working fine. I need this Plugin to put Userinput into Tokens (obviously) and because im using a Django backend I´m trying to convert the following PHP-Code (which is used to search a JSON for the userinput) into python, but I´m having some problems doing so. So this is the PHP-Code: <?php header('content-type: text/json'); $search = preg_quote(isset($_REQUEST['search']) ? $_REQUEST['search'] : ''); $start = (isset($_REQUEST['start']) ? $_REQUEST['start'] : 1; $obj = json_decode(file_get_contents('tagginglist.json'), true); $ret = array(); foreach($obj as $item) { if(preg_match('/' . ($start ? '^' : '') . $search . '/i', $item['text'])) { $ret[] = array('value' => $item['text'], 'text' => $item['text']); } } echo json_encode($ret); And this is my attempt convert this into python: import re import request import json r = request.head('tagginglist.py') search = re.escape(request['search']) start = request['start'] x = request.get('tagginglist.py') obj = x.json() ret = {} for item in obj: if re.match (re.compile('/' + (start '^' : '')) + search + '\i', item['text'])) ret = {'value' … -
Sending Video Stream from Front-end(angularjs) to Backend(Django)
I want to pass video frame from Front-end(angularjs) to Back-end(Django) for video sreaming. for that I had followed below link. https://github.com/aiortc/aiortc/tree/master/examples/server for Django,I had used Django-celery Tasks for asynchronuos function. I tried to pass RtcPeerConnection object(as arguement) into celery task that time I got below error TypeError: Object of type RTCPeerConnection is not JSON serializable Traceback (most recent call last): File "/home/loksun/.local/lib/python3.6/site-packages/kombu/serialization.py", line 50, in _reraise_errors yield File "/home/loksun/.local/lib/python3.6/site-packages/kombu/serialization.py", line 221, in dumps payload = encoder(data) File "/home/loksun/.local/lib/python3.6/site-packages/kombu/utils/json.py", line 70, in dumps **dict(default_kwargs, **kwargs)) File "/usr/lib/python3/dist-packages/simplejson/init.py", line 399, in dumps **kw).encode(obj) File "/usr/lib/python3/dist-packages/simplejson/encoder.py", line 291, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python3/dist-packages/simplejson/encoder.py", line 373, in iterencode return _iterencode(o, 0) File "/home/loksun/.local/lib/python3.6/site-packages/kombu/utils/json.py", line 59, in default return super(JSONEncoder, self).default(o) File "/usr/lib/python3/dist-packages/simplejson/encoder.py", line 268, in default o.class.name) TypeError: Object of type RTCPeerConnection is not JSON serializable Any hint will be appreciated. Thank you! -
NoReverseMatch Error for a pattern that exists
I am making a simple login logout app in django. I am getting a NoReverseMatch error claiming a pattern name doesn't exist, but it does. My project directory looks like this: dryrun_root -db.sqlite3 -manage.py -dryrun -asgi.py -init.py -py_cache -settings.py -urls.py -wsgi.py -dryapp -admin -apps.py -init.py -migrations -models.py -py_cache -static -templates -base.html -dryapp -home.html -login.html -tests.py -urls.py -views.py dryapp/views.py from django.views.generic import TemplateView from django.shortcuts import render # Create your views here. class HomePageView(TemplateView): template_name = 'dryapp/home.html' dryapp/urls.py from django.conf.urls import url from .views import HomePageView app_name="dryapp" urlpatterns = [ url('', HomePageView.as_view(), name='_home'), ] dryapp/templates/dryapp/home.html {% extends 'base.html' %} {% block head %} <title>Home Page</title> {% endblock %} {% block body %} <div class="container"> <h1>Home</h1> </div> <div> <small class="text-muted"> <a class="ml-2" href="{% url 'login' %}">Click here to log in</a> </small> </div> {% endblock %} Now, this displays just fine. But the next template does not. dryapp/templates/dryapp/login.html {% block body %} <div class="container"> <h1>Welcome!</h1> <p>You can login here.</p> <h2>Login</h2> <form method="post"> {{ form.as_p }} {% csrf_token %} <button type="submit">Login</button> </form> </div> <div class="border-top pt-3"> <small class="text-muted"> No Account? Let's Change That <a class="ml-2" href="{% url '_home' %}">Sign Up</a> </small> </div> {% endblock %} This template will not load. I keep getting the … -
How to apply background image in sending email using django
I hope the title is enough to understand my problem. i just want to add in my email_html background image. this is my email_html {% load static %} <!DOCTYPE html> <html> <head> <style> body { background-image: url('https://myschoolapp.school.com/static/emailbackground.jpg'); background-repeat: repeat-y no-repeat; margin: 0; padding: 0; } </style> </head> <body> <table width="100%" border="0" cellspacing="0" cellpadding="20"> <tr> <td> <p>Content on a pretty background image.</p> </td> </tr> </table> </body> </html> -
How to access url path in django view
How can I access the url in a django view. I have a view handling following 5 urls: localhost:8000/standings/ localhost:8000/standings/q1 localhost:8000/standings/q2 localhost:8000/standings/q3 localhost:8000/standings/q4 and my view is class StandingsView(LoginRequiredMixin, TemplateView): template_name = 'standings.html' Based on q1, q2, q3, q4 or None in the url path, I have to query data from the db and render to the given template. Please suggest on how such scenarios can be handled. -
how to implement mouse over feature in django app?
hope you all are safe from corona virus! I'm creating a Django app in which i want to implement the following functionality: "When person mouses over a target word, a pop-up window shows up with a short definition of the word" Can anyone help me in this or share any tutorial or reference link? -
Dango : Andministration page do not diplay user new well
I am learning Django 2.2, I am trying to display the user name of my model named 'Profile' but instead I have : Profile objet(3), Profile Object(4) Here is the code in Profile Apps=> models.py : from django.db import models from profiles.models import Profile from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. class Skill(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) name = models.CharField(max_length=220) score = models.PositiveIntegerField( validators=[MinValueValidator(1), MaxValueValidator(5)]) def __str__(self): return "{}-{}-{}".format(self.user, self.name, self.score) Here is the code in Profile Apps=> admin.py : from django.contrib import admin from .models import Profile # Register your models here. admin.site.register(Profile) Here is the code in Profile Apps=> init.py : default_app_config = "profiles.apps.ProfilesConfig" I have this, instead of user name: -
Django DateTimeField and User Input fields not added
I am beginner to python Django. I'm working on practice project. I got stuck while adding a product. Its adds all the fields except two fields i. DateTimeField ii. User (who add the product) The error which i'm facing is: django.db.utils.IntegrityError: null value in column "pub_date" violates not-null constraint DETAIL: Failing row contains (3, Piano, Ball Pens(set of 3), 15, 30, 10, images/ballpens_QdhwoOa.jpg, null, null). models.py class Product(models.Model): companyName = models.CharField(max_length=255) pro_name = models.CharField(max_length=255) Purchase_Price = models.IntegerField() Sale_Price = models.IntegerField() Quantity = models.IntegerField() Picture = models.ImageField(upload_to='images/') saler = models.ForeignKey(User, on_delete=models.CASCADE) pub_date = models.DateTimeField() def pub_date_pretty(self): return self.pub_date.strftime('%b %e %Y') def __str__(self): return self.pro_name views.py class AddProduct(TemplateView): template_name = 'stock/addproduct.html' def get(self, request): form = AddProductForm() args = {'form':form} return render(request, self.template_name, args) def post(self, request): form = AddProductForm(request.POST, request.FILES) if form.is_valid(): productadded = form.save() productadded.saler = request.user productadded.pub_date = timezone.datetime.now() productadded.save() return redirect('stock') else: args = {'form': form} return render(request, self.template_name, args) In views.py, I am saving a user and date and time as you see in above forms.py class AddProductForm(forms.ModelForm): class Meta: model = Product fields = ('companyName', 'pro_name', 'Purchase_Price', 'Sale_Price', 'Quantity', 'Picture' ) def __init__(self, *args, **kwargs): super(AddProductForm, self).__init__(*args, **kwargs) self.fields['companyName'].label = 'Company Name' self.fields['pro_name'].label = 'Product Name' … -
Initialise filed value to null when page loads in Django Admin panel
The following code is in models.py it is registered in admin.py class Customer(models.Model): name = models.CharField(max_length=100, null=True, blank=True, default=None,help_text="The full official name of the customer.") email = models.CharField(max_length=100, null=True, blank=False, default=None,) password = models.CharField(max_length=1000, null=True, blank=True, default=None,) name_short = models.CharField(max_length=100, null=True, blank=True, default=None,help_text="The commonly used (short) name of the customer.") country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True, blank=True, default=None,help_text="The main country code of the customer.") status = models.IntegerField(null=True, blank=True, default=None, help_text="1-2-3 temporary-registered-qualified.") sample = models.IntegerField(null=True, blank=True, default=None, help_text="1 if sample customer.") reset_password_otp = models.CharField(max_length=100, null=True, blank=True, default=None) reset_password_otp_time = models.DateTimeField(default=timezone.now) reset_password_otp_duration = models.CharField(max_length=100, null=True, blank=True, default=None) created = models.DateTimeField('created', default=timezone.now) updated = models.DateTimeField('updated', default=timezone.now) I want to initialise the password field to null when the admin page loads. -
Django Debug in VsCode
I am using Django 2.1 with the following code in vsCode-launch.json : { "name": "Python: Django", "type": "python", "request": "launch", "stopOnEntry": true, "pythonPath": "${config:python.pythonPath}", "program": "${workspaceFolder}/manage.py", "cwd": "${workspaceFolder}", "args": [ "runserver", "--noreload", "--nothreading" ], "env": {}, "envFile": "${workspaceFolder}/.env", "debugOptions": [ "RedirectOutput", "DjangoDebugging" ] } Even I mark the break point, vscode doesn't stop. Can anyone please teach me how to fix the bug? -
django-URL inside anchor tag becomes relative to the current page django
urls.py path('add_a_product_to_store/<store_id>',views.add_a_product_to_store,name='add_a_product_to_store'), path('show_a_store/<store_id>', views.show_a_store,name='show_a_store') show_a_store.html <a href="add_a_product_to_store/5">Add a product</a> When user enters ip:port/show_a_store/5 . . . . show_a_store.html is shown. But the link inside anchor tag points to http://127.0.0.1:8000/show_a_store/add_a_product_to_store/5 instead of http://127.0.0.1:8000/add_a_product_to_store/5 How to make it point to actual url irrespective of current page? -
Traversing Django models downstream in template language
I have the following model setup: class Model1(models.Model): val1 = models.CharField(max_length=25, blank=True) val2 = models.CharField(max_length=25, blank=True) user = models.ForeignKey('users.User', on_delete=models.PROTECT, related_name='model1') class Model2(models.Model): val3 = models.BinaryField() model1_link = models.ForeignKey(Case, on_delete=models.CASCADE, related_name='model2') class Model3(models.Model): id = models.BigAutoField(primary_key=True) model2_link = models.ForeignKey(Model2, on_delete=models.CASCADE, related_name='model3') class Model4(models.Model): id = models.BigAutoField(primary_key=True) model3_link = models.ForeignKey(Model3, on_delete=models.CASCADE, related_name='model4', null=True, default=None) pred = models.CharField(max_length=50) In my HTML template, I have a section where I iterate over entries from Model1 (e.g. val1), and would like to be able for each value, to include field 'pred' from Model4. Models 1-4 are daisy-chained through their FK`s at the moment. Yes, I know I could just include FK in Model4 linking it to Model1, but from logical point of view, I do not prefer this option at the moment. Anyway, expression like this does not get the job done on my end: ... {% for entry in model1_entries %} ... {% if user.is_superuser and entry.model2.model3.model4.count > 0 %} something here {% endif %} ... {% endfor %} I figure the problem has something to do with the fact that call model1.model2 returns a set of all model2's related to model1, but I dunno how I can pick one in this expression and … -
Forbidden (CSRF cookie not set.):
i am using ajax to post data from asp (as front) to Django rest api (as backend) First, I had a problem in Accessing to different domain but it solved using CORS then i had another error which is related to CSRF and the error like above :Forbidden (CSRF cookie not set.) i've used @csrf_exempt to pass this validation but i want a solution for use it without csrf exmption i tried more than one solution but it's not working or maybe i dont understand the way Is there any clearly solution to solve it in ajax i'll include code of my .cshtml file bellow ''' form id="std_form" class="mx-auto form-horizontal" method="POST" asp-antiforgery="false"> @Html.AntiForgeryToken() <div class="box-body"> <div class=" form-group"> <label for="inputEmail3" class="col-sm-3">ID</label> <div class="col-md-8"> <input type="number" id="first"> </div> </div> <div class=" form-group"> <label for="inputEmail3" class="col-sm-3">ID</label> <div class="col-md-8"> <input type="number" id="second"> </div> </div> <div class=" form-group"> <label for="inputEmail3" class="col-sm-3">ID</label> <div class="col-md-8"> <input type="number" id="third"> </div> </div> </div> <!-- /.box-body --> <div class="box-footer d-flex"> <button type="submit" id="save_btn" class="btn-success btn">Save</button> </div> <!-- /.box-footer --> </form> </div> ''' ''' window.CSRF_TOKEN = "{% csrf_token %}"; function getCookie(c_name) { if (document.cookie.length > 0) { c_start = document.cookie.indexOf(c_name + "="); if (c_start != -1) { c_start = c_start … -
Loop over django object
I have a model like this: class Grn(models.Model): owner = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='grn_owner') warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE, related_name="grn_warehouse") vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, related_name="grn_vendor") product1 = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='grn_product1') product1_quantity = models.IntegerField(default=0) product2 = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='grn_product2', blank=True, null=True) product2_quantity = models.IntegerField(default=0, blank=True, null=True) product3 = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='grn_product3', blank=True, null=True) product3_quantity = models.IntegerField(default=0, blank=True, null=True) product4 = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='grn_product4', blank=True, null=True) product4_quantity = models.IntegerField(default=0, blank=True, null=True) How can I loop over an object of this model? I tried something like this: class GRNFormView(CreateView): model = Grn template_name = 'GrnForm.html' form_class = Grnform def form_valid (self, form): data = form.save(commit=False) print("form.cleaned_data is ", form.cleaned_data) data.owner = Employee.objects.filter(user = self.request.user.id)[0] data.save() print("data is", data) for i in range(1,5): if data.product(i): print("product ", data.product(i)) else: pass How can I check if a product exists in an object and get its value ? -
Why my Django logging config has different behavior in dev vs prod environment
This is how my setting.py looks in dev and prod, DEBUG=False in both: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {funcName} {processName} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {asctime} {message}', 'style': '{', }, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, 'mail_admins': { 'level': 'WARNING', 'class': 'django.utils.log.AdminEmailHandler', 'formatter': 'verbose', 'include_html': True, }, 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': 'v.log', 'formatter': 'verbose' }, 'debug_file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'v_debug.log', 'formatter': 'verbose' }, }, 'root': { 'handlers': ['mail_admins', 'file'], 'level': 'WARNING', 'formatter': 'verbose', }, 'loggers': { 'django': { 'handlers': ['debug_file'], 'level': 'DEBUG', 'propagate': True, 'formatter': 'verbose', }, 'django.request': { 'handlers': ['console', 'file'], 'level': 'INFO', 'propagate': True, 'formatter': 'verbose', }, } } In my dev environment I get the desired result as follows: v.log gets: all INFO and above severity logs v_debug.log gets: all DEBUG and above severity logs Email gets WARNING and above security logs But in my prod environment I get different result as follows: v.log gets: WARNING and above security logs, but not INFO logs v_debug.log gets: WARNING and above security logs, but not INFO logs Email gets (expected) WARNING and … -
Effective way to use CSV of DNA information as database in Django project
I am thinking about the design of the following Django project. In this project, I have a CSV file (4 columns, 500 rows) which I am not sure how to handle as the database. the CSV looks like this The data contains 500 codes where each code has 3 scores: f1, f2, f3. The website goal: 1. to get the input of the user of what feature columns data he is interested in and in which order. e.g: 2Xf2 1Xf1 (there are only 3 feature columns: f1, f2, f3 and 'code' column) 2. to generate an output of codes that contains the highest-ranking codes for the required features in the required order. so for our input: 2Xf2 1Xf1 the output will be the following string: [#1 rankning code f2 column] [#2 ranking code f2 column] [#1 rankning code f1 column] I was thinking about creating a database with 3 columns: f1, f2, f3 where in each column there are codes in descending order, so if the user wants 5 codes from f1 I will take the first 5. My question is: How to handle the database in a simple way for developing and maintaining it (not looking for efficiency) that … -
How can I reference ForeignKey in django to populate a pedigree sheet?
I have two models that is linked each other by ForeignKey and OneToOneField as follows: Models class Porumbei(models.Model): serie_inel = models.CharField(max_length=25, null=False, blank=False, unique=True, help_text="Seria de pe inel. Ex: RO 123456") ... ... tata = models.ForeignKey('Perechi', to_field='mascul', on_delete=models.CASCADE, related_name="porumbei_masculi", null=True, blank=True) mama = models.ForeignKey('Perechi', to_field='femela', on_delete=models.CASCADE, related_name="porumbei_femele", null=True, blank=True) class Perechi(models.Model): ... mascul = models.OneToOneField(Porumbei, null=True, on_delete=models.CASCADE, limit_choices_to=Q(sex="Mascul"), related_name="perechi_masculi") femela = models.OneToOneField(Porumbei, null=True, on_delete=models.CASCADE, limit_choices_to=Q(sex="Femelă"), related_name="perechi_femele") ... In template I need to populate a table with ancestors of pigeons. To retrieve the pigeon from database I use: Views def editareporumbei(request, pk): porumbel = get_object_or_404(Porumbei, pk=pk) Then, in ancestor table, at father field I use {{ porumbel.tata.mascul }} My question is how I can get the grandfather, grandgrandfather of porumbel? How could I get it in template? Thanks in advance! -
How to make a self updating variable in Django?
I have 2 models, Employee and Designation. I want to count and update no. of Employees in a particular Designation. The project is a multiple user project, So I need a queryset, that focuses regarding the particular user. Models.py class Designation(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name="designation",null=True,blank=True) title = models.CharField(max_length=100) count = models.IntegerField(null=True,blank=True) class Employee(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,related_name="employee",null=True,blank=True) name = models.CharField(max_length=100) contact = models.CharField(max_length=15) dateJoined = models.DateField(auto_now_add=False,auto_now=False,null=True) designation = models.ForeignKey(Designation,on_delete=models.CASCADE,null=True,blank=True) I need the Variable count in Designation model to auto-update and count the no. of Employees holding a particular Designation -
Proper way of handling file from Django to Firebase Storage
I'm developing a web app in Django which uses Firebase Storage as its media storage place. Currently I have set the app to handle files saving as something like this: template.html <form enctype="multipart/form-data" method="post" action="{% my_view %}> {% csrf_token %} <input type="file" name="my_file"> <input type="submit"> </form> views.py # All the imports... cred = credentials.Certificate(os.path.join(settings.BASE_DIR, 'serviceAccountKey.json')) initialize_app(cred, { 'storageBucket': settings.FIREBASE_STORAGE_BUCKET}) bucket = storage.bucket() def my_view(request): file = request.FILES['my_file'] path = utils.handle_upload_file(file) blob = bucket.blob(blob_name=str(file)) blob.upload_from_filename(path) # Other logic... return redirect('home') utils.py def handle_upload_file(file): path = os.path.join(settings.BASE_DIR, 'media', str(file)) try: with open(path, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) except FileNotFoundError: os.mkdir('media') handle_upload_file(file) return path Okay, let me break this down: User uploads a file I receive the file, process and save it to my server (with the handle_upload_file method) File is sent to Firebase Storage User gets redirected to home view. Now, even though it works as expected, I feel like I'm doing an unnecessary step when I save it to my server. Nevertheless, I've tried with the blob.upload_from_file function to avoid the aforementioned step and I've been able to save it directly to Firebase Storage, but it gets saved in a weird way so I went back to my … -
Docker container does not communicate with others in same docker network(bridge)
I'm trying to set the environment for web server on amazon web server. I want to use django, react, nginx and they are running on each docker container. Belows are the command for running docker container. sudo docker run --name django-server -it -d -p "8000:8000" --volume=$(pwd)/trello-copy-django-src:/backend/trello-copy django-server sudo docker run --name nginx-server -d -p "80:80" --volumes-from react-server nginx-server I did not specified a custom docker network bridge and I checked that they are on same default bridge by typing $ docker inspect bridge. [{ "Name": "bridge", ..., "Containers": { "...": { "Name": "django-server", ... }, "...": { "Name": "react-server", ... }, "...": { "Name": "nginx-server", ... }, } }] So, I expected the react code down below works. But it worked only at my laptop, which has exactly same docker structure of aws. ... const res = await fetch('http://127.0.0.1:8000/api/'); ... Failed to load resource: net::ERR_CONNECTION_REFUSED 127.0.0.1:8000/api/:1 What am I doing wrong? -
How to Call a Foreign Key from a foreign App where the key is non Primary key in Django
I am still a newbie in Django. And Started working on task tracker DB. I have different apps like user, task,status etc., Now I am trying to call userID in different app, which is actually an ID in user table(by default autogenerated column). Below is example where I want to call ID from user app to Status app as userID.. from user.models import User userID = models.ForeignKey(User, to_field="id", db_column="userID", default="", editable=False, on_delete=models.CASCADE) But I am getting this error in my terminal django.db.utils.OperationalError: foreign key mismatch - "status_status" referencing "user_user" Error_Img Also my table name is coming like status_status, user_user Not sure where I am going wrong? can anyone please help me out..? Thanks in advanced! Have a great day.. -
How to autofill values from db in django
Guys i am quite new in django and for learning purpuse i am making mini project for better learning and understanding. Try to do a lot of stuff on my own, but there are stuff that i can't make work. There is a entry filed where a user enters product code. Each code has its product name. I want when i enter product code the field bring me otpions of its product names. Here is my models.py: class NM(models.Model): name = models.CharField(max_length=150) class Products(models.Model): productcode=models.CharField(max_length=200) productname=models.CharField(max_length=500) My views.py: def home(request): if request.method == "POST": form = NMForm(request.POST) if form.is_valid(): for_m = form.save(commit=False) name = for_m.name My template.html: <form method="POST" > {% csrf_token %} {{ form}} <button type="submit">OK</button> </form> I tried to insert the following code in my template.html: {% for field in form.visible_fields %} {{ field.errors }} {{ field }} {% endfor %} Howvere this code does nothing. It does not generate the desited action for me. Can someone help me with it ? I would appreciate your help and any advice.