Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django GroupBy that return a different value
I have a model that looks like this: class Company(models.Model): id = models.CharField(max_length=20) name = models.CharField(max_length=60) class Department(models.Model): id = models.CharField(max_length=20) company_id = models.CharField(max_length=20) name = models.CharField(max_length=60) I want to group the departments so that I would know in what company they are under, then return the company name: Database: Company Department id name id company_id name C001 aa D001 C001 zz C002 bb D002 C002 yy C003 cc D003 C003 xx D004 C001 uu D005 C003 vv What I want is to know the best way to set a query like this, but will return the Company name: Department.objects.filter(id=company_id).groupby(company_id) Return company_name Expected Result: D001 and D004 is under C001 wherein the name is aa D002 is under C002 wherein the name is bb D003 and D005 is under C003 wherein the name is cc -
Filtering model objects in django view
I'm currently creating a Social platform with Django. Right now, I'm developing their Profile page and want endusers to be able to see a timeline with their own posts. This is my Post model: class Post(models.Model): user = models.ForeignKey(User) posted = models.DateTimeField() content = models.CharField(max_length=150) Likes = models.IntegerField() def __str__(self): return self.user.username In the view I wanted to filter out all the posts created by the current user. But I keep getting the error: invalid literal for int() with base 10: 'Admin' This is my views: @login_required def profile_view(request): all_posts = Post.objects.get(user=User.username).order_by('-posted') return render(request, 'Dashboard/profiel.html', {'posts':all_posts}) What am I doing wrong? -
Tracking changes to all models in Django
I am working on a Django + DRF Web Application and I want to track changes to all model instances in the Database and keep a log of all changes made, namely: TABLE - Table to which record was added/modified FIELD - Field that was modified. PK_RECORD - Primary Key of the model instance that was modified. OLD_VAL - Old Value of the field. NEW_VAL - New Value of the field. CHANGED_ON - Date it was changed on. CHANGED_BY - Who changed it? REVISION_ID - Revision ID of the current Model Instance. Later on, I want the user to be able to track the changes made to the model and see which version of the instance was used for a particular action so everything can be tracked. For this purpose, I tried to understand the various packages in django for tracking database model changes, some of them listed here: django-model-audit packages I tried django-reversion, django-simple-history, django-audit-log, django-historicalrecords, but I fail to understand how and why I should use each of these packages as some of them seem like an overkill for the requirements. So, after two days of searching and reading through numerous posts about how I should be tracking … -
Recommend me reading material: Creating user-sortable/filterable django querysets
I'm somewhat new to Django and have a functioning page that I'm using with a few friends to catalog local hikes. I'm trying to put in a sortable list of the hikes -- options such as sorting by hike length, elevation, etc. (all of these are fields in my model). I'd also like to do more advanced sorting like a checkbox/option to "Exclude hikes that I've already done" and "Show hikes that other_user has done" -- preferably with the ability to select multiple filters at one time. I've read up a bit on Q objects, which has been effective at doing what I'm looking for on the backend, but am having difficulty finding any resources on creating a template/user interface that will allow this sorting to occur dynamically. I could definitely create all the custom filters myself and just make individual pages for each, but that would be a ton of work and I have to believe there's a better way, but given my inexperience with Django, I haven't been able to figure out where to start. Can you recommend me some reading material/examples on how to put something like this together? -
L.KML is not a constructor when using DJango and Leaflet
I created an html of an open street maps with a KML layer file that renders correctly here. <html lang="en-US" xmlns="http://www.w3.org/1999/xhtml"> <link rel="stylesheet" type="text/css" src="/maps/leaflet/leaflet.css" /> <link type='text/javascript' src='/js/jquery.min.js'></link> <link type='text/javascript' src='http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js'></link> <link rel="stylesheet" type="text/css" href="maps/leaflet/leaflet.css" /> <script type="text/javascript" src="maps/leaflet/leaflet.js"></script> <script type="text/javascript" src="maps/leaflet/layer/vector/KML.js"></script> Leaflet Example <p>Here's a map of the countries I've either lived in or travelled through for a month or more. <div id="map" style="height: 440px; width: 880px; border: 1px solid #AAA;"> <script> var map; // Set up the OSM layer // https: also suppported. function initmap() { var map = L.map('map',{ center: [20.0, 5.0], layers: [osmLayer,kmlLayer], minZoom: 1, zoom: 3 } ).setView([x,y], 14); } var osmLayer = L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>', subdomains: ['a','b','c'] }); var kmlLayer = new L.KML("kml", {async: true}); kmlLayer.on("loaded", function(e) { map.fitBounds(e.target.getBounds()); }); initmap(); </script> </div> I edited some of the html to a django template that I was using. However I move the file and static files into my django directory, add the relative urls, and a render template. The KML file no longer renders. When I remove the KML file from the django map.html, however the OSM tile does display correctly. I checked and there is no 404 in my … -
Run single python application in Raspberry pi and control with a web based admin panel
Here is what we trying to do with python and Raspberry pi 3. 1.Python application (without a graphical user interface ) for viewing images in HD monitor (image url's are from a server). When it runs in first time on Raspberry it will generate unique id and displayed for each device ,later it can be used in web based admin panel so user can able to modify the image url's. 2.We want run only the above python application in Raspberry pi. So it possible with python and Raspberry pi?? -
What does the object_list and bundle means in django tastpie while writing custom authorization
What does object_list and bundle means in django tastipie while writing custom authorization. What does bundle.obj.user and bundle.request.user means in below code. Thanks in advance. class UserObjectsOnlyAuthorization(Authorization): def read_list(self, object_list, bundle): # This assumes a QuerySet from ModelResource. return object_list.filter(user=bundle.request.user) def read_detail(self, object_list, bundle): # Is the requested object owned by the user? return bundle.obj.user == bundle.request.user def create_list(self, object_list, bundle): # Assuming they're auto-assigned to ``user``. return object_list def create_detail(self, object_list, bundle): return bundle.obj.user == bundle.request.user def update_list(self, object_list, bundle): allowed = [] # Since they may not all be saved, iterate over them. for obj in object_list: if obj.user == bundle.request.user: allowed.append(obj) return allowed def update_detail(self, object_list, bundle): return bundle.obj.user == bundle.request.user def delete_list(self, object_list, bundle): # Sorry user, no deletes for you! raise Unauthorized("Sorry, no deletes.") def delete_detail(self, object_list, bundle): raise Unauthorized("Sorry, no deletes.") -
How to access variable from one class to another in Django - Python
I am new to Django. In my case , I do have 2 class based views in my views.py which inherits API View in it . In my class 1 , i do have a Dictionary inside a post method class LDAPCheck(APIView): var def post(self,request): var = {} var = "some vale" Now i wanted to acces the var in another class with extends the ApiVIew class Submit(APIView): # access variable form LDAPCheck class How to do this Thanks in advance -
How to execute a python code on clicking a button on html page and show the results on the same page in Django?
I made a plain simple search page using this tutorial https://code.djangoproject.com/wiki/searchengine This works nicely and I get the search results as a list of clickable links. Now, I want that on clicking a link (one of the search result), one of my python function is run in views.py and the output is shown in the same page. For example, suppose the search result is like this, Results [result1][1] [result2][2] then upon clicking 'result1', my python code is run in the backend: def mypythoncode(a_search_result): output = a_search_result + ' processed output' return output and the returned output is shown on the same search result page as: Results [result1][1] result1 processed output [result2][2] For this, I was trying to make the search result output as buttons using this, <button id="{{ res.0 }}">{{ res.0 }}</button> I can easily make the button look like a URL hyperlink, so for my purpose this is fine. I do not know how to click on this "button" (the search result), run a python in backend, and render the results in the same search.html page. I am new to Django. I appreciate your help. -
jango home page doesnt display
I run the following tutorial Django Tutorial for Beginners - 2 - Creating a Project when I run the code bellow from urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include('music.urls')), ] It display the music page even that I am at http://localhost:8000/ When I remove the line url(r'^', include('music.urls')), Then it goes to the home page as expected Why does it happen? Shouldn't it go to the first line that fites? I run django version 1.10.5 Thanks -
How does Facebook URL regex work?
When you are in your profile the url is www.facebook.com/<username> However there are also URLs like www.facebook.com/support www.facebook.com/help Why does this not conflict with the profile pages? Why does the application not try to find the users support or help and show an error? I work in Django and I can assume that these URLs for support and help are listed BEFORE the user profile URL. However, I have projects with multiple apps and the home pages for apps like accounts and admin will also conflict with the user profile URLs as the URLs will be like 127.0.0.1:8000/admin 127.0.0.1:8000/accounts Django will try to find the usernames admin and accounts. How can I solve this problem in a way that is readable by someone else trying to understand my code? -
Assign integer value to non-integer fields Django Models
I have a website which catalogs various climbs. These climbs have difficulty grades associated with them, which are non-integer values. Users can also submit reviews of the selected climbs, and assign their own suggested difficulty grade. I want to be able to assign integer values to these difficulties, average them, and then output the result back in terms of the grading system. For example, if the rating system goes 5.1, 5.2, 5.3 ... 5.9, 5.10, 5.10a, 5.10b etc.. how do I assign an integer value to each of these fields so that I can average them later? class Climb(models.Model): GRADES = ( ('5.15', '5.15'), ('5.14', '5.14'), ... (more difficulties here) ('5.1', '5.1'), ) name = models.CharField(max_length=255, unique=True) grade = models.CharField(max_length=255, choices=GRADES) date = models.DateTimeField(auto_now_add=True) def __str__(self): return "%s %s" % (self.name, self.grade) I tried the following: class Climb(models.Model): GRADES = ( ('20', '5.15a'), ('19', '5.14d'), ('18', '5.14c'), ... ('1', '5.1'), ) But ran into issues later because I have another form where uses can select the climb, and the climb should display ideally as "Climb_name climb_grade" where climb_grade is "5.15a" or "5.9" or whatever, but instead was showing up as "20" or "10" or whatever integer I had attached to … -
Looping writes to serializer.save() in Django REST framework
I have a function in DRF where I want to tell the system to update "everybody", say I want to give everyone that logged in today a free prize and want to persist that list (I get this example is dumb, it just me trying to generalize my use case). It will query to see which users have signed in today and then I want to loop through those users to create a new activity of giving them a prize. It appears to only be storing the last value in the loop on write. time_threshold = datetime.now() - timedelta(hours=12) signed_in_list = Activity.objects.filter(created__gte=time_threshold, activity="signed in") for user in signed_in_list: serializer.save(id=user.id, activity="gets free prize") headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) I'm trying to get it so that each user ID that is returned from the "signed_in_list" would have a new activity written. -
AttributeError: 'dict' object has no attribute 'user' during overriding "social-app-auth-django" create_user
I noticed that the SAAD fails to associate an existing user with the social-auth logged in user. This is creating multiple users with the same email address. I tried to override this by commenting out in settings.py, # 'social_core.pipeline.user.create_user', I then made a view to create a user profile. I added this the pipeline, SOCIAL_AUTH_PIPELINE = ( ... 'accounts.views.save_profile', ... ) In accounts.views, def save_profile(backend, user, response, *args, **kwargs): username = "" if backend.name == "google-oauth2": email = response["emails"][0]["value"] existing_user = User.objects.get(email=email) username = existing_user.username password = existing_user.password authenticated_user = authenticate(username=username, password=password) login(request,authenticated_user) # I need request to login the user The problem here is that I need request to log in the user. The login requires request and authenticated user as parameters. Suppose I add request as a parameter, I get an AttributeError: 'dict' object has no attribute 'user'. def save_profile(request, backend, user, response, *args, **kwargs): username = "" if backend.name == "google-oauth2": email = response["emails"][0]["value"] existing_user = User.objects.get(email=email) username = existing_user.username password = existing_user.password authenticated_user = authenticate(username=username, password=password) login(request,authenticated_user) How do I login the user, having known username and password ? Traceback of the error : Traceback (most recent call last): File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 149, in get_response response … -
Ajax Jstree in Django
while searching for Ajax Jstree in Django I found this query.Tried this.but its not working on my pc.At the last author has mentioned the problem is "Seems the problem was I hadn't done both simplejson encoding whilst including the application/JSON mimetype." I did not get this point.Kindly some one help me with this. Following is the code provided by author. Thanks. result=[{ "data" : "A node", "children" : [ { "data" : "Only child", "state" : "closed" } ], "state" : "open" },"Ajax node"] response=HttpResponse(content=result,mimetype="application/json") jQuery("#demo1").jstree({ "json_data" : { "ajax" : { "url" : "/dirlist", "data" : function (n) { return { id : n.attr ? n.attr("id") : 0 }; }, error: function(e){alert(e);} } }, "plugins" : [ "themes","json_data"] }); -
'sudo: aptitude: command not found' when installing python package in terminal
I'm trying to install this python package called 'ffvideo' I'm on Mac so my 2 installation steps are, as per the instructions: In Ubuntu you can install the above using the following commands:: sudo aptitude install python-dev cython libavcodec-dev libavformat-dev libswscale-dev pip install git+https://github.com/radek-senfeld/ffvideo.git#egg=ffvideo When I execute the first line in my project (django) terminal, I get a sudo: aptitude: command not found error. Any idea what the problem is? I also have Macports installed and apparently that's supposed to help make installing packages easier, so maybe I can do something with that? -
How to paginate search results in Django 1.7?
The code I have is a pager that works for me very well, but now I would like to add the option to search but I do not know how to integrate it with my code, I appreciate all the help provided. This is my url: url(r'negocios/(?P<pagina>\d+)/$', NegociosView.as_view(),name='vista_negocios'), This is my view: class NegociosView(ListView): def get(self, request, *args, **kwargs): pagina = kwargs['pagina'] lista_negocios = Perfil.objects.all() paginator = Paginator(lista_negocios,2) try: page = int(pagina) except: page = 1 try: nego = paginator.page(page) except(EmptyPage,InvalidPage): nego = paginator.page(paginator.num_pages) ctx = {'negocios':nego} return render_to_response('home/negocios.html',ctx,context_instance=RequestContext(request)) This is my template code: This is the view from the browser: -
Django app with Rails API
How can you get a JSON object from an API and then display it nicely in the template? I've been beating my head against this one for awhile. I have some experience with Django apps, but I've never built an API-only app before so the requests and json libraries are new to me. The API is built with Rails. Stumbling through documentation, I have been able to authenticate and get the data. Now I'm just struggling with how to display it in the template. Views.py def accounts(request): # To-Do: Better check for user logged with API if not request.session.get('api_token'): return HttpResponseRedirect('/') token = 'Token token=' + request.session.get('api_token') path = 'https://myrailsapi.heroku.com/accounts' req = requests.get(path, headers={'Authorization': token}) accounts = req.json() print(accounts) context = {'accounts': accounts} return render(request, 'accounts.html', context) accounts (the data) looks like this: [{'created_at': None, 'account_username': 'woof', 'id': 12, 'updated_at': None, 'account_password': 'woof', 'user_id': 3, 'account_type': 'credit', 'institution_name': 'test'}, {'created_at': None, 'account_username': 'ge', 'id': 22, 'updated_at': None, 'account_password': 'ge', 'user_id': 3, 'account_type': 'checking', 'institution_name': 'test2'}] accounts.html {% for account in accounts %} <div class="card small> <div class="card-content white-text"> <span class="card-title no_margin"> {{ account.account_name }} </span> <span class="card_subtitle"> {{ account.account_type }} <span class="right">Balance</span> </span> </div> {% endfor %} How can I … -
How to create a django app that lets you type in small python programs, execute the code and show the result?
The app should enable the user to type in small python programs.When click Run the code is executed and output is delivered to the user -
How to connect django with a C library, to realise an public encryption operation on a webpage
I am studying a C library named libfenc, a functional encryption library for Attribute-Based Encryption. Now I want to combine it with a Django web framework, to realize an encryption operation for online documents in a website. The libfenc library has been installed successfully on my Ubuntu computer. But I don't know how to connect it with Django, which file is useful for my target? Can anyone give me some suggestion and hints? Actually, my development experience is not too much, and have no idea about it for several days. You can view the source link:enter link description here -
Is it possible to attach a pdf generated by a view to an email message in django?
I'm using this third party app for pdf generation. In my view I've this code for creating the Pdf: class artwork_catalog(PDFTemplateView): template_name = "someapp/sometemplate.html" def get_context_data(self, **kwargs): return super(artwork_catalog, self).get_context_data( pagesize="A4", title="My Title" + datetime.datetime.now().strftime('%m/%Y'), artworks=ArtWork.objects.filter(public=True).order_by('year'), **kwargs ) My Url for this is: url(r'^order-catalog/$', views.order_catalog, name="order_catalog"), So I can access my Pdf at localhost:8000/order-catalog. Now I want to send this Pdf as attachment per email. I created a view but I can't bring it to work: def order_catalog(request): if request.method == 'POST': form = OrderCatalogForm(request.POST) if form.is_valid(): subject = 'Test' from_email = 'Test@Test.com' message = 'TESTTESTTESTTEST' recipient = form.cleaned_data['email'] pdf = artwork_catalog try: mail = EmailMessage(subject, message, from_email, [recipient]) mail.attach("MyPdf.pdf", pdf, "application/pdf") mail.send() except: return HttpResponse('Error') return redirect('/somewhere/') else: form = OrderCatalogForm() return render(request, 'someapp/order_catalog.html', {'form': form}) Any hints? best regards Manuel -
Pass queryset data to another query django
I have the following model. I am trying to select all from UserClasses where a specific class_id is specified. I then want to get the User data for each of the results class UserClasses(models.Model): class_id = models.ForeignKey(Class) user = models.ForeignKey(User) This is my django view where I am trying to pull all User objects: users = UserClasses.objects.filter(class_id=data['class_id']) user_details = User.objects.filter(#get users.id from userclasses and compare here) How can I pass the results from one queryset into another? -
Django (using TokenAuthentication): "non_field_errors": "Unable to log in with provided credentials?
I'm using httpie to test my custom authentication. I did create a custom auth object using AbstractUser. Using TokenAuthentication, I followed the docs and added my custom TokenAuthentication in my REST_FRAMEWORK settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'regis.models.CustomAuthentication', ) } And added rest_framework.authtoken in my installed apps. My AUTHENTICATION_BACKEND is as follows: AUTHENTICATION_BACKENDS = [ 'regis.models.CustomAuthentication' ] And here is my custom authentication class: class CustomAuthentication(authentication.TokenAuthentication): def authenticate(self, request): username = request.META.get('X_USERNAME') print(username) user_model = get_user_model() if not username: return None try: user = user_model.objects.get(username=username) except User.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') return (user, None) I'm pretty much following the DRF docs (http://www.django-rest-framework.org/api-guide/authentication/#custom-authentication). If there's any additional info needed to solve this, please let me know and I'll update. Any help on what I'm missing would be great. To add: Just out of curiosity, do I need to make a custom authentication system if I have a custom user? -
Custom Django email script
I'm new to Django so don't be mad if this question might seem stupid. I would like to add some functionality to my django web page. I need to added script that would send newest add feed for registered users. Basically I would like to activate script when admin saves new post, but I don't know how modify admin page. Maybe there is other solutions for this kind of task? -
Django - Generating random, unique slug field for each model object
I have a Model called ExampleModel in Django, and want each of the model objects to be uniquely identified. Though, I don't want the ID of the object visible to the user in the URL; and so for this reason I want the objects slug to be a unique, randomly generated integer with 8 digits which will go in the views URL. This is different from other questions I've seen because this means not producing a slug string that is based on the model object's name//content itself. Models.py: class ExampleModel(models.Model): user = models.ForeignKey(UserModel, related_name='examplemodel', on_delete=models.CASCADE, null=True) title = models.CharField(max_length=50, verbose_name='Title') slug = models.SlugField(unique=True, blank=True, null=True) Currently the value of the slug is null so I don't have to set a default slug for all of the current ExampleModel objects. This is quite vague understandably, however I haven't been able to find any guides/tutorials that may work for my exact situation. Thanks for any help/guidance provided