Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Standalone Script
I am trying to access my Django (v1.10) app DB from another python script and having some trouble doing so. This is my file and folder structure: store store __init.py__ settings.py urls.py wsgi.py store_app __init.py__ admin.py apps.py models.py ... db.sqlite3 manage.py other_script.py In accordance with Django's documentations my other_script.py looks like this: import django from django.conf import settings settings.configure(DEBUG=True) django.setup() from store.store_app.models import MyModel But it generates a runtime error: RunTimeError: Model class store.store_app.models.MyModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I should note that my INSTALLED_APPS list contains store_app as its last element. If instead I try to pass a config like this: import django from django.conf import settings from store.store_app.apps import StoreAppConfig settings.configure(StoreAppConfig, DEBUG=True) django.setup() from store.store_app.models import MyModel I get: AttributeError: type object 'StoreAppConfig has no attribute 'LOGGING_CONFIG'. If I edit settings.py and add LOGGING_CONFIG=None I get another error about another missing attribute, and so on. Any suggestions will be appreciated. -
Cant see image from project directory [python][django]
I tried to handle this but I gave up. I have folder with images and I want to display my some image in html view but It wont work. I followed this tutorial enter link description here this my project tree: As you can see I tried to create plenty of directories to make it work. This is my settins: STATIC_URL = '/static/' # STATICFILES_DIRS = [ # os.path.join(BASE_DIR, "media"), # '/webstore/', # ] MEDIA_ROOT = '/webstore/media/' MEDIA_URL = '/media/' this is my html view where I try to display my image <img src="/media/example.jpg" /> this is my urls.py file from django.conf.urls import url, include from django.contrib import admin from djangoproject import settings from django.conf.urls.static import static urlpatterns = [ url(r'^', include('webstore.urls')), url(r'^admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Django & wsgi - setting on debian 8
I'm new to Django and I want to configure my app with apache2. I just follow the guide and the other question, but I can't figure out! My simple configuration file sites-available/000-default.conf: <VirtualHost *:80> WSGIScriptAlias / /var/www/html/mysite/mysite/wsgi.py WSGIPythonPath /var/www/html/mysite <Directory /var/www/html/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> after apache2 restart there is a syntax error in WSGIPythonPath if I put utside WSGIPythonPath inside apache2.conf file, the application does not work. What is the problem? I follow https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/modwsgi/ but WSGIDaemonProcess seems not to work -
Django error while saving Foreign Key - Can not assign none , Doesn't allow null values
I have two models - Events and Tenants. class EventsModel(models.Model): sys_id = models.AutoField(primary_key=True, null=False, blank=True) tenant_sys_id = models.ForeignKey('tenant.TenantModel', on_delete = models.CASCADE, null=False, blank=True) name = models.CharField(max_length=80, null=False, blank=False) start_date_time = models.DateTimeField(null=False, blank=False) end_date_time = models.DateTimeField(null=False, blank=False) created_when = models.DateTimeField(null=False, blank=True) def save(self, *args, **kwargs): self.created_when = timezone.now() self.tenant_sys_id = 1 #for-testing-only return super(EventsModel, self).save(*args, **kwargs) This model have a FK tenant_sys_id to tenant model. If for this I set null = False then below error is thrown. ValueError('Cannot assign None: "EventsModel.tenant_sys_id" does not allow null values.',) I am setting the value of this field in overridden save method. Setting null = True doesn't throw this error. However is I do the same for created_when field this behavior is not shown. Irrespective of null=True/False, value is being set from save method and saved. I am getting this error in View File. form = EventsForm(request.POST) print(request.POST) # print print(form) # do not print. error here <-- if form.is_valid(): # error here if above line is commented. form.save() ModelForm class class EventsForm(ModelForm): class Meta: model = EventsModel fields = '__all__' So here I am not able to understand - 1. why I must set FK to null=True and not created_when in order to … -
How to disable sorting by primary key in Django Admin?
Django admin sorts by primary key in addition to sorting fields specified in the model "ordering" record, thus, making it necessary to have composite indexes on a model just to allow sorting, which can be very prohibitive on a moderate amount of data(~5 000 000 records) This is a default behaviour of Django Admin selecting query SELECT * FROM `book` ORDER BY `book`.`added_at` ASC, `book`.`book_id` DESC LIMIT 100 I want to achieve the following behaviour SELECT * FROM `book` ORDER BY `book`.`added_at` ASC LIMIT 100 -
Getting Django function to return and render HTML page
I have function (inside a class) that returns True if a user is_authenticate() and is_active but it is not returning HTML as I thought it would. class LoginDetails: def __init__(self, request): self.request = request self.template = 'myapp/errorpage.html' self.context = {} def user_is_logged_in(self): if self.request.user.is_authenticated() and self.request.user.is_active: print 'USER IS AUTHENTICATED!' return True print 'USER IS NOT AUTHENTICATED!' return render(self.request, self.template, self.context) views.py: def authUsers(request): logindetails = LoginDetails(request).user_is_logged_in() return HttpResponse("HTML Error Page Not Rendered") How do I get the function to display/render error page without me doing it in views.py? Example of what I want to achieve is Stackoverflow's Page Not Found. -
Django POST with url argument impossible
I use django generic views POST def post(request,pk): poll = get_object_or_404(Poll,pk=pk) try: selected_item = poll.item_set.get(pk=request.POST['id']) except (KeyError,Item.DoesNotExist): return redirect("polls:detail") else: selected_item.votes += 1 selected_item.save() return redirect('https://www.google.com') But I got POST multiple argument. This is my url. url(r'^(?P<pk>[0-9]+)/vote$',views.PollVoteView.as_view(),name="vote") -
Post Request data by android does not display in Database backend as Django ?
I am working a as backend Django developer in which android developer send me a POST request with multiple key value pair and my work is to save it database MySQL but it's not correctly displayed in Django-admin site and when I send POST request through POSTMAN extension it's showing correctly . views.py @csrf_exempt def signup(request): if request.method == 'POST': if request.POST.get('type') == 'Student': stu_obj = Student.objects.create() stu_obj.email_id = request.POST.get('email') stu_obj.username = request.POST.get('username') stu_obj.full_name = request.POST.get('full_name') stu_obj.password = request.POST.get('password') stu_obj.phone_number = request.POST.get('phone_number', '') stu_obj.save() return JsonResponse({"status": "saved"}) return JsonResponse({"status": "not saved"}) else: return JsonResponse({'error': 'request is not accepted by server'}) Here my admin site view -
Can Django Leak PII?
I'm writing a Tor hidden service in python 3, and debating whether to write my own web server with sockets or use a more powerful framework such as django. So my question is, should I be worried about django leaking personally identifiable information? And if it does, should I invest extra time into brewing my own web server or is there a simpler solution? -
Django Template Does Not Exist at /
So i have this in my urls.py file urlpatterns = [ url('^$', IndexView.as_view(), name='index'), ] And my view is as follows: class IndexView(TemplateView): template_name = 'index.html' @method_decorator(ensure_csrf_cookie, name="dispatch") def dispatch(self, *args, **kwargs): return super(IndexView, self).dispatch(*args, **kwargs) But when i hit the link localhost:8000/ I get an error saying:- raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) TemplateDoesNotExist: index.html -
Django + google SMTP not working
I know this question has been there like million times, but I have a problem anyway. I need to configure Django to send emails via Google SMTP. My settings look like this: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'mymail@gjk.cz' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 587 EMAIL_USE_TLS = True When I type the username and password to gmail.com, it logs me in so I believe they are correct. However, when I try to send an email, I get this: I allowed less secure apps in google settings. But the result is still the same. Do you have any idea? Might the problem be somehow related to the fact that I do not have a @gmail.com email and I belong under an organisation? Thanks for any ideas. -
Django - Automatically change some "terms" in the response text based on settings
Let us say that we have two applications, Foo and Bar, and we use the same backend code for both of them. In our case, we decided to deploy two versions of this code -- one for each application. There are some endpoints where the server would behave slightly differently depending on whether it is running as Foo or Bar. Some endpoints are also not available for one app. (There are some reasons we are doing it like this). We use a flag in the settings file to determine the server type (Foo and Bar type). So far everything is working well, except for one thing: aside from the slight difference in behavior, there are also some terms that should be automatically change (translated?) -- both in the templates and in the REST API -- depending on the server type. For instance, in the page header, Foo would display "Welcome to Foo", and Bar should display "Welcome to Bar". The question is, how do I achieve this? -
Django filtering on foreign key properties
I'm trying to filter a table in Django based on the value of a particular field of a foreign key. my models are: class Retailer(SCOPEModel): """ A business or person that exchanges goods for vouchers with recipients """ office = models.ForeignKey(Office, related_name='retailers') uuid = UUIDField(auto=True, version=4, null=True, help_text=_('unique id')) name = models.CharField(_('Name'), max_length=50, validators=[validate_sluggable], help_text=_('Name of the retail shop'), blank=False) location = models.ForeignKey(Location, verbose_name=_('location'), blank=True, null=True, help_text=_('Location of the retail shop'), related_name='retailers') class PointOfSaleTerminalAssignment(SCOPEModel): """Point Of Sale (POS) is the location where a transaction occurs for exchange of goods and services and a POS terminal is the hardware used to perform the transactions. These terminals are registered in the system. POS' are managed at office level """ office = models.ForeignKey(Office, related_name='pos_terminals') terminal_type = models.ForeignKey( TerminalType, verbose_name=_('Terminal'), help_text=_("Device | Make (model)"), ) wfp_number = models.CharField( _('WFP Number'), max_length=50, unique=True, validators=[validate_sluggable], help_text=_("WFP unique generated number e.g. Inventory number") ) serial_number = models.CharField( _('Serial Number'), max_length=50, unique=True, help_text=_('Hardware device serial number') ) slug = models.SlugField( editable=False, unique=True, help_text=_('Unique ID generated from the WFP number') ) assigned_retailer = models.ForeignKey( Retailer, related_name='pos_terminals', null=True, blank=True, help_text=_('Retailer this POS terminal is assigned to') ) i want to get details of retailers and their assigned pos serial numbers … -
Using CSVSQL in Python Script
In python shell, the output of command: CSVSQL kmeans.csv > textfile.txt is a text file containing create table SQL statement for the csv file: CREATE TABLE kmeans( id INTEGER NOT NULL, state VARCHAR(2) NOT NULL, sfips INTEGER NOT NULL, fullname VARCHAR(31) NOT NULL, population INTEGER NOT NULL, percapincome INTEGER NOT NULL, unemploymentrate FLOAT NOT NULL ); I want to use the same command in my python code: def to_db(request, doc_id, upload_id): doc = get_object_or_404(Docs, pk=doc_id) upload = get_object_or_404(Uploads, pk=upload_id) path = os.path.join(MEDIA_ROOT, upload.csv_file.name) tblname = upload.file_title args = [os.path.join(MEDIA_ROOT, upload.csv_file.name), ">" , "C:\Users\FL\Viberr-master new\sql\textfile.txt"] CSVSQL(args).main() upload.in_db = True upload.save() The new textfile created is empty and does not contain the SQL statement that is the output of the command CSVSQL(args).main(). How should I write the output in a text file ? Thanks -
Turkish character issue while posting data from android to django
When I post turkish charecter(like ü,ö,ı,ğ) data from android to django turkish characters seems as question mark(like � and ?) Android protected Boolean doInBackground(Void... voids) { HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://10.0.3.2:8000/get_post"); List<NameValuePair> nameValuePair = new ArrayList<>(6); nameValuePair.add(new BasicNameValuePair("name", name)); nameValuePair.add(new BasicNameValuePair("topic", topic)); nameValuePair.add(new BasicNameValuePair("content", content)); nameValuePair.add(new BasicNameValuePair("email", email)); nameValuePair.add(new BasicNameValuePair("dep", dep)); try { httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } try { HttpResponse response = httpClient.execute(httpPost); // write response to log Log.d("Http Post Response:", response.toString()); } catch (ClientProtocolException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } return true; } Python django if request.method == 'POST': name = request.POST.get("name") topic = request.POST.get("topic") content = request.POST.get("content") email = request.POST.get("email") dep = request.POST.get("dep") img_path = request.POST.get("img_path") -
Exception in worker process & No module named wsg
I am trying to deploy my Django web app on heroku. An Application error message appears to me when I try to open it. this is my log: 2016-09-27T07:56:16.836350+00:00 heroku[web.1]: State changed from crashed to starting 2016-09-27T07:56:21.160909+00:00 heroku[web.1]: Starting process with command `gunicorn myblog.wsgi --log-file -` 2016-09-27T07:56:24.063399+00:00 app[web.1]: [2016-09-27 07:56:24 +0000] [3] [INFO] Listening at: http://0.0.0.0:37485 (3) 2016-09-27T07:56:24.062805+00:00 app[web.1]: [2016-09-27 07:56:24 +0000] [3] [INFO] Starting gunicorn 19.4.5 2016-09-27T07:56:24.063556+00:00 app[web.1]: [2016-09-27 07:56:24 +0000] [3] [INFO] Using worker: sync 2016-09-27T07:56:24.066328+00:00 app[web.1]: [2016-09-27 07:56:24 +0000] [9] [INFO] Booting worker with pid: 9 2016-09-27T07:56:24.069171+00:00 app[web.1]: [2016-09-27 07:56:24 +0000] [9] [ERROR] Exception in worker process: 2016-09-27T07:56:24.069172+00:00 app[web.1]: Traceback (most recent call last): 2016-09-27T07:56:24.069175+00:00 app[web.1]: worker.init_process() 2016-09-27T07:56:24.069175+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/base.py", line 122, in init_process 2016-09-27T07:56:24.069176+00:00 app[web.1]: self.load_wsgi() 2016-09-27T07:56:24.069174+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 515, in spawn_worker 2016-09-27T07:56:24.069177+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/base.py", line 130, in load_wsgi 2016-09-27T07:56:24.069178+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2016-09-27T07:56:24.069179+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi 2016-09-27T07:56:24.069179+00:00 app[web.1]: self.callable = self.load() 2016-09-27T07:56:24.069180+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 65, in load 2016-09-27T07:56:24.069181+00:00 app[web.1]: return self.load_wsgiapp() 2016-09-27T07:56:24.069181+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp 2016-09-27T07:56:24.069182+00:00 app[web.1]: return util.import_app(self.app_uri) 2016-09-27T07:56:24.069183+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/util.py", line 357, in import_app 2016-09-27T07:56:24.069183+00:00 app[web.1]: __import__(module) 2016-09-27T07:56:24.069185+00:00 app[web.1]: Traceback (most recent call last): 2016-09-27T07:56:24.069185+00:00 app[web.1]: File … -
Model Choice Field - get the id
I am busy trying to get the id only in integer format preferably for the ModelChoiceField. I get the list to display but get's returned in a string format. Please helping me in retrieving the id of ModelChoiceField. I think I need to do this in the view. forms.py class ProjectForm(forms.ModelForm): items = forms.ModelChoiceField(queryset=Project.objects.all()) class Meta: model = Project fields = ['items'] models.py class Project(models.Model): items = models.IntegerField(default=0, blank=True, null=True) views.py def ProjectView(request): form = ProjectForm(request.POST) if request.method == 'POST': if form.is_valid(): save_it = form.save(commit=False) save_it.save() return HttpResponseRedirect('/') else: form = ProjectForm() return render(request, 't.html', {'form': form }) -
Not nesting version of @atomic() in Django?
From the docs of atomic() atomic blocks can be nested This sound like a great feature, but in my use case I want the opposite: I want the transaction to be durable as soon as the block decorated with @atomic() gets left successfully. Is there a way to ensure durability in django's transaction handling? Background Transaction are ACID. The "D" stands for durability. That's why I think transactions can't be nested without loosing feature "D". Example: If the inner transaction is successful, but the outer transaction is not, then the outer and the inner transaction get rolled back. The result: The inner transaction was not durable. I use PostgreSQL, but AFAIK this should not matter much. -
Sharing authentication in Django
we are developing an application using Angular2 as frontend and Django as a backend. A Django backend is already in place, while the Angular2 application is in development. We chose, for obvious reasons, to use Django REST as a way to communicate with the backend. The application login and the backend login are done in two different pages but of course the login domain and the user base is the same. The two login are working properly by themselves, but we wanted to find a way to implement a transparent login (so an user can log into any of the two application and be recognized by the other one without re-logging). The Angular frontend is currently using Token Authentication. The server does send the csfr and session cookie along with the token. Moving to the backend, the csfr cookie is preserved, while the session is not, so a new login is required (of course, backend and Angular frontend are on different subdomains but in the same domain, the cookies are set on the domain, with two dots: '.domain.com') . Is it possible to do what we desire? Could someone help us find the proper way to do it? We've done … -
Python K-Medoids Clustering in Django
anyone knows how to run this code https://github.com/letiantian/kmedoids in Django website? what requirement i should install beside Django? i really need your help. Thank you -
AngularJS + django-allauth + django-rest-framework
I've been trying to integrate angular with django allauth with custom ui for login. When I do ng-click on a button I am doing an http request to /accounts/google/login/ which returns me an object containing html string as data. How do I render this html? I tried to do ng-bind-html with ngSanitize, it doesn't work. Is there any other approach to do the above? -
Python list to django javascript as text
Hello my generated python output list is l = ["one","two","there"] I am passing that to a django html script as {{list}} in the html it is shown as [&#39;one&#39;,&#39;two&#39;,&#39;three&#39; which i can't use for my javascript, how do i pass this correctly, even I tried json_dumps like l = json_dumps (["one","two","there"]) it just shows as following in html [&quote;one&quote;,&quote;two&quote;,&quote;three&quote;] -
How to store uploaded file to database as blob in django?
As the title says, I want to upload a file to the database as blob. When I write this in the model: blob = models.FileField(upload_to = 'file_folder') it appears as a <input type="file" /> just like what I want but the field type in database is varchar and it is saving the path of the file in the database but when I write this in the model: blob = models.BinaryField() the field type in database is blob just like what I want but it appear as <input type="text" /> How can I make it appear as <input type="file" /> in the view and at the same time, the field type is blob AND of course, it should save the file content in the database, not the path. -
Which docker container choose for a django application in production
I am new to docker. I saw existing images like one called "django" on docker hub. It sounds great but i see this image is working with django integrated server on 8000 http port. So i am wondering if this docker prebuilt image is for development purpose instead of production. Which prebuilt image should i use for production ? Thanks -
Django Zinnia blog error for entries
I am trying to fix issue with Zinnia blog application and its popping up error related to aggregator and entries. Following is the code if someone have a suggestion: def get_authors(context, template='zinnia/tags/authors.html'): """ Return the published authors. """ entries = Entry.objects.all() return {'template': template, 'authors': Author.published.all().annotate( count_entries_published=Count('entries')), 'context_author': context.get('author')} Above I don't think causing any issue but below is the code that might be causing all the fuss in second last line. def get_queryset(self): """ Return a queryset containing published entries. """ now = timezone.now() return super( EntryRelatedPublishedManager, self).get_queryset().filter( models.Q(entries__start_publication__lte=now) | models.Q(entries__start_publication=None), models.Q(entries__end_publication__gt=now) | models.Q(entries__end_publication=None), entries__status=PUBLISHED, entries__sites=Site.objects.get_current() ).distinct() Please suggest a solution because overall Zinnia is an impressive app but with one error its almost useless. Owner of the repo already got plenty of users with same complain. Error is same with both Python2 and PYthon3. For generous coders willing to work on this, repo is located at https://github.com/Fantomas42/django-blog-zinnia/issues. Traceback: File "C:\Users\Shazia\zinblog\lib\site-packages\django-1.10.1-py2.7.egg\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "C:\Users\Shazia\zinblog\lib\site-packages\django-1.10.1-py2.7.egg\django\core\handlers\base.py" in _legacy_get_response 249. response = self._get_response(request) File "C:\Users\Shazia\zinblog\lib\site-packages\django-1.10.1-py2.7.egg\django\core\handlers\base.py" in _get_response 217. response = self.process_exception_by_middleware(e, request) File "C:\Users\Shazia\zinblog\lib\site-packages\django-1.10.1-py2.7.egg\django\core\handlers\base.py" in _get_response 215. response = response.render() File "C:\Users\Shazia\zinblog\lib\site-packages\django-1.10.1-py2.7.egg\django\template\response.py" in render 109. self.content = self.rendered_content File "C:\Users\Shazia\zinblog\lib\site-packages\django-1.10.1-py2.7.egg\django\template\response.py" in rendered_content 86. content = template.render(context, self._request) …