Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Installing pyodbc failed on Linux
I just run this command: sudo pip install pyodbc then I get below message and error: steven81@PythonWEBVM:~$ sudo pip install pyodbc The directory '/home/steven81/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/home/steven81/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Collecting pyodbc Downloading https://files.pythonhosted.org/packages/aa/71/cef225c4889620a1a00251d24c1746fe0cf4124290a75d1c2dc5c187b61f/pyodbc-4.0.23.tar.gz (215kB) 100% |ββββββββββββββββββββββββββββββββ| 225kB 13.5MB/s Installing collected packages: pyodbc Running setup.py install for pyodbc ... error Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-NR7ytY/pyodbc/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-voJYBN/install-record.txt --single-version-externally-managed --compile: running install running build running build_ext building 'pyodbc' extension creating build creating build/temp.linux-x86_64-2.7 creating build/temp.linux-x86_64-2.7/src x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -DPYODBC_VERSION=4.0.23 -I/usr/include/python2.7 -c src/pyodbcmodule.cpp -o build/temp.linux-x86_64-2.7/src/pyodbcmodule.o -Wno-write-strings cc1plus: warning: command line option β-Wstrict-prototypesβ is valid for C/ObjC but not for C++ In file included from src/pyodbcmodule.cpp:11:0: src/pyodbc.h:56:17: fatal error: β¦ -
How can I move my django apps large production postgres database table data to development database?
I have a Production database table called sensordata with over 70 million entries, I need to have the same in my development database so I can check speed tests and do some query optimization. I used django 1.11 and postgres. All the other tables in development have data exactly same as in production except for sensordata. I tried doing dumpdata and loaddata but the json file obtained after dumpdata was too large to do loaddata. Is there anyway to do this with postgres? -
Model Creation calls its related model save method?
Having these kind of model definitions and a relationship between the two: class Car(models.Model): description = models.CharField(max_length=35) def save(self, **kwargs): invalidate_cache() super().save(**kwargs) def delete(self, **kwargs): invalidate_cache() return super().delete(**kwargs) class Passenger(models.Model): car = models.ForeignKey(Car, related_name='passengers') I have defined custom save and delete on the Car model because when a car instance is modified I have to perform some extra operations, in particular I need to invalidate a cache. My doubt is: creating/updating/deleting a related model would call these custom methods? I'll try to be more clear: c1 = Car(description='super fast car') p = Passenger(car=c1) Clearly the creation of the c1 calls the Car.save but would the creation of the instance p of Passenger call the Car.save or not? From my tests it seems so but I want to be more sure it wasn't just a specific case and this happens all the time in the Django model handling cycle (I could not find a specific documentation on this). -
How can I return a user's object-level permissions within a Django Rest Framework response?
Some of my DRF endpoints have custom permissions applied so they're editable only by the object author as well as site administrators, all other authenticated users have read-only access. For example, a comment: May be edited by the author or site admins and can be viewed read-only by all other authenticated users. All my permission handling within DRF is fine - My question is how can I best inform the user interface of the user's permissions? My intention is to have GUI logic to display an 'edit' option (client side) only if the user is allowed to edit the object (server side). I suspect this can be accomplished by passing the users permissions from the View to the Serializer. Is this the 'standard' approach? I hope I've overlooked something and this is basic and already builtin to DRF. How have others already addressed this? Thanks -
Django _ signal on special method calls in model
In my User model I have a method for generating new token . so I need to tell django signal when this method calls do something: models.py: class User(AbstractBaseUser): username = models.CharField(max_length=20, blank=True) first_token = models.ForeignKey(FirstToken, on_delete=models.SET_NULL, objects = UserManager() def generate_first_token(self, *args, **kwargs): ........ in signals.py def token_release(sender, instance, created, **kwargs): print(instance.first_token) post_save.connect(token_release, sender=User().generate_first_token()) so I want to call this signal when the generate_first_token() function called. -
Map IP+host as text in django
I created a Django project in ubuntu machine and hosted through an IP+host. I do not want the IP address to be shown in the URL. For example: python manage.py runserver 192.X.X.X:8000 URL : http://192.X.X.X:8000/ What I want is to make the URL look like below:- http://www.iphost.com/ -
Django-allauth restrict registration to list of emails
I'm using Django-allauth, I have a list of emails and I want to restrict registration to this list. My idea was to check the signing up user email and, if not in the emails list, stop registration process and redirect. I tried using allauth.account.signals.user_signed_up but i can't stop the registration process anyway. It sends the confirmation email and does not redirect anything. How can i do that? Thank you for help from allauth.account.signals import user_signed_up @receiver(user_signed_up) def auth_users(sender, request, user, **kwargs): auth_user_list = [ 'email_1', 'email_2', ... ] if not any(user.email in s for s in auth_user_list): return reverse('url_to_redirect') -
Keeping Bokeh plots when changing Django view
I am developing a Django application in which I can create some plots using Bokeh. The standard way I handle the Bokeh object is by calling script, div = components(fig, CDN) where fig is the Bokeh object that I created. Then, I pass the objects script and div to the template and I can visualize the plot. What I would like to do is to keep the created plot when changing view in order to be able to visualize the plot again without recreating it. So far I tried to follow two different approaches: 1) Save the plots components in the session (when I create the plot in the first view) as request.session['div']=div request.session['script']=script and then, in the second view, call div=request.session['div'] script=request.session['script'] The Django application looks like having no problems saving/loading the objects when changing from one view to the other, but the plot is not rendered in the second view (of course I call the objects both in the view context and in the template). 2) I tried to save the plot components as global variables, but the plot is not rendered once again. Am I doing anything wrong? Is there a simple way to achieve what I β¦ -
Serve blog from url path
My goal is to serve my blog from the path. So for example the blog's url should look like this: https://example.net/blog What is the best way to do it? I am using django and host on AWS -
Searching by primary key in PSQL and Django using SearchVector
I have the following method that perform search def _search_parts(self, query: str, limit: int) -> List[Part]: search_query = SearchQuery(query, config='simple') if len(query.split(' ')) > 1: for q in query.split(' '): search_query |= SearchQuery('+'+q, config='simple') search_vector = SearchVector('name', weight='B') + \ SearchVector('part_with_finish__manufacturer_product_code', weight='A') + \ SearchVector('part_with_finish__product_code', weight='A') + \ SearchVector('id', weight='A') + \ # <---- THIS LINE SearchVector('short_name', weight='A') search_rank = SearchRank(search_vector, search_query) parts = Part.objects.annotate(rank=search_rank).filter(rank__gt=0.0).order_by('-rank')[:limit] The following error appears with the SearchVector for the field id DataError at /api/v1/search invalid input syntax for integer: "" LINE 1: ...| setweight(to_tsvector(COALESCE("app_part"."id", '')), 'A')... ^ How to make it work? I can make a separate query by PK and merge results, but I wondering if it is possible to do it using a single query. -
Javascript: undefined table
I create a table through Javascript from Django models. Once this table is created, I cannot access to its cells values from an other javascript function, the error raised is that the table is "undefined". HTML <div id="fileList"> <table id="galleryTable" class="table table-striped table-advance table-hover"> <tr> <th>Field 0</th> <th>Field 1</th> <th>Field 2</th> <th>Field 3</th> <th>Field 4</th> <th>Field 5</th> <th>Field 6</th> </tr> </table> </div> JS code to create the table: <script type="text/javascript"> var imageObjectTable = []; var imageTable =[]; var dateTable = []; var urlTable = []; var commentTextTable =[]; var commentUserTable =[]; var commentUserProfilePicTable = []; var commenteDateTable =[]; var i = 0; {% for imagemodel in imagemodel %} imageObjectTable.push("{{ imagemodel }}"); imageTable.push("{{ imagemodel.image }}"); dateTable.push("{{ imagemodel.date_taken }}"); urlTable.push("{{ imagemodel.image.url }}"); {% for comment in imagemodel.comments.all %} commentTextTable.push(new Array()); commentTextTable[i].push("{{ comment.text }}"); commentUserTable.push(new Array()); commentUserTable[i].push("{{ comment.user }}"); commentUserProfilePicTable.push(new Array()); commentUserProfilePicTable[i].push("{{ comment.user.profile.profile_pic }}"); commenteDateTable.push(new Array()); commenteDateTable[i].push("{{ comment.created_date }}"); {% empty %} commentTextTable.push(new Array()); commentTextTable[i].push("No comment yet"); commentUserTable.push(new Array()); commentUserTable[i].push("No text comment yet"); commenteDateTable.push(new Array()); commenteDateTable[i].push("No date comment yet"); {% endfor %} i = i+1; {% endfor %} table = document.getElementById("galleryTable"); for(var i = 0; i < imageTable.length; i++) { // create a new row var newRow = table.insertRow(table.length); var cell0 = newRow.insertCell(0); β¦ -
cant install magic library
I want to validate my csv file reader class UploadFilesForm(models.ModelForm): def clean_file(self): file = self.cleaned_data.get("file", False) filetype = magic.from_buffer(file.read()) if not "CVS" in filetype: raise ValidationError("File is not CVS.") return file class Meta: model = User fields = ('file_one', 'file_two') but i cant install magic, i am using pycharm and when i lack a library i just do a install library directly from code, if that gives me an error I find the library and install it into the env and if that fails i do a pip install... none of those has worked for me so far. short story i get an error here: magic.from_buffer(file.read()) and I cant install magic. I am working local from windows and my server is an EC2 ubuntu 16.04 instance -
Why should we use django-webpack-loader?
I use both webpack and django. Now I move bundled assets to /static/ directory of django each time, so I'd like to make more effective process. I read some articles and many people recommend to use django-webpack-loader, but I don't fully understand what it does. I've already read the official documents below. https://owais.lone.pw/blog/webpack-plus-reactjs-and-django/ https://406.ch/writing/our-approach-to-configuring-django-webpack-and-manifeststaticfilesstorage/ I think it's for collecting bundled assets located outside of django projects, but it seems almost same as creating a symbolic link from django project to dist/ directory in webpack. Is there any other useful feature in django-webpack-loader? -
Make a model field as required on the base of a condition in Django Models
I'm working on a project with Python(3.6) and Django(2.0) in which I need to make a field in child model required on the base of a condition for a field in parent model class. If the service is multiple then the routing field will be required otherwise it's not necessary to be filled. Here's my code from models.py choices = ( ('Single', 'Single'), ('Multiple', 'Multiple'), ) class UserAccountModel(models.Model): deployment_name = models.CharField(max_length=150) credentials = models.FileField(upload_to='media/credentials/', name='credentials'), project_name = models.CharField(max_length=150, blank=True) project_id = models.CharField(max_length=100, blank=False) cluster_name = models.CharField(max_length=150, blank=False) zone_region = models.CharField(max_length=150, blank=False) services = models.CharField(max_length=100, choices=choices) class AwdModel(UserAccountModel): source_zip = models.FileField(upload_to='media/awdSource/', name='awd_source') routing = models.TextField(name='routing') Help me, please! Thanks in advance! -
Adding time in timefield
I have a model which contains the following field time_start = models.TimeField(u"Start Time", blank=False) I want to add 1hr in start time and save it in a list Here is what I have tried import datetime as dt start_time = Timeslot.objects.get(pk=1) start = start_time.time_start print(start) a = (start+dt.timedelta(hours=1)).time() print(a) li = [] li.append(a) but I am getting error unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta' -
Validate Django Time
I am not able validate the date. my goal is to raise an error if the date entered is less than today. forms.py class user(forms.ModelForm): def clean(self): date = self.cleaned_data['date_one'] if date < datetime.date.now() raise forms.ValidationError('No past Date') return date class Meta: model = user_model widgets = { 'date_one': forms.DateInput(attrs={'class':'datepicker'}), } fields = '__all__' models.py class user_model(models.Model): name = models.CharField(max_length=20,null=True) contact = models.IntegerField(null=True) email = models.EmailField(max_length=50,null=True) date_one = models.DateField(null=True) def __str__(self): return self.name This is the error Exception Type: AttributeError Exception Value: 'str' object has no attribute 'get' -
IndentationError: unindent does not match any outer indentation level django
The below code is showing an indentation error...please help! def downtime_monitor(): content = {'when':timezone.now(), 'name':'saumitra', 'back_up':backup} message = '' template = 'downtime_alert.html' to = '+91756785696' response = send_sms(to, message, content, template) -
Loading static files referenced by other static files in django
In my Python Django project I have a static html file. Inside this html file other static files are referenced. Like this: <!DOCTYPE html> <html><head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <script>L_PREFER_CANVAS = false; L_NO_TOUCH = false; L_DISABLE_3D = false;</script> <script src="mfiles/leaflet_002.js"></script> <script src="mfiles/jquery.js"></script> <script src="mfiles/bootstrap.js"></script> <script src="mfiles/leaflet.js"></script> <link rel="stylesheet" href="mfiles/leaflet.css"> <link rel="stylesheet" href="mfiles/bootstrap.css"> ... The static html file is referenced from a template file using django template language as so: {% load static %} <iframe src="{% static "map.html" %}" id="iframemap" style="top:0;left: 0;width:100%;height: 100%; position: absolute; border: none;"> The problem is django can't find the static files (mfiles/leaflet_002.js etc.) referenced in the static html file, because in this html file, django template language cannot be used so django doesn't find path to these files. To make my architecture clean I present this simple diagram: django_template_file ----references----> map.html (static, loads fine) ----references----> mfiles/*.js etc. (PROBLEM django doesn't see those files) How can I tell django to look also in m_app/static/mfiles/* and not just to m_app/static/? Even though the static files in m_app/static/mfiles/ are referenced only from other static files located in m_app/static/ (and loaded correctly)? -
Python Django slug url error
I am writing a practice python django website. I am trying to connect the links, slugs, in my contact.html to separate html pages. Imputing the URL by hand for these objects outputs the site correctly. However, the links in contact.html won't like to the pages. {% extends "base.html" %} <!DOCTYPE html> {% block content %} <body> <h1>Contact page</h1> <div class = "contact"> {% for contact in contact %} <h2><a href="{ % url 'detail' slug = contact.slug %}">{{contact.title}}</a></h2> {% endfor %} </div> </body> {% endblock %} contact_detail.html (the page href in contact.html should like to this html; both html files are in contact/contact/templates) {% extends "base.html" %} <!DOCTYPE html> {% block content %} <body> <div class = "contact"> <p>{{contact.title}}</p> <p>{{contact.body}}</p> </div> </body> {% endblock %} views.py from django.shortcuts import render from .models import Contact from django.http import HttpResponse def contact(request): contact = Contact.objects.all() return render(request, 'contact/templates/contact.html', {'contact': contact}) def contact_details(request, slug): contacts = Contact.objects.get(slug=slug) return render(request, 'contact/templates/contact_detail.html', {'contact': contacts}) urls.py from django.urls import re_path from . import views from django.conf.urls import url from django.conf.urls.static import static urlpatterns = [ url('^$', views.contact, name="list"), url(r'^(?P<slug>[\w-]+)/$', views.contact_details, name = "detail"), ] models.py from django.db import models class Contact(models.Model): title = models.CharField(max_length=500) slug = models.SlugField() β¦ -
create login for different user role
how to create login for different user i.e in my case there is two user(client and advertizer) and wants to redirect to specify page according to user type,here is my manage.py and views.py,and also how to check authentication for different user type,and there is only one login page for all users manage.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,null=True,related_name='client_profile') #first_name = models.CharField(max_length=30) #last_name = models.CharField(max_length=40) #username = models.CharField(max_length=30) buisness_name= models.CharField(max_length=30,blank=True) USER_TYPE_CHOICES = ( ('c', 'client'), ('a', 'advertizer' ), ) type_user = models.CharField(max_length=20, default='c',choices=USER_TYPE_CHOICES) class Advertizer(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,null=True,related_name='advertizer_Profile') USER_TYPE_CHOICES = ( ('c', 'client'), ('a', 'advertizer' ), ) type_user = models.CharField(max_length=20, default='a',choices=USER_TYPE_CHOICES) views.py def user_login(request): if request.method == 'POST': # First get the username and password supplied username = request.POST.get('username') password = request.POST.get('password') # Django's built-in authentication function: user = authenticate(username=username, password=password) # If we have a user if user: #Check it the account is active if user.is_active: # Log the user in. login(request) if request.Client.user.type_user == 'c': # Send the user back to some page. # In this case their homepage. return render(request,'client.html') else: # If account is not active: return HttpResponse("Your account is not active.") else: print("Someone β¦ -
Reverse for 'view_artist_details' not found. 'view_artist_details' is not a valid view function or pattern name
model.py class Artist(models.Model): name = models.CharField(max_length=250) rating = models.FloatField(default=0.0) image = models.ImageField(upload_to='artist/',default='') info = models.TextField() slug = models.SlugField(max_length=250,default="") def __str__(self): return self.name @permalink def get_absolute_url(self): return ('view_artist_details', None, {'slug': self.slug}) views.py def artist_details(request,slug): artists = get_object_or_404(Artist,slug=slug) songs = Song.objects.filter(artist=artists) albums = Album.objects.filter(artist=artists) return render(request,'music/view_artist.html',{ 'artists': artists, 'songs':songs, 'albums':albums, }) Template tag used: <span class="padder-v"><a href="{{ artist.get_absolute_url }}" data-bjax data-target="#bjax-target" data-el="#bjax-el" data-replace="true" class="text-ellipsis">{{ artist.name }}</a></span> NoReverseMatch at /artist Reverse for 'view_artist_details' not found. 'view_artist_details' is not a valid view function or pattern name. This is the error that I am encoutring -
How to add property to django user class?
I want to add a property to a User class in order to check if "request.user.is_manager", I use a standard user class, and I have already a working project with foreign keys to the User class. Could you advice me the most correct way to do that -
Remove existing formatting of csv cell copied into text editor in django
I have made a forums website in Django. The textarea for entering question has NicEdit integrated for formatting purpose. However if I copy a cell from a CSV file and paste it into the textarea and save it, the database has some extra tags added along with it. Example: On copying a cell which contains this info: Audio in this file is not clear. Not only in this file but also in some files. Please check it. and pasting it in textarea and saving, the way it is getting saved in the database is \r\n\t\r\n\t\r\n\t\r\n\t\tbody,div,table,thead,tbody,tfoot,tr,th,td,p { font-family:"Liberation Sans"; font-size:x-small }\r\n\t\ta.comment-indicator:hover + comment { background:#ffd; position:absolute; display:block; border:1px solid black; padding:0.5em; } \r\n\t\ta.comment-indicator { background:red; display:inline-block; border:1px solid black; width:0.5em; height:0.5em; } \r\n\t\tcomment { display:none; } \r\n\t\r\n\t\r\n\r\n\r\n\r\n\r\n\t\r\n\t\r\n\t\t\r\n\t\r\nAudio in this file is not clear. Not only in this file but also in some files. Please check it. As a result, I'm unable to get the proper results for further use of this data. Is there any way I can remove this excessive formatting in python? As I'm working in django and fetching data from views.py I need to do this in python and I'm unable to do it till now. Currently I β¦ -
Multiselect form in Django Admin
I'm attempting to add a multi-select widget to my admin view that corresponds to a char-field. models.py class Campaign(models.Model): name = models.CharField(max_length=128) start_date = models.DateTimeField(default=timezone.now) end_date = models.DateTimeField(blank=True, null=True) budget = models.IntegerField() target = models.IntegerField() component_choices = models.CharField(max_length=128, null=True, blank=True) admin.py class CampaignAdmin(admin.ModelAdmin): fieldsets = ( ('Main', { 'fields': ('name', ('start_date', 'end_date',),), }), ('Budget', { 'fields': ('budget', 'target',), }), ('Payment', { 'fields': ('payment_terms', 'payment_initial', 'payment_per_mvm'), }), ) form = ComponentChoicesForm admin.site.register(Campaign, CampaignAdmin) forms.py class ComponentChoicesForm(ModelForm): component_type_choices = tuple( (x.id, str(x)) for x in ComponentType.objects.all() ) class Meta: model = ComponentType fields = '__all__' available_components = forms.MultipleChoiceField( choices=component_type_choices) However the above code only displays the fieldsets and not the ComponentTypeChoices form at all. My intent is to have the user select from the choices i generate in forms.py in the admin.py in order to populate the Campaign.component_choices field. -
How to integrate Dialogflow with Django (Python)?
I'm developing an assistant (bot) with Dialogflow, and i have this Django project where I have to extract data and then expose it through the bot, this is going to be stored in a local platform. I worked with Dialogflow and it's integration before but with Node.js and Javascript, with Django (python) is a brand new challenge and I'm confused. Until now I have the following: I'm developing an assistant (bot) with Dialogflow, and i have this Django project where I have to extract data and then expose it through the bot, this is going to be stored in a local platform. I worked with Dialogflow and it's integration before but with Node.js and Javascript, with Django (python) is a brand new challenge and I'm confused. Until now I have the following: I know I can do it with this package: https://github.com/dialogflow/dialogflow-python-client-v2 I add a url for a webhook, right now this works locally only, like this: from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import dialogflow @csrf_exempt def webhook(request): return HttpResponse('Works like a charm!') and in urls.py I have: url(r'^webhook$', views.webhook, name='webhook') And that's all I don't know how to proceed after this, I'm blocked and I don't know β¦