Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Syntax Error in SQL Query( select ) when an empty list is passed
I'm running SQL Query using python-Django RAW Query..!! I'm using IN() function to pass my tuple in the query. My code looks like this... Here I am getting the list of dnc_domains and dnc_company from a json/function dnc_domain_names = list(map(lambda x: get_domain_name(x), dnc_websites)) dnc_company_names = list(map(lambda l: l.lower(), list(filter(None, list(map(lambda x: x['company_name'], dnc_info)))))) QUERY: select_query = """ select c.id from ( select id, lower(company_name) as c_name,substring(website from '(?:.*://)?(?:www\.)?([^/]*)') as website_domain, from contacts where campaign_id = %s ) c where c.c_name IN %s OR c.website_domain IN %s """ Executing Query: with connection.cursor() as cursor: cursor.execute(select_query, (campaign.id,tuple(dnc_company_names),tuple(dnc_domain_names)) matching_contact_ids = cursor.fetchall() But, there is a case when any dnc_company_names or dnc_domain_name is empty [] then my Query throws an Error otherwise if there at least 1 element in any of them then it works fine. SQL Error: syntax error at or near ")" LINE 5: WHERE id IN () ^ So, help me to tackle this error. SQL should handle both empty or non empty tuples. -
Nothing Helps! Manager isn't available; 'auth.User' has been swapped for 'user.User'
I am trying to make a signup form and save users. I am getting this error: Manager isn't available; 'auth.User' has been swapped for 'user.User'. That's because in my settings.py the AUTH_USER_MODEL = 'user.User' instead of AUTH_USER_MODEL = 'auth.User'. I dont' want to change that because I use that in another piece of code. I saw people having this problem online aswell and they said: " you have to define User with the Custom User model and you can do this with get_user_model at the top of the file where you use User " I tried that but I still get the same error. Please help! register.html {% block content %} <h1>Signup</h1> <form class="site-form" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="register"> </form> {% endblock %} forms.py from django.contrib.auth.forms import UserCreationForm from user.models import User from django import forms from django.contrib.auth import get_user_model class UserCreationForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = get_user_model() fields = ('email', 'name') def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 … -
Django Extra Views, CreateWithInlinesView - how to get InlineFormSet pass to _form.html?
How do I get InlineFormSet to show in my building_form.html? views.py from django.contrib.auth.mixins import LoginRequiredMixin from extra_views import InlineFormSet, CreateWithInlinesView from buildings.models import Building, Gallery from .forms import BuildingForm class GalleryInline(InlineFormSet): model = Gallery fields = ['image', 'caption'] class BuildingCreateView(LoginRequiredMixin, CreateWithInlinesView): model = Building form_class = BuildingForm inlines = [GalleryInline, ] template_name = 'cms/building_form.html' forms.py from django.contrib.gis.forms import OSMWidget, ModelForm from buildings.models import Building class BuildingForm(ModelForm): class Meta: model = Building fields = '__all__' widgets = { 'point': OSMWidget( attrs={ 'map_width': 600, 'map_height': 600, 'template_name': 'gis/openlayers-osm.html', 'default_lat': 56, 'default_lon': 10, 'default_zoom': 7, } ) } class Media: css = { 'all': ( 'https://cdnjs.cloudflare.com/ajax/libs/ol3/3.20.1/ol.css', 'gis/css/ol3.css', ) } js = ( 'https://cdnjs.cloudflare.com/ajax/libs/ol3/3.20.1/ol.js', 'gis/js/OLMapWidget.js', ) building_form.html {% block content %} <form enctype="multipart/form-data" method="post" action=""> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit"/> </form> {% endblock %} -
Django static files in Development not working
I have the following directory structure in my project: I'm trying to serve the static files in my environment, but I always getting the 404 error. This is my settings.py configuration: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) I also put this in my urls.py: URLS: from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns() And this is my view: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- Tell the browser to be responsive to screen width --> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <!-- Favicon icon --> <link rel="icon" type="image/png" sizes="16x16" href="../assets/images/favicon.png"> <title>Nossas Finanças</title> <!-- Bootstrap Core CSS --> <link href="{% static 'plugins/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> I've follow a lot of tutorials but I don't know what i'm doing wrong. I know by this question (Django Static Files Development) that the static files are served in two different way when is in Dev and in production. Someone can help me? -
Is it possible to install mysqlclient (DB API driver) without using pip and PyPI?
I've been learning Python. I've installed Mysql database downloaded from the official website.I have Django framework installed through downloading it from the official website https://www.djangoproject.com/download/. Now I need mysqlclient (DB API driver). I've learned of possible security risks as to using pip and PyPI. The widely used pip package management system, which most Python developers rely on, doesn't require cryptographic signature before executing code when a package is installed. PyPI is a third party repository. According to PyPI officials (the article as of 9/16/2017), PyPI does not have any full time staff devoted to it. It is a volunteer run project with only two active administrators. As such, it doesn't currently have resources for some of the proposed solutions such as actively monitoring or approving every new project published to PyPI. On Septermber 16, 2017, there came some news about some Malicious Libraries uploaded into PyPI. My question is how to installmysqlclient needed in the context of Python, Django and Mysql database, without using pip and PyPI repository? -
Restful API optimization to get huge data
I have a page for listing categories. There are parameters under categories and sub-parameters under parameters and data is huge. Recently I developed and tested the same. It is taking a lot of time and the performance is severely hit. Because there are about 1600 API calls(API calls to fetch the data for each of the categories, parameters & sub-parameters) for that single page. I have two questions. 1) Which way is effective? a or b? a) I have an API to get data for a parameter, so that I can make use of this call 1600 times to get data for all categories/parameters/sub-parameters. b) Have one call to get all parameters/parameters/sub-parameters data 2) Does AWS charge based on number of the calls? -
OSError: [Errno 12] Cannot allocate memory
I have implemented below code for multiprocessing that can handle multiple request concurrently but I'm getting below error. For that i use producer and consumer concept where producing putting process in queue and consumer consume that process and do some JOB. Traceback (most recent call last): p.start() File "/usr/lib/python2.7/multiprocessing/process.py", line 130, in start self._popen = Popen(self) File "/usr/lib/python2.7/multiprocessing/forking.py", line 121, in __init__ self.pid = os.fork() OSError: [Errno 12] Cannot allocate memory queue = Queue() lock = Lock() producers = [] consumers = [] for frame in frames: `enter code here`producers.extend([Process(target=self.producer, args=(queue, lock, frame)) for i in xrange(cpu_count())]) for i in range(50): p = Process(target=self.consumer, args=(queue, lock)) p.daemon = True consumers.append(p) for p in producers: #time.sleep(random.randint(0, 5)) p.start() for c in consumers: #time.sleep(random.randint(0, 5)) c.start() # Like threading, we have a join() method that synchronizes our program for p in producers: p.join() u_end = time.time() print u_start, u_end print('Parent process exiting...') -
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?