Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django map widget console showing DjangoGooglePointFieldWidget Uncaught ReferenceError
I'm trying to implement the django map widget https://github.com/erdem/django-map-widgets But there is no map appearing and i have this in the browser console Uncaught ReferenceError: DjangoGooglePointFieldWidget is not defined in settings.py, i have INSTALLED_APPS = [ ... 'mapwidgets', ] MAP_WIDGETS = { "GoogleStaticMapWidget": ( ("zoom", 15), ("size", "320x320"), ), "GoogleStaticMapMarkerSettings": ( ("color", "green"), ), "GOOGLE_MAP_API_KEY": "AIzaSyA1fXsJSKqZH_Bl9d9wueJMlpXd-6tEJy0" } in my model.py class CompanySettingEdit(forms.ModelForm): display_companyname = forms.CharField(label='Display Company Name', max_length=50, required=True) class Meta: model = Company fields = ("display_companyname","location_point") widgets = { 'location_point': GooglePointFieldWidget, } Am I missing something ? to I need to load anything in the template ? -
Django template get foreign key value name
I've made a form containing tests with questions for translators. My problem is that I can't show language value name and type value name, instead of the name it shows me the id. views.py def translator_test(request): tests = TranslatorTest.objects.filter(data__translator__user=request.user).filter(completed=False) forms = [] for index, test in enumerate(tests): forms.append(TranslatorTestForm(request.POST or None, instance=test, prefix="form_{}".format(index))) if request.method == 'POST': for form in forms: if form.is_valid(): cd = form.cleaned_data answer = cd['answer'] test_form = form.save(commit=False) if answer: test_form.completed = True else: test_form.completed = False test_form.save() return redirect(reverse_lazy('core:index')) return render(request, 'core/translator_test.html', {'forms': forms}) translator.html {% for form in forms %} {% for field in form %} <div class="form-group m-form__group row"> {% if field.name == 'question' %} <label for="example-text-input" class="col-2 col-form-label"> {{ field.label }}: </label> <div style="margin-top:8px;"> {{ field.value }} </div> {% elif field.name == 'language' %} <label for="example-text-input" class="col-2 col-form-label"> {{ field.label }}: </label> <div style="margin-top:8px;"> {{ field.instance.language.name }} </div> {% elif field.name == 'type' %} <label for="example-text-input" class="col-2 col-form-label"> {{ field.label }}: </label> <div style="margin-top:8px;"> {{ field.value }} </div> </div> {% endfor %} {% endfor %} models.py class Language(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class TextType(models.Model): name = models.CharField(max_length=100, unique=True) def __str__(self): return self.name class TranslatorTest(models.Model): language = models.ForeignKey(Language) type = … -
Avoid deletion in Generic Relation?
Try remove relation in pre_delete signal before delete instance ModelB instance. Trouble is when i delete intance of ModelB django use cascade deletetion and delete ModelA instance. class AModel(models.Model): field_custom_id = models.PositiveIntegerField( blank=True, null=True, db_index=True ) field_custom_type = models.ForeignKey( 'contenttypes.ContentType', on_delete=models.SET_NULL, blank=True, null=True, db_index=True ) field_custom = GenericForeignKey('field_custom_type', 'field_custom_id') class BModel(models.Model): fidl_fild = GenericRelation( AModel, related_query_name='customqueryname', content_type_field='field_cusntom_type_one', object_id_field='field_cusnto_id_one', ) -
python Django - Convert SQL Query to ORM Query
I want sql query to orm SELECT id, title, (SELECT SUM(AMOUNT) FROM web_history A WHERE A.car_id = B.id AND type = 3) FROM web_car B; histories = History.objects.filter(car=OuterRef('pk'), type=3) cars = Car.objects.annotate(count=Subquery(histories.annotate(a=Sum('amount')))) This can not be done by setting the output_field ... I can not solve it even if I apply variously from FloatField to Char through Concat. I leave a comment on whether I can get advice. -
slice a query result string field in annotation using Django 1.11
I am trying to slice the last two characters of a field and annotate it to query result. Something like: Person.objects.all()\ .annotate( code = F('PoBox')[-2:] ) How can I achieve this? Do I need to use extract()? -
Python wkhtmltopdf can't import module
I am using python version 3.6 and django version 1.9. wkhtmltopdf version 0.2. My python is not GCC its Anaconda3.When i run my project which using wkhtmltopdf throwing error like : from main import WKhtmlToPdf, wkhtmltopd ModuleNotFoundError: No module named 'main' How i import the wkhtmltopdf: import pdfkit from wkhtmltopdf.views import PDFTemplateView -
geocoding error in django-easy-maps
I cant get django-easy-maps to work. It has "geocoding error" error and I am not sure why and how to solve this. based on this: https://github.com/bashu/django-easy-maps I first ran this: pip install django-easy-maps settings.py INSTALLED_APPS = ( ... 'easy_maps', ) EASY_MAPS_GOOGLE_MAPS_API_KEY = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ___0123456789' (not this is not my key but i just put it as example' in my template for the html {% extends 'employee/base.html' %} {% load bootstrap3 %} {% block page %} <div class="col-lg-12"> <div class="panel"> <div class="panel-heading bg-blue"> <h4 class="panel-title text-center text-white"> My Map </h4> </div> <div class="panel-body"> {% load easy_maps_tags %} {% easy_map "Russia, Ekaterinburg, Mira 32" 300 400 %} </div> </div> </div> {% endblock %} I run python manage.py makemigrations python manage.py migrate But it doesnt show any map in the page. It has this It has this "geocoding error" in the html generated file. <!-- HTML map container --> <div id="map-canvas-1" class="easy-map-googlemap"> <!-- geocoding error --> </div> What is the problem and what is the right way to setup easy-maps on django ? -
Model In Django
PAYCODE_BLUEPAY = "BLUEPAY" PAYCODE_HEARTLAND = "HEARTLAND" PAYCODE_1STPAY = "1STPAYMENT" PAYCODE_CHOICES =( (PAYCODE_1STPAY, '1St Payment'), (PAYCODE_BLUEPAY, 'Bluepay Payment'), (PAYCODE_HEARTLAND, 'HeartLand Payment'), ) class Payment(models.Model): paymentmethod = models.CharField("Payment Method", max_length=20, choices = PAYCODE_CHOICES, blank=False, null=False) def __str__(self): return self.paymentmethod The method __str__(self) will return BLUEPAY or HEARTLAND or 1STPAYMENT. But I want __str__(self) return 1St Payment, Bluepay Payment or HeartLand Payment. Please give me solution. Thanks. -
Need to trigger a script accepting Django form Text field values as parameter
I am very new to Django. I have a script for which i am planning to make a Web APP. I require some of values to be passed through HTML form action method into my python script. and the script output to be shown in same page or different page. Example script: a={{get-val1-from form}} b={{get-val2-from-form}} def add(a,b): return (a+b) My HTML form will look like : <form action="/"> <fieldset> <legend>Input Requirements<br></legend> <p> <label>Value A:<br></label> <input type="text" name="val1" value=""> </p> <p> <label>Value B:<br></label> <input type="text" name="val2" value=""> </p> <p> <button id="Submit" > Analyze </button> </p> <p> <label>Result : <br></label> <textarea id="out_string"> {{out_string}} </textarea> </fieldset> </form> I want to implement it through Django, kindly let me know the way out using views templates. Thanks in advance.. -
Render the FileField as multiple file input field in the form based on multiple choices field
I have 2 Models, Product and Document. Document has a FK to Product. class ProductDocument(models.Model): product = models.ForeignKey(Product, related_name='documents', on_delete=models.CASCADE) document = models.FileField(upload_to=file_upload_to) type = models.CharField(max_length=255, choices=DOC_TYPE) The Document can have different types (data sheet, whitepaper etc). When I render the modle Filefield field I want to render an input file HTML element for each type(instead of making the user select the type). After that on form processing, separate somehow the file type, on the save method. I render the Document form in the Product form. -
Django DB connections issue.
I'm troubleshooting a database in which Django's database connection is queued up hanging. I want to confirm - If Django creates DB connection per HTTP request - If for some reason, the HTTP request is thrown exception Django will close the database exception. I also want to know at what exact moment Django creates a database connection. For example, if I have a function based view which doesn't deal with the database will it still initiate a connection? -
AssertionError: 200 != 302
Traceback (most recent call last): File "/home/infinity/.virtualenvs/p38-1/src/p38/p38/tests/test_urls.py", line 82, in test_signout self.assertEqual(200, response.status_code) AssertionError: 200 != 302 View @secure_required def signout(request, *args, **kwargs): """ Signs out the user and adds a success message ``You have been signed out.`` If next_page is defined you will be redirected to signin page. """ use_messages = getattr(settings, 'USERENA_USE_MESSAGES', True) if request.user.is_authenticated() and use_messages: messages.success( request, _('You have been signed out.'), fail_silently=True) userena_signals.account_signout.send(sender=None, user=request.user) auth_logout(request) return HttpResponseRedirect(reverse('userena_signin')) URL url(r'^accounts/signout/$', 'p38.views.signout', name='userena_signout'), Test def seUp(self, validated=True): UserenaSignup.objects.check_permissions() self.user = mock_user() self.user['recaptcha_response_field'] = 'PASSED' if validated: self.client.login(username='test', password='test') else: self.client.post(reverse('userena_signup'), {'codeclient': '000203475', 'lastsalenumber': '136088', 'is_tos_agreed': True}) def test_signout(self): self.seUp() response = self.client.get(reverse('userena_signout')) self.assertEqual(200, response.status_code) I have the error 200 != 302 in the top of that question. I am struggling to fix it. I am pretty sure the problem is due to the login, but I can't figure out what to add or what to remove from the view for instance. How could I deal with that problem? -
Whether I can write the logic in View?
I can write myself's logic in the Serializer's create method: class UserCreateSerializer(ModelSerializer): class meta: model = User fields = "__all__" def create(self, validated_data): username = validated_data["usernmae"] email = validated_data["email"] password = validated_data["password"] # there I can do myself's logic return validated_data Whether I can write the logic in View? If is, how to do with that in View? -
Django manage.py runserver invalid syntax
I am developing a web in Ubuntu using django. Everything works normal. Now, I want to change my computer which use Windows. When I try to runserver, it gives: E:\DEGNet>py manage.py runserver File "manage.py", line 14 ) from exc ^ SyntaxError: invalid syntax E:\DEGNet>py Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> As shown above, I have installed Python 3.6.3. I have installed django and other necessary library using pip3 too. -
How to add csrf token in django with js only without ajax?
I basically want to implement a django view that accepts some json data and then also posts a json data which would be displayed.The confirm group view accepts a list of people via json data , forms a group and then returns the group code back to display. The other answers I found focused on sending csrf token during an ajax request and not simple js. I am beginner in django and js so please answer accordingly. Thanking you in advance :) view.py def confirm_group(request): data = json.loads(request.body.decode("utf-8")) grp = Group() grp.group_code = group_code_generator() grp.save() for i in range(len(data)): Player = Regplayer.objects.filter(pk=data[i]["pk"]) pl = Enteredplayer() pl.regplayer = Player pl.group = grp pl.save() return JsonResponse(grp.group_code, safe=False) script.js function confirm() { var i = 0; var rows= document.getElementById("group").children; var num= document.getElementById("group").childElementCount; if(num==0) { } else { // alert("Confirm grouping of "+num+" people?"); for(i=0; i < num; i++) { send_name=rows[i].children[0].children[0].innerHTML; send_gender=rows[i].children[3].children[0].innerHTML; send_clgname=rows[i].children[1].children[0].innerHTML; send_sport=rows[i].children[2].children[0].innerHTML; send_id=rows[i].children[5].innerHTML; myObj["data"].push({"name":send_name, "gender":send_gender, "college":send_clgname, "sport": send_sport, "pk": send_id}); alert(JSON.stringify(myObj)); } //POST TO BACKEND // Sending and receiving data in JSON format using POST method // var ourRequest = new XMLHttpRequest(); var url = "/confirm_group/"; ourRequest.open("POST", url, true); ourRequest.setRequestHeader("Content-type", "application/json"); // POST var data = JSON.stringify(myObj); ourRequest.send(data); // Obtain ourRequest.onreadystatechange = … -
What is the best way to refresh a simple div below using AJAX?
I'm having trouble making the element that displays the value, live, from the DB update via AJAX. This app, is supposed to take a number, add 1 to it, save the new value and display the updated value, live to the user. It is a simple counter based off of AJAX. Objective: I need to get the {{ number_post }} number to reflect the recently changed value in the DB, live, without having to refresh the entire page. What is the best way of doing this? Views.py: from django.shortcuts import render, redirect from django.http import HttpResponse from django.template import Context, loader from home.models import DeathNum import datetime import time def index(request): counter = DeathNum.objects.get(pk=1) return render(request, 'home/basenum.html', {'number_post': str(counter.deaths)} ) def counterf(repeat): while True: time.sleep(5) counter = DeathNum.objects.get(pk=1) counter.deaths += 1 counter.save() print('Added @ %s ' % datetime.datetime.utcnow()) time.sleep(5) return redirect(index) basenum.html: {% extends "home/index.html" %} {% block content %} <br /> <div class="banner"> <div class="bannerNum"> <p div class="numberOf"> Number of deaths in Blank since 1999: </p id="number1"> <br /><br /><br /> <a href="http://127.0.0.1:8000/counter"><p id="h2s">Please click here to see the live counter...</h2></a> <br /> <br /> <br /> <div class="death-div"> <p class="death1"> {{ number_post }} </p> </div> </div> </div> {% … -
Pyinstaller running Error in loading python DLL
I have created an executable file for my django project using pyinstaller. while running py installer i'm getting error as below Error loading Python DLL 'C:\Dev\EXE\cookie\build\cookie_tableau_crumbs\python3 .dll'. LoadLibrary: The specified module could not be found. Steps that i followed : 1.pyinstaller --name= project_name C:\Dev\EXE\cookie\manage.py 2.projectname.exe localhost:8000 -
Should Meta Classes in Models Inherit From Object
It seems pretty conventional to write models something like this: from django.db import models class Foo(models.Model): name = models.CharField(max_length=100, null=False) class Meta: ordering = ("name") Is there any reason class Meta: is used, and not class Meta(object):? Is there any reason not to explicitly inherit from object? -
Django Admin ForeignKey field widget options and inconsistent defaults
I have a model that has foreign keys, and in the admin those FKs render as drop-down lists. However, some of them show buttons for 'add', 'edit', and 'delete' of the elements in the related table, and others do not. I cannot figure out what is different between the fields such that some render one way and some render a different way. My ideal situation is that those buttons do not render for any foreign keys, that editing one model is restricted to just changes on that entity itself. I see that Django ultimately selects the RelatedFieldWidgetWrapper for these fields. I can set can_add_related, can_change_related, and can_delete_related on this widget, but I don't see how to easily pass these as options for these fields so that they are all consistent. How do I manage turning these options on and off in the admin? -
Finding difference of two time objects in django
I want to know about the best way to find the difference between two time objects in Django. I want to know whether the time of a particular object is in a difference of 4 hours or not. I have my models.py as class Task(models.Model): time = models.TimeField() In the shell, I tried something like from django.utils.timzone import datetime, timedelta obj_time = Task.objects.first().time obj_time - datetime.now().time() < timedelta(hours=4) But I get the following error TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time' How should I go about solving this? -
Custom LoginView in Django 2
I am trying to customise the authentication and view in Django 2 but the problem is that if the user is already authenticated the login form is still shown and it is not redirected to the appropriate URL. To get over this I have done the following: class CustomLoginView(LoginView): form_class = LoginForm template_name = 'login.html' def get_initial(self): if self.request.user.is_authenticated and self.request.user.is_staff and has_2fa(self.request.user): return HttpResponseRedirect(reverse('{}'.format(self.request.GET.get('next', 'portal_home')))) else: return self.initial.copy() def form_valid(self, form): if self.request.user.is_staff and not has_2fa(self.request.user): logger.info('is staff but does not have 2FA, redirecting to Authy account creator') auth_login(self.request, form.get_user()) return redirect('2fa_register') return HttpResponseRedirect(self.get_success_url()) But the HttpResponseRedirect in get_initial() does not redirect to the /portal/ page. I have also tried redirect('portal_home') but nothing happens or do I need to write a custom dispatch? Any help would be much appreciated. -
Heroku free dyno working hours are not working properly
I have only one Django app with PostgreSQL running on heroku and I have 801.59 free dyno hours (80.16%) used this month. Can anyone explain me how it is possible? 801.59:24=33,39 Today is the nineteenth of December, so where 14 days disappeared? -
Django TimePicker Does Not Work, How To Integrate TimePicker
I am trying to get TimePicker to work for my Time selection in the form. I tried to do this based on this very old blog http://bradmontgomery.blogspot.my/2008/11/selecttimewidget-custom-django-widget.html In forms.py from django.forms.extras.widget import SelectTimeWidget ... class CompanyWorkingHoursSettingsForm(forms.ModelForm): mon_start = forms.TimeField(widget=SelectTimeWidget()) mon_end = forms.TimeField() tue_start = forms.TimeField() tue_end = forms.TimeField() class Meta: model = Workinghours fields = ("mon_start","mon_end","tue_start","tue_end") However it cause this problem: from django.forms.extras.widget import SelectTimeWidget ModuleNotFoundError: No module named 'django.forms.extras.widget' Im using Django==1.11.7. So Im not sure whats the best way to do TimePicker for the TimeField ? Do show me the right way to implement TimePicker (in bootstrap) for TimeField. -
Django: Dynamically add CharField to form
I am working on a voting app in Django and I want to be able to add new choices with an "add" button. I currently have this: https://i.stack.imgur.com/kcpyR.png View: def newPollView(request): if request.method == 'GET': form = submitPollForm() else: form = submitPollForm(request.POST, extra=request.POST.get('extra_field_count')) # Bind data from request.POST into a PostForm if form.is_valid(): usedChoices = [] question = form.cleaned_data['question'] choice_1 = form.cleaned_data['choice_1'] q = Question.objects.create(question_text=question, pub_date=timezone.now()) c1 = q.choice_set.create(choice_text=choice_1, votes=0) usedChoices.append(choice_1) choiceList = [choice for choice in form.cleaned_data if choice is not 'question' and choice is not 'choice_1' and choice is not 'extra_field_count'] for choiceName in choiceList: c = form.cleaned_data[choiceName] if c != "" and c not in usedChoices: usedChoices.append(c) q.choice_set.create(choice_text = c,votes=0) return HttpResponseRedirect(reverse('vote:index')) return render(request, 'vote/newPoll.html', {'form': form,}) Forms: class submitPollForm(forms.Form): question = forms.CharField(max_length=250) choice_1 = forms.CharField(max_length=250,required=True) extra_field_count = forms.CharField(widget=forms.HiddenInput()) def __init__(self, *args, **kwargs): extra_fields = kwargs.pop('extra', 0) super(submitPollForm, self).__init__(*args, **kwargs) self.fields['extra_field_count'].initial = extra_fields print(extra_fields) for index in range(2,int(extra_fields)+4): self.fields['choice_{index}'.format(index=index)] = forms.CharField(max_length=250,required=False) Template: <script> function showMessage(){ form_count = Number($("[name=extra_field_count]").val()); window.alert(form_count); form_count ++; element = $('<input type="text"/>'); element.attr('name', 'choice_' + form_count); $("#forms").append(element); $("[name=choice_count]").val(form_count); } </script> <form action="/vote/newPoll.html" method='post'> {% csrf_token %} <h1>Create a new Poll</h1> <label>Enter name of the poll:</label> {{ form.as_p }} <Button type = 'button' onclick="showMessage()">add another</Button> … -
Why can't I see running django migration saves in postgress
I'm migrating over from mongo to postgres, however I can't see the intermediate results in the postgres table. Why is this the case? I know it works because I've tested the migrations locally on the smaller database, but with a larger testing database it takes ages and I see nothing.