Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create dynamic ManyToMany field in Django?
In admin add view I would like to able to select dynamically field A_permission from selected A-object while creating new B-object A(models.Model): name = models.CharField(primary_key=True, max_length=50) permission = models.CharField(max_length=50) B(models.Model): A_name = models.ForeignKey(A) A_permissions = models.ManyToManyField(A) So I have objectA1 and objectA2 for example. While creating object B I should be able to first select one of the A objects, and then just get its permission for selection in field A_permissions Can someone please point me how to do this? I feel like I tried everything -
manage.py runserver do nothing on VPS
When I run python3 manage.py runserver on Ubuntu 16.04 VPS machine it does nothing with my project but it runs that runs on my computer. I try to run python3 -v manage.py runserver and have seen that it stopped when executing this: # code object from '/usr/lib/python3.5/site-packages/OpenSSL/__pycache__/SSL.cpython-35.pyc' import 'OpenSSL.SSL' # <_frozen_importlib_external.SourceFileLoader object at 0x2b1d1d937630> # /usr/lib/python3.5/site-packages/OpenSSL/__pycache__/version.cpython-35.pyc matches /usr/lib/python3.5/site-packages/OpenSSL/version.py # code object from '/usr/lib/python3.5/site-packages/OpenSSL/__pycache__/version.cpython-35.pyc' import 'OpenSSL.version' # <_frozen_importlib_external.SourceFileLoader object at 0x2b1d1e6a5c50> import 'OpenSSL' # <_frozen_importlib_external.SourceFileLoader object at 0x2b1d1d923da0> after last line it start to do nothing my settings.py file: """ Django settings for hahachat project. Generated by 'django-admin startproject' using Django 3.0.4. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'p#b#s#!sfv#o(o661x=kb7!-nfef&33orv%74s8*1gdi)1w1u8' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'main', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'djoser', 'channels', 'room', 'chat', 'game', … -
Javascript code not working using template inheritence in Django template
I am having trouble in executing Javascript code in a Django project. The following is working fine - i.e. without using template inheritence html: <!DOCTYPE html> <html> <head> {% load static %} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> <script src="{% static 'ads/test.js' %}" type="text/javascript"></script> <title> Test </title> </head> <body> <form action="{% url 'test' %}" method="post" id="my_form"> {% csrf_token %} <button type="submit" class="btn btn-success">Submit</button> </form> </body> </html> test.js $(document).ready(function() { $("#my_form").submit(function(){ alert('submitted'); }); }); Since the above external Javascript file test.js has executed successfully, I assume the settings of static url, static dirs, etc. are correct. Also, since jquery has worked, I assume the order of jquery first, then js code is also correct. The problem comes when I use template inheritence. base html: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> {% block scripts %} {% endblock %} <title> {% block title %}{% endblock %} </title> </head> <body> {% block body %} {% endblock %} </body> </html> inherited template: {% extends "base.html" %} {% block scripts %} {% load static %} <script src="{% static 'ads/test2.js' %}" … -
Using Foreign Keys to import Images in Django
I am using Django 2.2 to make a project where designers upload designs and when I want to post them from admin, I want to choose their names and after I choose their names only their designs appear in the drop down list. So far I have reach the reach the designer name in a drop down list but I don't know how to link only their designs in the designs drop list. I am using 2 different apps: 1."Score" where designers can upload their designs 2."Core" where I can list the items First in the Score .model where designers upload the designs class Post(models.Model): designer_name = models.ForeignKey(User, on_delete=models.CASCADE) design = models.ImageField( blank=False, null=True, upload_to='new designs') title = models.CharField(max_length=100) def __str__(self): return self.title def get_absolute_url(self): return reverse("score:post-detail", kwargs={"pk": self.pk}) Second in the Core App Model: class Item(models.Model): title = models.CharField(max_length=100) description = models.TextField() price = models.FloatField() designer_name = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(blank=False, upload_to='imgs') **How can I make this a drop down list with the selected user's (designer's) all previously uploaded images to choose from instead of uploading new images** def __str__(self): return self.title -
django-autocomplete-light doesn't show the data when editing
I'd like to have the same field autocompletion for creating and editing a model so I'm trying to use the same form. Problem is when editing the object it is not showing the selected value, I'm getting an empty value. How can I set the initial value for it? relevant view code: if request.method == 'POST': form = PuppetClassForm(request.POST, instance=class_instance) if form.is_valid(): class_instance.scope = sub_scope class_instance.module = None class_instance.save() return redirect('show.subscope', user_slug=owner.slug, platform_slug=platform.slug, scope_slug=parent_scope.slug, sub_scope_slug=sub_scope.slug) else: form = PuppetClassForm(request.GET, initial={ 'name': class_instance.id, 'description': class_instance.description }) if class_slug: return render(request, 'classes/edit.html', {'form': form, 'class_instance': class_instance}) else: return render(request, 'classes/edit.html', {'form': form }) Model: class PuppetClass(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=256, blank=False) description = models.CharField(max_length=256, default='') Form: class PuppetClassForm(forms.ModelForm): filters = ~Q(properties=None) name = forms.ModelChoiceField( queryset=PuppetClass.objects.filter(scope=None).filter(filters).order_by("name"), widget=autocomplete.ModelSelect2(url='puppetclass-autocomplete'), to_field_name="name" ) description = forms.CharField(required=False) def __init__(self, data, **kwargs): initial = kwargs.get('initial', {}) data = {**initial, **data} super().__init__(data, **kwargs) class Meta: model = PuppetClass fields = (['name', 'description']) -
here, my if condition is not working in python [closed]
for obj in cartobj: print("-------------------",pid,"----------------",obj.prodid.id) print("-------------------------",nm,"-----------",type(nm)) print("------------------------",obj.prodid.product_name,"-----------------",type(obj.prodid.product_name)) if pid == obj.prodid.id or nm == obj.prodid.product_name: print("------------------Condition True---------------") print(obj) print(obj.prodid) print(proobj) print("\n Before Quantity==",obj.qnty) obj.qnty = int(qty) print("\n After Quantity==",obj.qnty) print("\n Before rowtotal==",obj.rowtotal) obj.rowtotal=int(qty)*proobj.product_price print("\n After rowtotal==",obj.rowtotal) print("Name--------------->",obj.prodid.product_name) obj.cnm=nm obj.save() print("##################Reached#########################") return HttpResponse(1) else: print("------------------Condition False------------------") pass -
Django 2.2 error - Integrity Error, NOT NULL constraint failed
I have a sample Django 2.2 project that has a search bar in the top right corner of the nav bar (taken from the Bootstrapers): navbar.html: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="/">Navbar</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a> </li> {% if user.is_authenticated %} <li class="nav-item"> <a class="nav-link" href="/search/">Search</a> </li> ... {% endif %} <li class="nav-item"> <a class="nav-link" href="/a/">A</a> </li> <li class="nav-item"> <a class="nav-link" href="/b/">B</a> </li> </ul> <form class="form-inline my-2 my-lg-0" action = '/search/'> <input class="form-control mr-sm-2" type="search" name="q" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> It returns "You searched for [search argument]" to the url '/search/' and works fine. I would like to bring it from the nav bar under the 'Search' menu in the nav bar. I have the following: searches/models.py from django.db import models from django.conf import settings # Create your models here. class SearchQuery(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, blank = True, null=True, on_delete=models.SET_NULL) query = models.CharField(max_length=220) timestamp = models.DateTimeField(auto_now_add=True) searches/views.py: from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.contrib.admin.views.decorators import staff_member_required from .models import SearchQuery # Create your views here. … -
Is there a way to dynamically edit value in django template?
Okay so I've been trying to show time in my website, and i was successful in it, but then after the time changes in real-time it does change in the site, we will have to reload the page and then time would b updated. Is there a way to update the time without reloading the page using django templates (html). -
django - My html page have textbox or checkbook both are in loop it is save only last value but i want save all value in all selected checkbox
----------------------------------html---------------- {% for Deficiency in Deficiency_View %} <tbody> <tr> <td class="hidden-phone"> {{ Deficiency.Institute }}</td> <td class="hidden-phone"> {{ Deficiency.Course }}</td> <td class="hidden-phone"> {{ Deficiency.StudentName }}</td> <td> {{ Deficiency.FathersName }}</td> <td class="hidden-phone"> {{ Deficiency.MothersName }}</td> <td>Check: <input type="checkbox" name="EnrollmentGenerate" id="Enrollment_Generate" value="{{ Deficiency.formNo }}"></td> <td> <input type="text" name="my_list" id="EnrolNo" value=" {{ Deficiency.Institute_Code }}{{ Deficiency.Course_Code }}{{ Deficiency.Branch_Code }}"> </td> </tr> {% endfor %} ----------------------------------view---------------- formNo = request.POST.get('EnrollmentGenerate') # EnrollmentGenerate is a name="checkbox" a checkbox have loop in html enrollment_Generate = EnrollmentForm.objects.get(formNo=formNo) # this is save only last checked Row not save all , i want save all selected checkbox in model enrollment_Generate.EnrollmentNo = request.POST.get('my_list') # this is save only last value but i wanr save all (name="my_list" a text box have loop in html) enrollment_Generate.save() Note: model EnrollmentForm in EnrollmentNo (not use form use custum update data code) -
why Django button don't have auto built code as asp.net does?
I am from the background of asp.net, currently i have started working on django, I always wonder why Django button don't have a auto built code or function that will execute on button click as asp.net does ? and can we make such functionality in Django that when we add button the auto built in code for that button will generate ? I am new in Django please provide me the reason why Django use this approach and its advantages and disadvantages ? -
How to incorporate images or graphs and plain-text in same field in Django
In my web-app (say a simple polls app) I want to add images and graphs to question text and options.Can you help we with appropriate field(s) for my models(Question and Option)? I want it to look this way : ................................ . n . Question Text .. ................................ ...... (relavant images) ....... ................................ ...Option1(Maybe a graph/text).. ...Option2(Maybe images)........ -
Django reply to comment in ajax does not work
I am writing an application in django 2.2 with ajax. It's about the comments section and responses to comments. I have two problems: Writing a new comment works. The response to the comment does not work, an error appears: The view spot.views.SpotDetailView didn't return an HttpResponse object. It returned None instead. Validation - if a comment is added, it works, but the error appears on all windows to respond to comments. The validation of the response to the comment does not work, the page source appears instead of the error view.py class SpotComment(SingleObjectMixin, FormView): template_name = 'spot/spot_detail.html' form_class = CommentModelForm model = Spot def get_success_url(self): return reverse('spot_detail_url', kwargs={'slug': self.object.slug, 'id': self.object.pk}) def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.form_class(request.POST) form.instance.spot = self.object form.instance.author = self.request.user if form.is_valid(): reply = request.POST.get('comment_id') comment_qs = None if reply: comment_qs = Comment.objects.get(id=reply) form.instance.reply = comment_qs form.save() if request.is_ajax(): context = { 'form': form, 'errors': form.errors, 'object': self.object, } html = render_to_string('spot/comments.html', context, request=request) return JsonResponse({'form': html}) else: context = { 'form': form, 'errors': form.errors, 'object': self.object, } html = render_to_string('spot/comments.html', context, request=request) return JsonResponse({'form': html}) jQuery code: $(document).on('submit', '.comment-form', function(event){ event.preventDefault(); var serialized = $('.comment-form').serialize(); $.ajax({ type: 'POST', url: $(this).attr('action'), data: … -
How to filter django models based on ManytoMany relationhsip and on math calc
Guys i am learning Django and models linking to DB quite confusing for me. I would like to gte your help/guidance . Any help is very much welcomed. I have 4 models: class Profile(models.Model): player = models.CharField(max_length=150) surname=models.CharField(max_length=200) class Meta: db_table='profile' class race19(models.Model): player = models.CharField(max_length=150) profile=models.ManyToManyField(Profile) score19=models.DecimalField(decimal_places=2,max_digits=1000) distance=models.DecimalField(decimal_places=2,max_digits=1000) class Meta: db_table='race19' class race18(models.Model): player = models.CharField(max_length=150) profile=models.ManyToManyField(Profile) score18=models.DecimalField(decimal_places=2,max_digits=1000) distance=models.DecimalField(decimal_places=2,max_digits=1000) class Meta: db_table='race18' class adjustments(models.Model): player = models.CharField(max_length=150) profile=models.ManyToManyField(Profile) bonus=models.DecimalField(decimal_places=2,max_digits=1000) class Meta: db_table='adjustments' I explored django docs and could learn filtering just from 1 table as fowllowing : score_m=race19.objects.annotate(score_margin=F('score19') / F('distance')).filter(score_margin__gt=0.4,) Now i want to be able to get values such as score19, score18, bonus from different tables and i though ManytoMany would help and tried the following: score_growth=race19.objects.annotate( score_change=((F('score19')+F('bonus')) / F('score18')).filter(score_change__gt=0.10,) But this does not work. What i needed to do. Would appreciate if you could share code as thereby i would better understand. Thanks in advance. -
Why the ach form is_bound always false?
i trying to update a modelform while save another modelform, I want to update ach form with the new value from the Payments forms, the ach from is always unbound ?? forms.py : achat = get_object_or_404(Achats,pk=pk) form = Payments_Form(request.POST or None,achat_id=pk) if form.is_valid(): ach = AchatForm(instance=achat) ach.fields['Montant_pay'] = form.cleaned_data['Montant_TTC'] if ach.is_valid(): ach.fields['Montant_pay'] = form.cleaned_data['Montant_TTC'] ach.save() print(ach.errors) print(ach.is_bound) form.save() return redirect('view') forms.py : class AchatForm(ModelForm): class Meta: model = Achats fields = ('Date','Id_Fournis','Montant_HT','Montant_TVA','Montant_TTC','Montant_pay') class Payments_Form(forms.ModelForm): class Meta: model = Payements fields = ('Date', 'mode_de_payement', 'reference', 'Montant_HT','Montant_TVA','Montant_TTC', 'Numero_facture', 'Numero_payement','E_S') -
Datable not working in django/bootstrap 4
Goal: I am using django and bootstrap. I would like to use datatable jquery plugin in my bootstrap table. Issues: The table in my html stay the same and doesn`t use the datatable plugin What Ive done to resolve this issue? I`ve added the two lines in my base.html file base.html <!-- Datatable --> <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css"> <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script> and the javascript code as well: <script> $(document).ready(function(){ $('#dtBasicExample').DataTable(); }); </script> <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script> My table is name dtBasicExample in my html file: <div class="container-fluid"> <div class="col-sm-20"> <table id="dtBasicExample" class="table table-striped table-hover"> Is there anything I need to add in django to make it work? Many Thanks, -
Apache2&Django - NameError: name "AttributeError" is not defined
I followed pretty much every official documentation to get my Django project running on my Ubuntu 18.04 v-server. And it seems to work...sudo service apache2 status -> everything ok too. [Sun May 03 16:07:20.489608 2020] [mpm_event:notice] [pid 11531:tid 139884218760128] AH00489: Apache/2.4.29 (Ubuntu) OpenSSL/1.1.1 mod_wsgi/4.7.1 Python/3.8 configured -- resuming normal operations [Sun May 03 16:07:20.489764 2020] [core:notice] [pid 11531:tid 139884218760128] AH00094: Command line: '/usr/sbin/apache2' I first noticed that something's off when my templates wouldn't update without a server restart which is not Django's usual behaviour (even in a productive environment). Whenever I restart the server I get this error in the apache2/error.log. Although the server keeps working I want to get to the bottom of this. Exception ignored in: <function Local.__del__ at 0x7fbd983f03a0> Traceback (most recent call last): File "/var/www/my_app/.my_app/lib/python3.8/site-packages/asgiref/local.py", line 95, in __del__ NameError: name 'AttributeError' is not defined Exception ignored in: <function Local.__del__ at 0x7fbd983f03a0> Traceback (most recent call last): File "/var/www/my_app/.my_app/lib/python3.8/site-packages/asgiref/local.py", line 95, in __del__ NameError: name 'AttributeError' is not defined [Sun May 03 16:07:19.418926 2020] [core:warn] [pid 11433:tid 140452536064960] AH00045: child process 11435 still did not exit, sending a SIGTERM [Sun May 03 16:07:20.419208 2020] [mpm_event:notice] [pid 11433:tid 140452536064960] AH00491: caught SIGTERM, shutting down [Sun May 03 … -
invalid syntax in views.py in Django
The code was working. However, I got the error suddenly that can be seen in the image invalid_syntax_error . Even though the name of view and the name of function are same(in this case "addArticle"), I got this error. How can I fix that issue? Here is what my urls.py contains; from django.contrib import admin from django.urls import path from . import views app_name = "article" urlpatterns = [ path('dashboard/',views.dashboard,name = "dashboard"), path('addarticle/',views.addArticle,name = "addarticle"),] -
Django CreateView: How to create the resource before rendering the form
I have a model class for my resource, class Article(db.Model): title = models.CharField(_('title'), max_length=255, blank=False) slug = AutoSlugField(_('slug'), populate_from='title') description = models.TextField(_('description'), blank=True, null=True) content = RichTextUploadingField() Here's my form class class ArticleForm(ModelForm): class Meta: model = kb_models.Article And finally my CreateView, class CreateArticleView(generic.CreateView): form_class = ArticleForm model = Article def get_success_url(self): return "some_redirect_url" Right now I have configured my URLs like below, path('add/', CreateArticleView.as_view(), name='create_article') path('<slug:article>', ArticleDetailView.as_view(), name='article_detail'), path('<slug:article>/update', UpdateArticleView.as_view(), name='update_article') The current flow will render a form when I hit the add/ resource endpoint, and save the resource in the database only after I submit the form. After that, the article can be accessed using the slug generated from the title. What I want instead is to be able to create the Article resource before the resource is rendered, so that the add/ endpoint redirects to some add/unique-uuid endpoint, and even when the form is not submitted from the browser, this empty resource is preserved, and it can be accessed later on because of the unique-uuid. I thought of instantiating an object and redirecting that to UpdateView, but I am having difficulties in figuring out how to keep track of the unique-uuid and point both generated-uuid and slug … -
Django - LANGUAGE_CODE - 'en-IN' does not work, but 'hi-IN' works
Django version 2.2 and 3.0 Purpose: I would like to display numbers in India locale format. For e.g. 1000000 should be displayed as 10,00,000 Action To do this, I went to settings.py and made the following changes: LANGUAGE_CODE = 'IN' - date and time was displayed in Indonesian format but grouping of numbers were correct LANGUAGE_CODE = 'en-IN' - date and time was displayed properly but grouping of numbers were incorrect LANGUAGE_CODE = 'hi-IN' - date and time had Hindi language display but grouping of numbers were correct What I want LANGUAGE_CODE = 'en-IN' to display date and time properly and also do number grouping My settings.py file : LANGUAGE_CODE = 'en-IN' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_THOUSAND_SEPARATOR = True NUMBER_GROUPING = (3,2, 0) USE_TZ = True I had a look at Number Grouping which actually talked about this but I believe documentation is misleading. For starters they have put language code as en_IN which doesn't work. Let me know if any additional information needed. -
Get latitude and longitude after clicking on Geodjango Leaflet map
I have a form with a Geodjango Leaflet map on my page. What I want to achieve is that after clicking somewhere on the map, I get the latitude and longitude from that location, to than store that in my form. The code in the form already takes care of placing a marker on the map. I'm not able to find the location where I clicked. forms.py class PlacesForm(forms.ModelForm): required_css_class = 'required' place = forms.PointField( required=False, widget=LeafletWidget()) class Meta(): model = Places form.html var markers = []; var layerGroup = new L.layerGroup(); $.fn.setMap = function(map) { console.log(layerGroup); layerGroup.clearLayers(); //$(".leaflet-marker-icon").remove(); $(".leaflet-popup").remove(); if( $("#id_latitude").val() && $("#id_longitude").val() ) { map.setView([$("#id_latitude").val(), $("#id_longitude").val()], 18); markers = L.marker([$("#id_latitude").val(), $("#id_longitude").val()]).addTo(layerGroup); if( $("#id_radius").val() ) { L.circle([$("#id_latitude").val(), $("#id_longitude").val()], {radius: $("#id_radius").val()}).addTo(layerGroup); } layerGroup.addTo(map); } } $(document).ready(function() { // Store the variable to hold the map in scope var map; var markers; $(window).on('map:init', function(e) { map = e.originalEvent.detail.map; $.fn.setMap(map); }); $("#id_latitude").on("change", function () { $.fn.setMap(map); }); $("#id_longitude").on("change", function () { $.fn.setMap(map); }); $("#id_radius").on("change", function () { $.fn.setMap(map); }); $('#id_place-map').on("click", function(e) { //var lat = e.latlng; //var lng = e.latlng; console.log(e); }); }); </script> If I look in my console I can't find anything that I can use. I only see the … -
Django tournament
I have a problem with my model, i don't know how to create model called battle, because i want to choose two users from my database but i don't know how to create it class battle(models.Model): user1 = models.ForeignKey(Debatants, on_delete=models.DO_NOTHING) user2 = models.ForeignKey(Debatants, on_delete=models.DO_NOTHING) judge = models.ForeignKey(Judges, on_delete=models.DO_NOTHING) data = models.DateField(auto_now_add=False, auto_now=False) I'd appreciate any hint -
Copying dataframe column dict into Django JsonField
I have a table created with Django(3+) on a postgres database (10+). Class Cast(models.Models): profiles=JSONField(null=True) I am trying to copy a dataframe with a column full of python dict of the form {'test':'test'}. When I use the command: df.to_sql('cast',engine,if_exists='append') I get the following error: (psycopg2.ProgrammingError) can't adapt type 'dict' I tried replacing my dict by None and it worked well. I have correctly added 'django.contrib.postgres' in INSTALLED_APPS ( I don't know if this should be done before creating the database but I guess not) I must add that the postgres database is on a remote server, the django code is on my local computer and the code to copy the dataframe on a second remote server. -
Can I Delete migrations models django?
i am creating my site with django and MySQL (all are latest versions), my data base plan was change. now i want to edit my MySQL database. the project is still testing in face i don't need any data of the database. I'm new for python, Django with MySQL. please help with this. thank you -
How to create a google sign-in popup window that gets closed after login success in Django
I am creating a Django app that allows google sign-in (using python-social-auth). I want the google sign-in page to open in a new window. I am able to implement it with a javascript window.open() function. But after login, the app continues (successfully) on the created window. How do I get it to close itself and redirect the parent to the appropriate redirect_after_login_page? Is there any native way in Django to implement popup windows? -
Exception Value: 'str' object has no attribute '__name__' CreateView
Не получается создать экземпляр класса изза ошибки: Exception Value: 'str' object has no attribute 'name' До некоторго времени работало в норме, а сейчас перестало. Не могу понять в чем проблема. Заранее спасибр view.py class FoodCreateView(CreateView): fields = ('food_name','active_b','food_type_r','boxing_r','profile_pic_i','show_comments_b','User_Create_r') queryset = Food.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.user.is_authenticated: context['test'] = self.request.user.id else: pass return context url.py path('food/create/',views.FoodCreateView.as_view(model="Food"),name='create'), Model.py class Food(models.Model): food_name = models.CharField(max_length = 25, verbose_name="Наименование еды") date_d = models.DateTimeField(auto_now=True, verbose_name="Время создания") desc_c = models.CharField(max_length = 256, verbose_name="Описание блюда") active_b = models.BooleanField(verbose_name="Активно?") food_type_r = models.ForeignKey(Food_Type_ref, models.DO_NOTHING, verbose_name="Тип Блюда", related_name='Food_type') boxing_r = models.ForeignKey(Boxing_ref, models.DO_NOTHING, verbose_name="Упаковка") moderated_b = models.BooleanField(verbose_name="Прошел модерацию", default=False) User_Create_r = models.ForeignKey(User, models.DO_NOTHING, verbose_name="Автор") views_n = models.SmallIntegerField(verbose_name="Просморы", default=0) profile_pic_i = models.ImageField(upload_to='profile_pics', blank=True, verbose_name="Фото еды") show_comments_b = models.BooleanField(verbose_name="Отображать комментарии") def __str__(self): return self.food_name def get_absolute_url(self): return reverse('dish_app:detail',kwargs = {'pk':self.pk})