Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get latest value of a field on a related model in Django?
I have the following models: class Timestamped(models.Model): created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) class Meta: abstract = True class Thread(Timestamped): user1 = models.ForeignKey(User, related_name='user1') user2 = models.ForeignKey(User, related_name='user2') class Message(Timestamped): thread = models.ForeignKey(Thread) text = models.CharField(max_length=255) sender = models.ForeignKey(User) I have a QuerySet to get all threads, but I also want to display the latest message for each thread while I loop over them. I have come up with the following to show the latest Timestamp for the message. threads = Thread.objects.filter(Q(user1=request.user) | Q(user2=request.user))\ .annotate(latest_msg=Max('message__modified')).order_by('-latest_msg') How can I show the message text? -
django-cors-headers settings.py django app not working even though I've added all the requirements to settings.py
So, I'm using django-cors-headers with Rest Framework with Django 1.11.x, and I've pretty much followed the general advice, and yet, I'm still getting "x has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource." As you can see, I've added 'corsheaders' to INSTALLED_APPS and 'corsheaders.middleware.CorsMiddleware' to Middleware, and I've set CORS_ORIGIN_ALLOW_ALL to true and CORS_ALLOW_CREDENTIALS to true, too. I've even included a whitelist option, though it's my understanding that, if CORS_ORIGIN_ALLOW_ALL is set to true, the whitelist isn't needed. I've also pip3 installed django-cors-headers. What is the deal??? BTW, I've read the README on the django-cors-headers repo. I want to know why it's not working. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'books.apps.BooksConfig', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = ( 'localhost:5555' ) And my js file that's accessing from localhost:5555 is: var request = $.ajax({ type: 'GET', url: url, dataType: 'json', xhrFields: { withCredentials: true }}); -
How to activate users manually
Django 1.11.2 django-registration-redux==1.6 I'm building an intranet website. And I'd like to control myself whether users are active or not. In Django admin there is such a possibility. But "Active" attribute is set to True automatically when a newly registered user confirms his/her email. In other words what I'd like to do: 1) Let users register and reset passwords. 2) Admin of the site assigns the new user to a group. Users with the minimum permissions can only view. Special permissions allow edit, delete etc. But the user must be unable even to view anything without approval by the admin. Now I'm planning to organize can_view permission for every model. The two above conditions will be performed by assigning the user to a group. Well, this seems to be rather cumbersome. That "Active" attribute in admin is much more elegant. But "Active" is automatically set to True when the user confirms his/her email. Could you give me a piece of advice here? -
Facebook Profile Photo use in Django
I have a django project that allows login/signup through Facebook only. My app requests for profile photo too (by default). In the extended User Model, I have a function to check if the profile photo exists in the project dir, then return that url or else fetch the photo from Facebook and download it. Here is the function and how I use it in django template. def get_photo_url(self): username = self.user.username path = os.path.join(settings.STATICFILES_DIRS[ 0], "img", username) + '.jpg' if os.path.isfile(path): return '/static/img/{0}.jpg'.format(username) else: facebook_data = self.user.social_auth.filter( provider='facebook').first() if facebook_data: fb_id = facebook_data.uid url = 'http://graph.facebook.com/' + \ str(fb_id) + '/picture?type=large' try: f = urllib.request.urlopen(url) print("Downloading Profile Photo for ", url, " to ", path) local_file = open(path, "wb") local_file.write(f.read()) local_file.close() except HTTPError as e: print("HTTP Error:", e.code, url) except URLError as e: print("URL Error:", e.reason, url) if os.path.isfile(path): return '/static/img/{0}.jpg'.format(username) else: print("Unsuccessful Attempt to download file.") self.get_photo_url() else: print("----------------------\n") print(" You programmed WRONG \n") print("----------------------") return '/static/img/default.png' Django Template: <img src="{{ article.author.profile.get_photo_url }}" class="img-thumbnail" width="70px" height="70px"> Article Model is defined in another app of same project with author associated as user. Why does the photo not show? The snip is here -
What Django does when there is no terminal to print to?
Sometimes I forget to remove print statements that I add to debug my Django codes. So they go to production code and are supposed to print something in the terminal, but there is no terminal in production to print at. I'm wondering what happens in such scenarios? Does it have any impact on the code's performance? -
Django Test Change Datetime Now
I have a Django test where I need to mock datetime.now(), because the view that it tests uses datetime.now() I'm using Michael Foord's mock library, version 1.0.1. I'm looking for a solution without using other libraries such as freezegun. Most examples like this and this import datetime and override it, but I'm importing datetime.datetime and im trying to override it, and for some reason this doesn't work. I'm trying to do something like this: class FixedDate(datetime): @classmethod def now(cls): return cls(2010, 1, 1) datetime = FixedDate @patch(datetime, FixedDate) def testToday(self): print 'fixed_today', datetime.now() Nb. I saw also this example, but it won't work for me, cause I dont have one function that returns the datetime, but my view uses datetime.now() -
Correct way to assign unique group to users Django
Thanks for reading my question. I read about it on the next articles, trying to find information about my doubt: https://baxeico.wordpress.com/2014/09/10/group-combo-box-django-user-profile-form/ https://micropyramid.com/blog/django-permissions-and-groups/ https://www.webforefront.com/django/setupdjangousers.html My premise in my system: an user only can be in an unique group. My question is about my premise, how is the correct way to assign a unique group to an user from my app? Thanks a lot! -
Django index lookup with a forloop.counter0
I have this for loop that creates a Django template element, which stores the information of 1 row of the query table. `{% for user in ml_users %} `<div class="container"> ......... <p><a id="event" href="#"><strong>Name-</strong> {{ user.name }} </a></p> ... </div> Now for some reason , that i will not go into, i need to print out {{user.name.0}} on the first iteration, {{user.name.1}} on the second iteration and so on ... Is there a way to somehow put a forloop counter where the index is? It should be something like: {{user.name.forloop.counter0}} -
Use Django admin change_list in an app
I would like to have the admin change_list in my app, like a generic filtered list view. For example, I have an app "cars" and I would like a url http://www.example.com/cars/mycars/ that has a list of all the cars (that can be filtered and sorted by the column headers). I am able to create a custom admin site and customize the admin change_list, but it ends up on a link like http://www.example.com/my_admin/cars Is there a simple way use the nice change_list view and template of the admin site to create a generic sortable, filterable list in an app without having another link to the admin? If now, any recommendations on how to go about this? Thanks! T -
Django validate_unique returns 500 on error
When trying to validate unique of two fields, which one of them is a field of a foreign key in the model, I used 'validate_unique'. According to the documentation it should return 400. I get 500. This is how I use it: in the models.py (model is Item and foreign is Spec. Tested fields are 'identifier' and 'container_id): def validate_unique(self, exclude=None): u_item = Item.objects.filter(identifier=self.identifier) if u_item.filter(spec__container=self.spec.container).exists(): uu_item = Item.objects.get(identifier=self.identifier) print("already Exists") print("item identifier: ", uu_item.identifier) raise ValidationError('Identifier must be unique per Container') def save(self, *args, **kwargs): self.validate_unique() super(Item, self).save(*args, **kwargs) As mentioned, when testing two items with same identifier and spec.container_id I do get an error, but the status code is 500 instead of 400. -
How to get data from two different django apps into one single page
I have two django apps, adsense and blog How do I get data from these both and show it in a single page index.html This is the model.py for adsense from __future__ import unicode_literals from django.db import models from ckeditor.fields import RichTextField class Adsense(models.Model): ads = RichTextField() def __unicode__(self): return self.ads This is the model.py for blog app class Entry(models.Model): title = models.CharField(max_length=200) post_type = models.CharField(max_length=50,choices= ( ('Mobiles', 'Mobiles'), ('Laptops', 'Laptops'), ('Laptop_Accesories', 'Laptop_Accesories'), ('Tablets', 'Tablets'), ('Cameras', 'Cameras'), ('Others', 'Others'), ), default='Others') author = models.CharField(max_length=30, blank=False) description = RichTextField() body = RichTextUploadingField() slug = models.SlugField(max_length = 200, unique = True) publish = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now_add=True) objects = EntryQueryset.as_manager() def __str__(self): return self.title def get_absolute_url(self): return reverse("entry_detail", kwargs={"slug": self.slug}) class Meta: verbose_name = "Blog Entry" verbose_name_plural = "Blog Entries" ordering = ["-created"] This is admin.py for adsense class AdAdmin(admin.ModelAdmin): class Meta: model = Adsense admin.site.register(Adsense, AdAdmin) This is admin.py for **blog class EntryAdmin(admin.ModelAdmin): list_display=("title","created") prepopulated_fields = {"slug" : ("title",)} admin.site.register(models.Entry, EntryAdmin) This is the view.py for blog class BlogIndex(generic.ListView): queryset = models.Entry.objects.published() template_name = "index.html" paginate_by = 5 This is the view.py for adsense def Ads(generic.ListView): context=locals() template = "index.html" render(request,template,context) This is urls.py from adsense import views … -
How to obtain the field value when m2m signal triggered with this code
I know how to trigger a function when a m2m field is either added or deleted. However I do not know how get the field value of the changed object.This is explained below This is my main model class modelPatient(models.Model): student = models.ManyToManyField(modelStudent,null=True,default=None,blank=True) patient_name = models.CharField(max_length=128, unique=False) Now this is the modelStudent attached to above via m2m class modelStudent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,null=True, blank=True) first_name = models.CharField(max_length=128, unique=False) Now to detect changes in modelPatient I am using the m2m signal like this m2m_changed.connect(NewCaseAssigned, sender=modelPatient.student.through,dispatch_uid="NewCaseAssigned") This is the function that gets triggered def NewCaseAssigned(sender, **kwargs): if kwargs['action'] not in ('post_add', 'post_clear', 'post_remove'): return if kwargs['action'] in "post_add": print "Something got added" rcv = kwargs["receivers"] print "Something got removed" if kwargs['action'] in "post_remove": rcv = kwargs["receivers"] print "Something got removed" Now i know when something is removed from m2m relation post_add is called and when something gets removed post_remove is called. My question is how do I get the model that is removed in this case how do I get access to student field modelStudent that got added or removed to modelPatient -
Refreshing Facebook open graph cache each time the url of the page is shared
I am creating a small game where the user types the URL of my page in the comment box, and a random Game of Thrones character with an image is generated and displays as the preview. But the problem is that facebook caches the preview and shows same character everytime. I found out that I need to send a GET request to https://graph.facebook.com/?id=https://www.cpclips.com/got&scrape=true&method=post to refresh each time. But when I make the call from my Django backend, it creates an infinite loop. (MyServer -> OG endpoint -> Myserver -> OG endpoint...) How do I work around that? Is there any method to disable OG cache for my page? Here is my Django View - def game_of_thrones(request): urllib.request.urlopen("https://graph.facebook.com/?id=http%3A%2F%2Fcpclips.com%2Fgot&scrape=true&method=post").read() name = got_names[random.randint(0,len(got_names)-1)] image = "https://www.cpclips.com/static/images/games/got/"+name.lower().replace(" ","-")+".jpg" return render(request, "got_characters.html",{"title":"You are "+name, "image":image,"name":name}) -
Django and mongoDB - Create index/search page/website
I m looking for a tutorial to create something like this with Django and mongoDB: Specifications: 1 - using mongodb and Django 2 - I can search by typing any information 3 - I can filter results 4 - I can sort results (by name...) I have searched in google but I have not found any tutorial! Thank You -
Unable to connect to WSGI daemon process mod_wsgi in Centos7 with Cpanel/WHM
I'm with a problem do deploy django/python in my VPS with Centos7.3 and WHM. All are working, execept a socket problem with mod_wsgi. [Sun Jun 25 00:37:03.254774 2017] [wsgi:error] [pid 29756] (13)Permission denied: [client 66.249.83.220:35523] mod_wsgi (pid=29756): Unable to connect to WSGI daemon process 'brunamaiahair.com.br' on '/var/run/apache2/wsgi.721.27.1.sock' as user with uid=1004. I read some post saying to put WSGISocketPrefix out apache directive, so I edit httpd.conf and put WSGISocketPrefix /var/run/apache2/wsgi But I'm receiving the same error. Log when rebuild httpd.conf and restart apachectl [Sat Jun 24 21:10:56.084269 2017] [mpm_prefork:notice] [pid 721] AH00163: Apache/2.4.25 (cPanel) OpenSSL/1.0.2k mod_bwlimited/1.4 mod_wsgi/4.5.7 Python/2.7 configured -- resuming normal operations My custom virtualhost WSGIDaemonProcess brunamaiahair.com.br socket-user=#1004 python-path=/home/bmhair/public_html/django/framework:/home/bmhair/public_html/django/denv/lib/python2.7/site-packages WSGIProcessGroup brunamaiahair.com.br WSGIScriptAlias / /home/bmhair/public_html/django/framework/framework/wsgi.py -
{{row.column."i need a forloopcounter here"}}
so i have the following problem. Im new to both Django and Python and cant figure this out. I have a table with some array_agg columns . And a {% for index in array %} to create Parts of a django template. The Table is similar to this: Person_ID | Possesions 1 | {phone, car, watch} now when i go {{table_name.Possesions}} it gives me back all the indexes instead of just one. i need it to go {{table_name.Possesions.0}} on the first iteration {{table_name.Possesions.1}} and so on. Is it possible to do with a forloop counter ? like {{table.Possesions.forloopcounter0 }} i mean. How does the syntax go here ? I need to get 3 elements: Posession: phone Posession: car Posession: watch What i get now is those 3 elements: Possesion: phone, car , watch Possesion: phone, car , watch Possesion: phone, car , watch -
redirect django heroku app
I have a heroku app using django at example.herokuapp.com. I also have a custom domain that points to this heroku app at example.com How can I make it so that any time someone goes to example.herokuapp.com, it automatically redirects to my custom domain at example.com? I essentially only want users to see the url example.com even if they type in example.herokuapp.com Keep in mind that this is a django app. I could redirect every route to my custom domain, but I am wondering if there is any easier/better way to do this. -
Saving extended user model data from POST method API
I don't have any forms to get input from user only by using POSTMAN i have tested this. I extend my default user model by OneToOneField class Profile(models.Model): user = models.OneToOneField(User, related_name='profile') phone = models.CharField(max_length=15) address = models.CharField(max_length=250) and i implemented below method def create_profile(sender, instance, **kwargs): if kwargs["created"]: user_profile = Profile(user=instance) instance.profile.save() post_save.connect(create_profile, sender=User) so it creates a record for profile while any record gets inserted in user model. For example If i have made any API call like localhost:8000/signup with POST method data like username: abc, password: passkey123, phone: 9876543210 it save username and password in user model respective profile model created with user reference failed to update my phone number field. I don't have any forms to get datas. Below is my view that routed from /signup @api_view(['post']) @authentication_classes([]) @permission_classes([]) def signup(request): username = request.data.get('username') password = request.data.get('password') email = request.data.get('email') phone = request.data.get('phone') user = User.objects.create_user(username=username, password=password, email=email) if not user: return Response({'message': 'Failed'}, status=HTTP_400_BAD_REQUEST) return Response({'message': 'success'}) Do i need to implement any special signal to pass the input data like phone and address to profile model or extra lines i have to add. Thanks in advance. -
django cron_tab is not sending email why?
I am trying to play around django cron_tab, I also know there's one called django cron but cron_tab is recommended by lots people instead. I have it installed (I believe it is installed properly as when I run commands there are no errors) But it is not working though. (Does it have to do with running it locally that's why it's not working?) I have followed all the steps here to install cron_tab https://pypi.python.org/pypi/django-crontab I did install it via pip, I put the it into INSTALLED_APPS also added in my settings CRONJOBS = [ ('1 * * * *', 'main.extras.cron_job.my_scheduled_job') ] I have a folder named main under it is extras directory and under extras directory I have a file named cron_job.py cron_job.py def my_scheduled_job(): from django.core.mail import send_mail print('######################################') // this is added because I want to see if terminal / console would print this out as I would know at least the function did at least run but never seen this got printed send_mail( 'cron job test', 'Here is the message.', 'from@hello.com', // using real email locally ['to@hello.com'], // using real email locally fail_silently=False, ) I believe the setting for my cron is run the following function every … -
Django Project isn't working on production server
This company hired me as a contract to make a Django app for a website. I made the app and it runs using ./manage.py but when I put it in the public_html directory it won't load on the website. My wsgi.py is just the default The folder tree looks like public_html | |__Django project | | | |__my_site | | | |__my_app | |__Other stuff -
djangofilterbackend query params and un populated query param options
I want to create viewset in django which will take a url with query params and filter upon the query params. My biggest problem with documentation is it doesn't idiot proof them. Take this example from the django rest framework docs http://www.django-rest-framework.org/api-guide/filtering/ class ProductList(generics.ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = (filters.DjangoFilterBackend,) filter_fields = ('category', 'in_stock') which will work with the below url: http://example.com/api/products?category=clothing&in_stock=True but what if I have a url without the category option set for example. Will this code break? Or is it smart enough to know when a query param filter isn't populated and ignore it? If it isn't then I would imagine I have to create a filter like this: ass PurchaseList(generics.ListAPIView): serializer_class = PurchaseSerializer def get_queryset(self): """ Optionally restricts the returned purchases to a given user, by filtering against a `username` query parameter in the URL. """ queryset = Purchase.objects.all() username = self.request.query_params.get('username', None) if username is not None: queryset = queryset.filter(purchaser__username=username) return queryset Which ok fine, but does that mean that djangofilterbackend library is only good for use cases where filters are guarnteed? If not can someone please provide me an example, since the docs don't realize im stupid as hell. Thank you -
Displaying forms SelectField 'options'
How to display selectField options in html, and toggle the options when clicked. so basically remove the selectField drop down bar and just display all the options out. {% for x in form_select.select %} <option value="{{ x }}"> </option> {% endfor %} -
Unable to retrieve from Django database in deployed Heroku App
Hi guys I'm really stuck on something developing my website with Django/Heroku. (And also using mptt) I get the error: (again2 is the name of a table) DoesNotExist: again2 matching query does not exist. I get no errors when I run locally, but I get a 500 error when I deploy to Heroku. So something has gone wrong in terms of communication between Heroku and my Django database. But I have no idea what to do to fix this? A list of things I have done (looking at other people's questions): python manage.py makemigrations followed by git commit, pushing to heroku and heroku run manage.py migrate i have imported ''django.contrib.sites' into my installed apps, i have my herokuapp url saved as a site object i have an updated requirements.txt heroku appears to have 'data' and tables in the database it created for the app (heroku postgres) Below is what I would have in my views: def topic_detail(request, x): text1 = str(again2.objects.get(pk='Top').get_children()) return render(request, 'things/topic_detail.html', { 'text1': text1, }) In local this would work, on deployment it would give the error, if i replaced text1 to just be again2.objects.all() it would show the contents on local but nothing on deployment to … -
How to debug openshift v2
I am getting Internal Server Error ``` The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator, root@localhost and inform them of the time the error occurred, and anything you might have done that may have caused the error. More information about this error may be available in the server error log. Apache/2.2.15 (Red Hat) Server at www.abettingtips.com Port 80 ``` I have a django 1.8.8 on python 2.7 app. Looking at logs in ~/app-root/logs, no info in cron_minutely.log or haproxy logs. I also removed .htaccess from app/wsgi/ folder. Lately I have set up env variables. (rhc env set BLA=bla -a app). I have also read that env should be in quotes, so I tried rhc env set BLA="bla" -a app. No luck. I probably should just get rid of openshift and move it to somewhere else. But it would take me too long to setup docker, vps for docker, postgres instance and crons on a small app. So please, do you have an idea how to find out where is the problem? -
how to run django-simple-blog?
How to run Django-simple-blog? I tried to install django-simple-blog but could not find the manage.py file to run it. Can I get a solution or another simple blog?