Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Different database user for each Django Admin user
In light of being GDPR compliant, it's useful to keep an audit of who does what and when on the data, speaking of the Admins. Many RDBMS systems and Cloud databases too, already have systems in place to do this, but they work on the assumption that a specific database user is accessing the database itself. But Django always use the very same, fixed, credentials (specified in settings.py), when accessing the database, so this auditing systems have no clue of which actual user is connected. Obviously it should be possibile to replicate the auditing functions on the application (Django) side (there already is the Django Admin history), but the database integrated systems are supposedly more robust. So this is the question, would it be possible to have different Django Users use a corresponding database user when accessing the database? That is, when a Django User makes a request, Django would have to use a corresponding database user credentials to connect to the database for all the connections needed to serve that particular request. A Django Database Router seems not to have the request instance available and as such, it doesn't seem possible for it to know the requesting User and … -
OSError: /usr/lib/libgdal.so.20: undefined symbol: sqlite3_column_table_name
I have followed the tutorial for installing Geodjango on my Ubuntu. I am using Django 1.11.2 and Python 2.7.6, postgres-9.3.2 and postgis 2.0.3. I have checked here and here, but found no solution. But after my installation, when I tried to run, I got error: OSError: /usr/lib/libgdal.so.20: undefined symbol: sqlite3_column_table_name lgdal = CDLL(lib_path) self._handle = _dlopen(self._name, mode) -
Problems converting Django project to .exe with Pyinstaller
I am working to convert my Django project to a .exe file using Pyinstaller. I want to be able to just click an icon and open the project in a browser. Here is my folder structure: proj __pycache__ proj __pycache__ __init__.py manage.py Dashboard __pycache__ __init__.py urls.py proj __pycache__ __init__.py settings.py urls.py wsgi.py static_cdn And here is my manage.py file: # -*- coding: utf-8 -*- import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj.settings") print("here") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc import django.test from html.parser import HTMLParser execute_from_command_line(sys.argv) Currently I cd to C:...\proj, then run pyinstaller --name=Dashboard proj/manage.py. Then when I click on Dashboard.exe in C:...\proj\dist\Dashboard, an error comes up. I'm not sure what is going wrong here. I think I may either have something wrong with my folder structure, or I may be calling the pyinstaller in the wrong folder. Any help is super appreciated! Additional information: I am following directions from this tutorial on how to make a .exe A similar question suggested adding an … -
Keyerror in Django when the key already exists
I am trying to get data from a user via this api request but its throwing Keyerror on email address when the key already exists. How to get through this?My view: @api_view(['POST']) def index(request): if request.method=='POST': email=request.data['email_address'].replace('%40','@') if Roctaves.objects.filter(email_address=email): return Response({'message':'email exists'}) mobile_number=str(request.data['phone']) if len (mobile_number)==10: try: mobile_number=int(mobile_number) roctaves=Roctaves() roctaves.name=request.data['name'] roctaves.elimination_preference=request.data.get['elimination_preference'] roctaves.genre=request.data['genre'] roctaves.number_of_participants=request.data['number'] roctaves.entry1=request.data['entry1'] roctaves.entry2=request.data['entry2'] roctaves.entries=request.data['enteries'] roctaves.phone='91'+mobile_number roctaves.email_address=email serializer=RoctaveSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors,status=400) except ValueError: return Response({'message':'Data entered is not in proper format'}) else: return Response({'message':'Data entered is not in proper format.Please try again'}) Thanks in advance. -
Send data from Gpslogger to django application throw rest framework
I need to send GPS location data from a mobile app called gpslogger but i didn't get any luck.The app supporting send data to a custom url so i manged to send the data to my localhost but the server alawys replay with 405 not allowed Here is my serializers: class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = [ "latitude", "longitude", "created_on", ] def create(self, validated_data): print(validated_data) return Location.objects.create(**validated_data) def update(self, instance, validated_data): print(instance,validated_data) # instance.username = validated_data.get('username', instance.username) instance.save() return instance LocationSerializer() class LocationHyperSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Location fields = [ "latitude", "longitude", "created_on", ] and here is also my views and urls code : class LocationAPIView(ListAPIView): queryset = Location.objects.all() serializer_class = LocationSerializer class LocationCreateAPIView(CreateAPIView): queryset = Location.objects.all() serializer_class = LocationSerializer urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/list/$', LocationAPIView.as_view()), url(r'^api/create/$', LocationCreateAPIView.as_view()), ] i send data as post request from the app interface but the server seems doesnt' accept the data sent from the app -
Save list of data item by item Django
Im creating a website that allows users to follow stocks and see articles based on what they follow. I createded a page to follow stocks by selecting checkboxes, pass that data into stocks_user_selected as a list, but am then unsure how to save the information to the database. Thanks in advance. models.py: class Stock(models.Model): name = models.CharField(max_length = 50) ticker = models.CharField(max_length = 50) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) followed_stocks = models.ManyToManyField(Stock, blank=True) def __str__(self): return self.user.first_name @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() views.py: def follow_stocks_post_registration(request): all_stocks = Stock.objects.all() if request.method == 'POST': stocks_user_selected = request.POST.getlist('stocks_selected') for stock in stocks_user_selected: request.user.profile.followed_stocks = request.user.profile.followed_stocks + stock #??? return render(request, 'core/post_registration_stock_following.html', {'all_stocks': all_stocks}) The form used to get the data: {% block head %} <title>Next step follow stocks</title> {% endblock %} {% block body %} <form action ="{% url 'follow_stocks_post_registration' %}" method="post" > {% csrf_token %} {% for stock in all_stocks %} <input type="checkbox" value="{{ stock.name }}" name="stocks_selected">{{ stock }} <br/> {% endfor %} <button type = "submit" value="Submit"></button> </form> {% endblock %} -
Calling a Model inside another Model - Django
I have 2 models listed. I want to be able to call the first model, into the second and have its fields show up as if they were originally in the first. And once I can do that, I want those fields to only show up if a certain condition was met. Essentially Id like to be able to have conditional fields in an object that appear when triggered. In this case when the "Application_Status" == 'Unavailable' Applications should only have the fields under 'Incident' if their status is 'Unavailable'. Otherwise they don't need any of that information and it does not exist. This is where I'm starting from. At this point it only gives me a blank drop down for incident. from django.db import models class Incident(models.Model): Incident_Number = models.CharField( max_length=10, default='', ) Incident_Link = models.URLField( default='' ) Point_of_Failure = models.CharField( max_length=50, default='' ) Description_of_Issue = models.TextField( max_length=500, default='' ) class Application(models.Model): Application_Name = models.CharField(max_length=50) AVAILABLE = 'av' UNAVAILABLE = 'un' Application_Status_Choices = ( (AVAILABLE, ' Available'), (UNAVAILABLE, 'Unavailable'), ) Application_Status = models.CharField( max_length=2, choices=Application_Status_Choices, default=AVAILABLE, ) incident = models.OneToOneField( Incident, on_delete=models.CASCADE, primary_key=True, default='' ) -
Facing issue in Zappa when try to access the API with Authorization token
I have implemented an API server using Django and Django-REST-Framework with Zappa in AWS Lambda. I use Auth0 for identity. When I try to signup or login from localhost it works well and good but when I try to do the same from the AWS domain it throws timeout errors. URL: https://api.bearete.com/api/v1/signup/ Logs: Starting new HTTPS connection (1): arete.auth0.com Task timed out after 30.03 seconds I need help to solve this issue. Thank you. -
How to translate all the contents inside model queries in DJango?
i am a new to Django, i am trying to make a small blog with two different languages, i got all the translations inside my blog including the admin, but still don't know how to translate the content of my posts. After i fetch the content using the models queries, inside my template i used to type this {% trans "SOME TEXT" %} and it works just fine, with variables that i am getting from database i am using this code: {% blocktrans %} {{head.title_text}} {% endblocktrans %} now when i type django-admin makemessages -l ru, inside django.po i can't see any new text that have been added. Also inside my views.py i tried this: head = Head.objects.first() trans_h = _(u'{}'.format(head)) but nothing gets added inside django.po Please, anyone knows how to resolve this issue ?? -
get stuck how to filter [ model.objects.filter(datetime.time).count() ] to django views.py
got stuck, I am a newbie on Django also a newbie with algorithm. I am trying to filter and count employee attendance. I have a table like this: attedance table: +-----+-----------------------+----------+-----------+ | id | time | status | emp_id | +-----+-----------------------+----------+-----------+ | 1 | 2018-04-17 7:03:40 | 1 | 1 | | 2 | 2018-04-18 7:10:50 | 1 | 1 | | 3 | 2018-04-19 5:05:32 | 1 | 1 | | 4 | 2018-04-20 7:07:44 | 1 | 1 | | 5 | 2018-04-18 7:10:50 | 1 | 2 | +-----+-----------------------+----------+-----------+ my objective is to filter all attendance data. got solution with models.model.objects.filter(emp_id=1).count() its return 4 in my case. but also filter that time(hour) must > 6 trying to add datetime.datetime(time).time() > 6 to the filter but its not work. any can help or suggest me how to make it happen?... or have other best scenario like use forloop, or it's not possible?... -
from django.db.models.sql.aggregates ImportError: No module named aggregates
I've been facing a particular problem with aggregates. In this code, sumcase class has a method add_to_query which is intended to instantiate the SQL implementation of the aggregate and sets it as a class variable (aggregate) which i'd be using to call the as_sql method in Default SQL Aggregate (django/db.models.sql.aggregates.Aggregate) from another file. My code (The first file, how I implement aggregate): from django.db.models.aggregates import Aggregate from django.db.models.sql.aggregates import Aggregate as SQLAggregate class SQLsumcase(SQLAggregate): is_ordinal = True sql_function = 'SUM' sql_template = "%(function)s(CASE WHEN %(when)s THEN %(field)s ELSE 0 END)" def __init__(self, col, **extra): if isinstance(extra['when'], basestring): extra['when'] = "%s" % extra['when'] if extra['when'] is None: extra['when'] = True super(SQLSumCase, self).__init__(col, **extra) class SumCase(Aggregate): -
I can't get Django's shell to perform as expected
So here is a script supposed to query the DB for some data and loop through the result and do some stuff...I have few comments on where the code works and where it does not. I am trying to test this locally before deploying... from app.models import Credit, Interest_History from django.utils.timezone import now import datetime from sys import stdout, stderr cr = Credit.objects.all() print(cr, file=stdout) #This prints properly for credit in Credit.objects.all(): print(credit.payment_date, file=stdout) #But this does not work at all!! How can I get the shell to work properly? Am I missing or doing something wrong? -
Configuring a MongoDB replica set to work with Django
I'm following these instructions to set up a replica set. I've successfully completed the Initiate the Replica Set step and now would like to make it somehow work with django. But I can't seem to figure out what exactly I should specify in the django app settings. I tried this: 'HOST': 'mongodb://mongo1:27017,mongo2:27017,mongo3:27017/?replicaSet=example' But it didn't work, instead it errored out with: pymongo.errors.ServerSelectionTimeoutError: mongo1:27017: [Errno -2] Name or service not known,mongo3:27017: [Errno -2] Name or service not known,mongo2:27017: [Errno -2] Name or service not known What am I doing wrong? P.S. In order to make django and mongodb coact in peace and harmony I'm using djongo which is set to be the engine for DATABASES in the settings file. -
Create .EML file in Django and return as response
I am trying to store an email as a eml file in Django. I have seen links that use the python email generator to create the email and store it to a file on the OS, and I have code that makes an email in the EmailMultiAlternatives class in Django. What I want is to create the email using the EmailMultiAlternatives class and instead of sending it just download the .eml file (gives the user chance to make changes to the file before sending along with other reasons that have been requested by the client). Is there anyway of doing this? I looked at the class and there is no save functionality for the class - only send. -
How can i find all instances of ViewClasses in Django
I can't find this. In my case i create simple a new instance. But i think Django make a instance for all viewclasses. ins=TicketSystem() # Instanz von Ticketsystem erzeugen ins.request=request # Request zuweisen context = TicketSystem.get_context_data(ins,*args,**kwargs) -
How to call a management.call_command in remote serve with Django?
I have a job script in Python that call a command to update AD users. When I run this command in my local machine, it works fine. But in our Remote Server, with Linux and Apache, the same script doesn't work and give me a error: "Unknown command: 'ldap_sync_users'... I tried to use other common commands like migrate (just to test) and it gives the same problem... This is the command that I'm trying to run and works fine in my local: # https://github.com/etianen/django-python3-ldap management.call_command('ldap_sync_users') I'm using Python 3.6, Django 2.0.4. In localserver I'm using virtualenv and in remote server Apache 2. What I'm doing wrong? Someone can help me? -
Is it possible to Switch template with a url variable? like Joomla TMPL=component switch
Hi We've just been dumped with a Django / Wagtail install ( not complaining - just don't know the system yet! ) Was starting to have a look at the templates. is there a simple mechanism to switch off the chrome ( or parts of the template ) like you can with Joomla using the tmpl=component switch? The use case is To be able to quickly pull content into other sites etc without menu items or footers. In my case I wanted to create popout modal links that would display content? is there a simple way to do this? is it simply a case of adding something into the base.html template to switch things off? -
django template tag running for loop not for all objects [duplicate]
This question already has an answer here: How do you limit list objects template side, rather than view side 2 answers I want to run for loop for 4 objects but when i use .all method it runs for all objects, here is my code {% for book in object.book_author.all %} ... {% endfor %} because of .all method for loop runs for all books but I want only 4. -
Using Djongo package with django applications
I am making a Django application which needs MongoDB as the backend database. I have used djongo (https://nesdis.github.io/djongo/get-started/) to get this MongoDB connected to Django. But then I add the following line in models.py: from djongo import models class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() class Meta: abstract = True class Entry(models.Model): blog = models.EmbeddedModelField( model_container=Blog, ) headline = models.CharField(max_length=255) And when I go to admin panel to add an entry I get the following error: SQLDecodeError at /admin/app/entry/ FAILED SQL: SELECT COUNT(*) AS "__count" FROM "app_entry" Pymongo error: OrderedDict([('ok', 0.0), ('errmsg', "Unrecognized pipeline stage name: '$count'"), ('code', 16436)]) Version: 1.2.24 Can anyone help me out here, please? Thank You -
Django - Related Field got invalid lookup: name when I have not mentioned name
hi I have a view in my Django project which essentially uses a search query to display a paginated list of results. In development mode, this 'querying' functionality works perfectly fine. However when deployed in production, when trying to make a query, the template returns the error Related Field got invalid lookup: name Although there is nowhere in my views.py where I use the word 'name'. The error seems to occur at the start of the pagination function according to the tracebacks interactive view. Traceback: File "/home/ubuntu/myproject/env/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/home/ubuntu/myproject/env/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/home/ubuntu/myproject/env/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/myproject/products/views.py" in results 129. def paginator_loop(arg): File "/home/ubuntu/myproject/env/lib/python3.5/site-packages/django/db/models/manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/ubuntu/myproject/env/lib/python3.5/site-packages/django/db/models/query.py" in filter 836. return self._filter_or_exclude(False, *args, **kwargs) File "/home/ubuntu/myproject/env/lib/python3.5/site-packages/django/db/models/query.py" in _filter_or_exclude 854. clone.query.add_q(Q(*args, **kwargs)) File "/home/ubuntu/myproject/env/lib/python3.5/site-packages/django/db/models/sql/query.py" in add_q 1253. clause, _ = self._add_q(q_object, self.used_aliases) File "/home/ubuntu/myproject/env/lib/python3.5/site-packages/django/db/models/sql/query.py" in _add_q 1271. current_negated, allow_joins, split_subq) File "/home/ubuntu/myproject/env/lib/python3.5/site-packages/django/db/models/sql/query.py" in _add_q 1277. split_subq=split_subq, File "/home/ubuntu/myproject/env/lib/python3.5/site-packages/django/db/models/sql/query.py" in build_filter 1207. raise FieldError('Related Field got invalid lookup: {}'.format(lookups[0])) Exception Type: FieldError at /results/ Exception Value: Related Field got invalid lookup: name Simplified version of views.py: def results(request): user … -
Django uninstall development version
I am facing a strange problem today. I was trying to install Django on my server and I accidentally installed the development following the official documentation.Now when I tried to start a new app using the django-admin startapp ure I got something like this. However, the file structure I know is something like this. app_folder --app_folder --db.sqlite3 --manage.py Now I don't see any manage.py on my server so I have no idea what to do with it. I tried the uninstalling Django using pip uninstall django and installed it again but the result is same. Any idea how can I get rid of the development version and get back to the official release I used before? -
Pinning one package breaks the graph
I am pinning django to a specific, older version: ... [packages] ... Django = "==1.10.8" I can not install: $ pipenv install Could not find a version that matches Django==1.10.8,>=1.11,>=1.6,>=1.7,>=1.8,>=1.8.7 Well, of course, those constraints are mutually exclusive. So I force a install anyway, to take a look at the graph: $ pipenv install --skip-lock And now taking a look at the graph: django-allauth==0.35.0 - Django [required: >=1.11, installed: 1.10.8] - python3-openid [required: >=3.0.8, installed: 3.1.0] - defusedxml [required: Any, installed: 0.5.0] - requests [required: Any, installed: 2.18.4] - certifi [required: >=2017.4.17, installed: 2018.4.16] - chardet [required: >=3.0.2,<3.1.0, installed: 3.0.4] - idna [required: >=2.5,<2.7, installed: 2.6] - urllib3 [required: >=1.21.1,<1.23, installed: 1.22] - requests-oauthlib [required: >=0.3.0, installed: 0.8.0] - oauthlib [required: >=0.6.2, installed: 2.0.7] - requests [required: >=2.0.0, installed: 2.18.4] - certifi [required: >=2017.4.17, installed: 2018.4.16] - chardet [required: >=3.0.2,<3.1.0, installed: 3.0.4] - idna [required: >=2.5,<2.7, installed: 2.6] - urllib3 [required: >=1.21.1,<1.23, installed: 1.22] (this happens with several packages) What should I do now? What I think will solve my issue is: search for all packages which are requiring a version higher than the one I want take a look at the homepages of those packages, and see if I … -
Django delete&update view only for owner
I'm writing some task for my university in Django.In my update&delete view I want to make sure that only an owner of object can update/delete it. Now everyone can do it. Here are views: class UpdateCar(SuccessMessageMixin, UpdateView): model = Car form_class = AddNewCarForm template_name = 'c2crental/car/update_car.html' success_url = reverse_lazy('c2crental:list_user_cars') success_message = _("Car has been updated.") def get_queryset(self): owner = self.request.user return self.model.objects.filter(owner=owner) class DeleteCar(DeleteView): model = Car success_url = reverse_lazy('c2crental:list_user_cars') template_name = 'c2crental/car/delete_confirm_car.html' success_message = _("Car has been deleted.") def delete(self, request, *args, **kwargs): messages.success(self.request, self.success_message) return super(DeleteCar, self).delete(request, *args, **kwargs) def get_queryset(self): owner = self.request.user return self.model.objects.filter(owner=owner) I found some solutions with querysets as shown above. They won't let other Users update/delete an object and raise Http404 error which is fine, but I want to use Django messages framework to print error message on page and dont redirect to Http404 page. How can I do that? -
render the form same without any changes from the request.post in django
I don't want the values to be updated from request.POST but require the old form values submitted before. so that, return render(request, 'view.html', {'form': form_html}) would return the old form and nothing updated from the new request. How can this be achieved? -
Editing profile in django python
I am adding in some functionality that allows a user to edit their personal profile page information. When the user updates their info and hit submit they are getting a NameErrorsaying that the user is not defined. Below is how I am trying to implement the editing functionality. forms #this is all the information that the user is allowed to edit. class UpdateProfile(forms.ModelForm): username = forms.CharField(required=False) email = forms.EmailField(required=False) first_name = forms.CharField(required=False) last_name = forms.CharField(required=False) age = forms.IntegerField(required=False) height = forms.IntegerField(required=False) weight = forms.IntegerField(required=False) class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'age', 'height', 'weight') def clean_email(self): username = self.cleaned_data.get('username') email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).exclude(username=username).count(): raise forms.ValidationError('This email address is already in use. Please supply a different email address.') return email def save(self, commit=True): # user = super(RegisterUserForm, self).save(commit=False) user.email = self.cleaned_data['email'] #This is where i am trying to save the new information. if commit: user.save() #This is where i am returning the user. return user Views def update_profile(request): args = {} if request.method == 'POST': form = UpdateProfile(request.POST, instance=request.user) form.actual_user = request.user if form.is_valid(): form.save() return HttpResponseRedirect(reverse('account:profile.html')) else: form = UpdateProfile() args['form'] = form return render(request, 'account/edit_profile.html', args)