Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error while running migration return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: near ")": syntax error
I am learning Django and making a basic app till now I have coded the account handling part but when I run python manage.py migrate I get this is the console I can't understand which file to look into, Operations to perform: Apply all migrations: accounts, admin, auth, contenttypes, sessions Running migrations: Applying accounts.0003_auto_20180910_1420...Traceback (most recent call last): File "C:\Python\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Python\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: near ")": syntax error The above exception was the direct cause of the following exception: Operations to perform: Apply all migrations: accounts, admin, auth, contenttypes, sessions Running migrations: Applying accounts.0003_auto_20180910_1420...Traceback (most recent call last): File "C:\Python\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Python\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: near ")": syntax error The above exception was the direct cause of the following exception: return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Python\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Python\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Python\lib\site-packages\django\db\utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Python\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Python\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute return Database.Cursor.execute(self, query, … -
Django teacher-student model filtering data
I have a user model in Django in which the usertype field is "administrator" for teachers and "student" otherwise. class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=False) username = models.CharField(max_length=25, unique=True) password = models.CharField(max_length=50) usertype = models.CharField(max_length=140, null=True) teacher = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null = True ) objects = UserManager() I also have a Django model for student data: class Row(models.Model): user = models.TextField(max_length=500, blank=True) question = models.TextField(max_length=500, blank=True) answer = models.TextField(max_length=500, blank=True) When a teacher is logged in, I display their list of students and want them to be able to view a copy of the student's data (a modal should pop up). <table> <h2>Students Directory: </h2> <tr> <th>Name</th> <th>Email</th> <th>Download Data</th> </tr> {% for student in usertable %} <tr> <td>{{ student.first_name }} {{ student.last_name}} </td> <td>{{ student.email }}</td> <td><a onclick="viewData({{student.username}});"> Download Link </a></td> </tr> {% endfor %} </table> So, I pass the student's username into viewData() and that should pop up the modal. However, the function is written in javascript and I can't do something like - "Row.objects.all.filter(username=username)". However, I can't pass the already filtered object into the profile.html because I don't know which student's username I will need. There's probably an easy solution to this that I'm missing somewhere. … -
Deploying Django project with Pyinstaller and Apache
I am looking to deploy a Django project to run locally on user's machine. I've looked into what webservers can be used to run the project and as it will be running in a Windows environment only I have tried using IIS and Apache (WAMP). The Django project runs fine in the developmnent mode (runserver). It also runs fine on both web servers when using an uncompiled version of the code. The problem comes when I try to package the project using Pyinstaller. As this builds a .exe I have the change the way the web servers run the project. In IIS this actually works fine using wfastcgi, I just make wfastcgi as the target of the build and set IIS to run this .exe. However IIS requires a few additional settings to be set and I've struggled to find a way for these to be set at the point of install so instead I've tried to use Apache. As mentioned Apache works fine when just using the source code and wsgi.py. An example of what I have in my httpd.conf file is below. # Apache httpd.conf settings LoadModule wsgi_module "C:/Program Files (x86)/Python36-32/Lib/site-packages/mod_wsgi/server/mod_wsgi.cp36-win32.pyd" WSGIScriptAlias / "C:/mysite/wsgi.py" WSGIPythonHome "c:/Program Files (x86)/python36-32" … -
Jquery datatables not displaying data in heroku python django?
I am trying to render a jquery datatable in a html form. Now, for some weird reason, I can see that I can receive the data from my API, but nothing shows up in the datatable. Interesting enough, the same code works perfectly when I am running in my local machine. But when i check the error in my heroku logs, I see that i get this error. error logs (index):254 Uncaught TypeError: Cannot read property 'length' of undefined at Object.success ((index):254) at fire (jquery-1.12.4.js:3232) at Object.fireWith [as resolveWith] (jquery-1.12.4.js:3362) at done (jquery-1.12.4.js:9840) at XMLHttpRequest.callback (jquery-1.12.4.js:10311) But in my local server, everything works perfectly fine. $(document).ready(function () { //We have to get all users in the system var jsonres=[] var orgid = $('#orgid').val(); console.log('orgid',orgid) $.ajax({ url: "/user/api/v1/userapi/", type: "get", success: function (json) { console.log("json", json) json = json.results; for(var i=0;i<json.length;i++){ console.log('jsonnnn',json[i].orgid) if(json[i].orgid==orgid){ jsonres.push(json[i]) } } console.log('jso',jsonres) var data = jQuery.map(jsonres, function (el, i) { /* if(el.title.length>20){ el.title = el.title.substring(0,10) + '..........'; }*/ return [[el.userid, el.firstname, el.lastname, el.mobilenumber, el.email, el.isactive]]; }); $('#demotbl').DataTable({ "searching": true, "bLengthChange": false, "order": [[3, "desc"]], "aaData": data, "bPaginate": true, "aoColumns": [ {"sTitle": "userid"}, {"sTitle": "firstname"}, {"sTitle": "lastname"}, {"sTitle": "mobilenumber"}, {"sTitle": "email"}, {"sTitle": "isactive"}, ] }) } }) … -
Write django unit test for model.py
Below is a class in model.py of my project. I need help in writing django unit test for this class especially for end date should be after start date class Unit(models.Model): name = models.CharField(max_length=200) start = models.DateTimeField() end = models.DateTimeField() description = models.TextField() deleted = models.BooleanField(default=False) def clean(self): if self.end and self.start and self.end <= self.start: raise ValidationError({ 'end': _('End date should be after start date') }) def __str__(self): return self.name -
How to show an ImageField in Django template
I have looked this questions from the stack overflow. question 1 question 2 about showing an image field in a template and follow accordingly. But the image is not showing in the template although the image is properly uploaded to the folder. models.py class Book(models.Model): book_thumbnail = models.ImageField(upload_to='images/%Y/%m/%d', blank=True, null=True) views.py def home(request): book = Book.objects.all() return render(request, 'books/books.html', context={'books': book}) template.html <img class="group list-group-image" src="{{ books.book_thumbnail.url }}" width='240' alt="alt" /> settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py urlpatterns = [ path('books/', views.home), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
D3v5 and Django Rest Framework
I'm having some trouble getting the following AJAX call to work. I'm using D3 version 5 to make the following POST request to a Django REST Framework (DRF) ModelViewSet (version 3.x) view. DRF provides the list of tasks under the path /gander/tasks/ and allows one to create a new one by POST'ing to the same path. I believe I'm retrieving the CSRF token correctly but I'm not sure I'm formulating the POST properly. d3.json("/gander/tasks/?format=json", {method:"POST", headers:{ "Content-type": "application/json; charset=UTF-8", "X-CSRFToken" : Cookies.get('csrftoken') }, body:JSON.stringify({ "parent": null, "name" : "", "time" : null}), }) .then(json => {console.log(json);}) .catch(error => {console.log(error);}); I've gone through the Django A.J.A.X. docs, D3 examples and a stack of S.O. Questions but they all refer to the D3-Request interface and I can't find any examples using the newer D3-Fetch API as above. -
Login_redirect_url Django 2
Hi I am trying to redirect the user to a different URL when the user logs in: urlpatterns = [ url(r'^$', views.home), url(r'^login$', auth_views.LoginView.as_view (template_name='accounts/login.html')) settings.py LOGIN_REDIRECT_URL = '/account/' It works but I would like '/account/' to take my user to home (home.html) What am i doing wrong here? thank you -
Override MultipleSelectField with Textarea to add many fields in Django ModelForm
I would like to have the possibility to add ManyToMany fields using a textarea instead of MultiSelect field. This textarea will search in DB for tag occurrencies or will add a new tag. This is my code: MyModel.py class Event(models.Model): name = models.CharField('Name', max_length=100, blank=True, default='') created_at = models.DateTimeField('Date', auto_now_add=True) tag = models.ManyToManyField('Tag') class Tag(models.Model): value = models.CharField('Tag Value', max_length=100) STATE = ( ('1', 'domain'), ('2', 'ip'), ('3', 'url'), ) type = models.CharField('Type', max_length=2, choices=STATE) admin.py from django.contrib import admin from .models import Event, Tag from . import forms @admin.register(Event) class EventAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'created_at') form = forms.EventAdminForm @admin.register(Tag) class TagAdmin(admin.ModelAdmin): list_display = ('value', 'type') forms.py class EventAdminForm(forms.ModelForm): extra_field = forms.CharField(widget=forms.Textarea) # textarea I wish to use to dinamically add tag class Meta: model = Event fields = ['id', 'name', 'tag'] def save(self, commit=True): event_item = super(EventAdminForm, self).save(commit=True) uploaded_tags = self.cleaned_data['extra_field'] uploaded_tags = uploaded_tags.splitlines() event_item.tag.clear() tag2insert = [] for custom_tag in uploaded_tags: tag_type = getTagType(custom_tag) # ('1', 'domain') => '1' if tag_type != 0: t, created = Tag.objects.get_or_create(value=custom_tag, type=tag_type) tag2insert.append(i) # does not works # event_item.tag.add(t) # does not works # event_item.save_m2m() # does not works # for saved_tag in tag2insert: # event_item.tag.add(saved_tag) event_item.save() return event_item I preferred … -
How to combine two query sets into a dict like object?
from itertools import chain import json checkin = Checkins.objects.get(checkinno=1) checksins = (Checkins.objects.filter(checkinno=1).values('checkinno', 'date', 'time', 'consulted', 'closed')) custid = checkin.hospitalid.cstid checks = (customer.objects.filter(cstid=custid).values('name', 'age', 'gender', 'mobile', 'email', 'address')) result_list = list(chain(checksins, checks)) print(result_list) I get: [{'checkinno': 1, 'date': datetime.date(2018, 9, 10), 'time': '6:10 PM', 'consulted': 0, 'closed': 0}, {'name': 'Jeff', 'age': 5, 'gender': 'male', 'mobile': '000000', 'email': '', 'address': ''}] What I want: ['checkinno': 1, 'date': datetime.date(2018, 9, 10), 'time': '6:10 PM', 'consulted': 0, 'closed': 0, 'name': 'Jeff', 'age': 5, 'gender': 'male', 'mobile': '000000', 'email': '', 'address': ''] -
Pass a template tag to a child template
I need to pass the result of a template tag to a child template. Parent template: {% template_tag param1 param2 as templink %} {% include "child_template.html" with templink1=templink %} child_template.html: <a href="">Download</a> The result of the template tag is a url which is an input to the href in the child template. The template tag is a simple_tag. Using 'as' for variable assignment breaks the app. What are the possible alternatives to evaluate the template tag and pass the url to the child template? -
Django uwsgi gets killed
The uwsgi gets killed and we could receive a core dump file generated with following logs. Anyone faced a similar issue. Please guide... Platform: Ubuntu 16.04 Program terminated with signal SIGQUIT, Quit. #0 __lll_lock_wait () at ../sysdeps/unix/sysv/linux/x86_64/lowlevellock.S:135 135 ../sysdeps/unix/sysv/linux/x86_64/lowlevellock.S: No such file or directory. [Current thread is 1 (Thread 0x7eff0c4d5700 (LWP 6239))] (gdb) (gdb) bt #0 __lll_lock_wait () at ../sysdeps/unix/sysv/linux/x86_64/lowlevellock.S:135 #1 0x00007eff0c0badbd in __GI___pthread_mutex_lock (mutex=0x70b028 <uwsgi+6248>) at ../nptl/pthread_mutex_lock.c:80 #2 0x000000000041f265 in wsgi_req_accept () #3 0x0000000000467856 in simple_loop_run () #4 0x000000000046765e in simple_loop () #5 0x000000000046befa in uwsgi_ignition () #6 0x000000000047063d in uwsgi_worker_run () #7 0x0000000000470c20 in uwsgi_run () #8 0x000000000041e76e in main () -
Deployment of a Django app on Apache2 404 not found
I googled it and i searched everywhere including, but i could't find any solution for my problem. I'm trying to deploy an django application on a VPS server. I set up apache2 with my project but i always get a 404 not found. Here are my configurations: project path : /var/www/master WSGI file path /var/www/master/projectx249/wsgi.py Apache2 site conf path: /etc/apache2/site-available/mekhoukh.conf Apache2 site conf file: for this part this is the last conf i tried on it. <VirtualHost *:80> <Directory /var/www/master/projext249> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess mekhoukh python-home=/usr/lib/python3.5 python-path=/var/www/master WSGIProcessGroup mekhoukh WSGIScriptAlias / /var/www/master/projext249/wsgi.py i'm using ssh to connect trough the server, i also updated the /etc/hosts with the public ip pointig to the domain name and the localhost ip pointing to it too. -
Django graphene (graphql) get only latest record of each product
The following MySQL example is basically what I want to achieve in graphql. Filter records by time and field I have model: class HighRiskPackingList(models.Model): productCode = models.ForeignKey(Productlist, db_column='productCode', on_delete=models.CASCADE) currentStock = models.IntegerField(db_column='currentStock', blank=False, null=False) stockNeeded = models.IntegerField(db_column='stockNeeded', blank=False, null=False) created = models.DateTimeField(auto_now_add=True, editable=False, null=True, blank=True) last_modified = models.DateTimeField(auto_now=True, editable=False, null=True, blank=True) And the following graphql query: { filterHighriskpackinglist{ edges{ node{ lastModified productCode{ productid } } } } } that returns the following result: { "data": { "filterHighriskpackinglist": { "edges": [ { "node": { "created": "2018-09-10T13:08:14.755115+00:00", "productCode": { "productid": "SS5" } } }, { "node": { "created": "2018-09-10T13:08:14.755115+00:00", "productCode": { "productid": "SV1" } } }, { "node": { "created": "2018-09-10T13:08:15+00:00", "productCode": { "productid": "SV1" } } }, // ... What I would like is a query that would return a result where there is only one productid called SV1, and it would be the one that was last created. -
What is the DRF way to return a list of items from a third party api?
I have an endpoint where I need to make make a request to a third party API to get a list of items and return the results to the client. Which of the following, or any other approach would be better suited to DRF? Make input parameter validation and the call to the third party API and in the view method, pass the list of items in the response to a serializer for serialization and return serializer data to the client Pass the request parameters to the serializer as write-only fields, make the field validation, api call and serialization in the serializer A mixture of 1 and 2; use 2 different serializers, one that takes request parameters as write only fields, validates input parameters and makes the request to the 3rd party api, and another serializer that takes the resulting list from the first serializer and serializes the items for use of client -
Django Group Link in Custom Object: Serialization problem
I try to implement a Model in which 2 groups are linked. I made this model: GroupLinker.py from django.contrib.auth.models import Group from django.db import models class GroupLinker(models.Model): EMSGroup = models.ForeignKey(Group, on_delete=models.CASCADE, related_name="EMSGroup", default=None) LDAPGroup = models.ForeignKey(Group, on_delete=models.CASCADE, related_name="LDAPGroup", default=None) But in my /POST request, I just want to specify their names: { "links": [ { "EMSGroup": "UserAdministrator", "LDAPGroup": "master group" } ] } My main problem is to figure out how to implement it with the Django Serializing process. I tried to implement a GroupLinkerSerializer like this: GroupLinkerSerializer.py from api.Models.GroupLinker import GroupLinker from django.contrib.auth.models import Group from rest_framework import serializers class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('name',) class GroupLinkerSerializer(serializers.ModelSerializer): EMSGroup = GroupSerializer() LDAPGroup = GroupSerializer() class Meta: model = GroupLinker fields = ("EMSGroup", "LDAPGroup") Off course I understand it cannot retrieve the requested groups by itself (only with the names), so I thought, in my ClassView I could do this, and pass to the GroupLinkerSerializer the parameters it needs (the Groups in Dicted format), but the fact I set the name of each group in the GroupSerializer is non-sense after thinking about it... Here is my View (which is non well coded at all I already know): … -
Return PNG image from Django views is damaged
I'm working on a Django(2) project in which I need to return a PNG image as HttpResponse when I return this image in the form of a zip archive it returns the image correctly, but when I return the PNG image directly it damaged the image. Here's my code: How it's writing the image: img_resized = cv2.resize(seg_image, dsize) cv2.imwrite(os.path.join(settings.BASE_DIR, 'img/MaskedImage.png'), img_resized) How it's returning the Image: response = HttpResponse(os.path.join(settings.BASE_DIR, 'img/MaskedImage.png'), content_type='image/png') response['Content-Disposition'] = 'attachment; filename=MaskedImage.png' return response It returns an Image with the name MaskedImage.pn but the image is damaged, not able to open. What can be wrong here? Thanks in advance! -
django search results on different page
I am learning the search functionality of Django. I want to show my search result on the separate page. eg. listingsearch home-v3.html page <form method="POST" action="/listingsearch/"> {% csrf_token %} <div class="input-group input-group-1"> <span class="input-group-addon" id="basic-addon1">Find</span> <input type="text" name= "srh" class="form-control" placeholder="Business Name Type Karo" aria-describedby="basic-addon1" list="find"> <datalist id="find"> <option value="Food"> <option value="Service"> <option value="Hotel"> </datalist> </div> <button class="btn btn-default" type="submit"><i class="fa fa-search" style="font-size: 25px"></i></button> <div class="fix"></div> </form> listing-search.html <div> {% if sr %} {% for k in sr %} <table border="0px" width="300px" <tr> <td> {{ k.business_name }} </td> </tr> {% endfor %} {% endif %} </div> View Page def homesearch(request): if request.method == 'POST': srch = request.POST['srh'] if srch: match = business_info.objects.filter(Q(business_name)) if match: return render(request, 'listing-search.html', {'sr':match}) else: messages.error(request,'no result found') else: return HttpResponseRedirect('/homesearch/') return render(request, 'home-v3.html') URL page urlpatterns = [ path('admin/', admin.site.urls), path('home/', business_info_form), path('signup/', signup), path('homesearch/', homesearch), path('listingsearch/', listingsearch) ] Models.py Page class business_info(models.Model): business_name = models.CharField(max_length=100, null=True) email_id = models.EmailField(max_length=60, null=True) mobile = models.CharField(max_length=10, null=True) def __str__(self): return self.business_name i want to know how can i make my search better. please help. -
What is the difference between south migrations and django migrations?
Can anyone please explain me the difference between south migrations and django migrations? What advantage/disadvantage one has over another? -
Cannot import name 'login'
Hi I am currently working on a project in Django... I am trying to import login from django.contrib.auth.views but getting the following error. from django.conf.urls import url from . import views from django.contrib.auth.views import login urlpatterns = [ url('', views.home), url('login', login, {'template_name': 'accounts/login.html'}) ] error message(cmd): ImportError: cannot import name 'login' Any help? Thank you -
Django Debug Toolbar show in the html page
I have added the django toolbar in the settings.py when i run the api xx.xxx.xx.xx:8000 the debug tool is shown and its working fine. Toolbard image Now i want to show the django debug tool on the each page of my website since the performance of the site pretty slow i would like to understand the issue hence i need to integrate the django debug tool bard on each i am using the fronend as Vue js i want to show this tool bar on each page of the vue file how can i do it -
Django HttpRequest vs. Request
I'm new to Django. Curious to note that every "view" function has a "request" as the first parameter, but when I look for "request" object in the documentation, I got "HttpRequest" instead... Are they the same? If so, why bother to give two names for the same object? Thanks! -
Broken virtualenv but no succes with other solutions Library not loaded: @executable_path/../.Python
When i tried to start django I get this: (daxtest) MacBook-Pro-15-Officerebel:daxtest timvogt$ python manage.py runserver dyld: Library not loaded: @executable_path/../.Python Referenced from: /Library/Frameworks/Python.framework/Versions/3.6/bin/python3 Reason: image not found Abort trap: 6 -
Securely outputting Django's URLField in template
I am confused about how to securely output a link stored in Django's URLField. My model links something like this: class Article(models.Model): article_title = models.CharField(max_length=1000000) article_url = models.URLField(max_length=20000, default='') When I output the link from the Article class I simply do this: views.py context = { 'article': article } template.html <a href="{{ article.article_url }}" target="_blank"> {{ article.article_title }} </a>) Is this safe or do I need some validation at some point? -
Heroku-Django: 1000s of H13 errors for no apparent reason?
My app is running the following processes (Procfile): web: daphne artist_notify.asgi:channel_layer --port $PORT --bind 0.0.0.0 -v1 worker: python manage.py migrate --noinput && python manage.py runworker -v1 celerybeat: celery -A artist_notify beat -l debug celerybackgroundworker: celery -A artist_notify worker -Q regular,important -l info -n backgroundworker@%h celeryworker: celery -A artist_notify worker -Q important -l info -n importworker@%h In my Metrics pane, Heroku is showing over 1500 errors like that for the web process/dyno in the last 24 hours, starting around 12 hours ago. Heroku defines an H13 error as such: H13 - Connection closed without response This error is thrown when a process in your web dyno accepts a connection, but then closes the socket without writing anything to it. 2010-10-06T21:51:37-07:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=GET path="/" host=myapp.herokuapp.com fwd=17.17.17.17 dyno=web.1 connect=3030ms service=9767ms status=503 bytes=0 One example where this might happen is when a Unicorn web server is configured with a timeout shorter than 30s and a request has not been processed by a worker before the timeout happens. In this case, Unicorn closes the connection before any data is written, resulting in an H13. Previously, when such errors were being reported by Heroku's Metrics pane, I could see them …