Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django - use cloudinary only for image manipulation and save the image to local project folder?
is there an option to do some image cropping in cloudinary and save it in local project folder. transformations like detect face and save as profile image. is there any other plugins for the same? -
Can't get the form to comment on posts
Ok this will be my last try, why I can't get the FormComment to comment a post in detail.html ? I'm getting nervous about this.. def DetailView(request, pk): if request.user.is_authenticated(): base_template_name = 'blog/base.html' else: base_template_name = 'blog/visitor.html' post = get_object_or_404(Post, pk=pk) form = CommentForm(request.POST or None) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('blog:DetailView') return render(request,'blog/detail.html',{'post':post,'from':form ,'base_template_name':base_template_name}) form.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('textc',) And here the detail.html ( part of it) {% if post.comment_set.all %} <h2>Comments</h2> <div class="comments"> {% for comment in post.comment_set.all %} <span> <a href="">{{ comment.user }}</a> said on {{ comment.created_on }} </span> <p> {{ comment.textc }} </p> {% endfor %} </div> {% endif %} <h4>Leave a Comment:</h4> <form action="" method="POST"> {% csrf_token %} <table> {{ form.as_p }} </table> <input type="submit" name="submit" value="Submit" /> </form> </div> the CommentModel: class Comment(models.Model): post = models.ForeignKey('blog.Post', null=True,related_name='comments') user = models.ForeignKey(User, max_length=200, blank=True, null=True) textc = models.TextField(null=True,max_length=200) created_date = models.DateTimeField(default=timezone.now) -
Django TimeZone issue with postgres
I am trying to save Date-Time in postgres table but It got changed after insertion. My Django Model and Insertion Query: class Notifications(models.Model): message = models.CharField(max_length=150, null=True, blank=True, default='') start_time = models.DateTimeField(blank=True,default=datetime.now) @classmethod def create_or_update(cls): try: entity = cls() entity.message = 'message' import dateutil entity.start_time = dateutil.parser.parse('04/18/2017 1:39 AM') entity.save() return 1 except Exception as ex: return 0 def __str__(self): return self.message class Meta: db_table = u'app_notifications' permissions = () SQL Output: start_time: 2017-04-17 18:39:00-07 Actual Input: 04/18/2017 1:39 AM I have tried to convert the time but same result: def to_aware_datetime(datetime_str): try: ret = parse_datetime(datetime_str) if not is_aware(ret): ret = make_aware(ret) return ret.astimezone(pytz.utc) except Exception as ex: return '' Output: to_aware_datetime('2017-04-18 01:18') --> 2017-04-17 18:18:00-07 How can I resolve the issue? Thanks -
Browser ignoring set-cookie
I am working on Angular 2 / Django Project. Each project is running on a specific port. When making a post to /login route, server returns seesionid and csrftoken cookies. Javascript code can't access both returned cookies and they don't apear on chrome developer tool: Response: Access-Control-Allow-Credentials:true Access-Control-Allow-Origin:http://localhost Allow:POST, OPTIONS Date:Tue, 04 Apr 2017 14:47:31 GMT Server:WSGIServer/0.2 CPython/3.5.2 Set-Cookie:csrftoken=ITzlkMrTtSYcmlNQANFvxQHlZ829qXe0tEblA3KOaKY6iRRB7Y3pYlvdcZNSpDcv; expires=Tue, 03-Apr-2018 14:47:31 GMT; Max-Age=31449600; Path=/ Set-Cookie:sessionid=d5v1mri12bniyvyqqt55ar8mfl9mr2jk; expires=Tue, 18-Apr-2017 14:47:31 GMT; HttpOnly; Max-Age=1209600; Path=/ Vary:Accept, Cookie, Origin X-Frame-Options:SAMEORIGIN -
Badly Formed hexadecimal uuid string error in Django fixture
I have been doing this project I want to filter all_products by the category id name but when I do it, it gives me the badly formed hexadecimal UUID string error. This is the models.py from django.db import models import uuid # Create your models here. class Category(models.Model): category = models.CharField(max_length=100) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.category class Product(models.Model): title = models.CharField(max_length=100) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) image = models.FileField(default=None) desc = models.TextField(default="Random") price = models.DecimalField(max_digits=10, decimal_places=2) vnos = models.CharField(max_length=30) quantity = models.BigIntegerField() category = models.ForeignKey(Category, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) times_bought = models.BigIntegerField(default=0) def __str__(self): return self.title and views.py def category_detail(request, category_id): try: current_category = Category.objects.get(pk=category_id) except Product.DoesNotExist: raise Http404("Album does not exist.") current_category_name = current_category.category template = loader.get_template('categories/details.html') all_products = Product.objects.all() products_by_category = Product.objects.all().filter(category=str(current_category_name)) footer = loader.get_template('main/footer.html') head = loader. get_template('main/head.html') nav = loader.get_template('main/nav.html') all_categories = Category.objects.all() paginator = Paginator(all_products, 6) page = request.GET.get('page') try: all_products = paginator.page(page) except PageNotAnInteger: all_products = paginator.page(1) except EmptyPage: all_products = paginator.page(paginator.num_pages) context = { 'all_products': all_products, 'all_categories': all_categories, 'footer': footer, 'head': head, 'nav': nav, 'products_by_category': products_by_category } return HttpResponse(template.render(context, request)) I have tried different methods but nothing really helps. I … -
django ManifestStaticFilesStorage nginx setting
here is my question: I used to provide staticfile by nginx like location /static { alias /path/staticfile; } but after I used ManifestStaticFilesStorage in my django's settings.py, browser can't find filename name like xxxx.{md5hash}.css, it get 404. -
Heroku web dyno running Django app not releasing memory
I'm struggling with a memory issue on Heroku when running a Django application (with gunicorn). I have the following code that takes a user-uploaded image, removes all EXIF data, and returns the image ready for it to be uploaded to S3. This is used both as a form data cleaner and when reading base64 data into memory. def sanitise_image(img): # img is InMemoryUploadedFile try: image = Image.open(img) except IOError: return None # Move all pixel data into a new PIL image data = list(image.getdata()) image_without_exif = Image.new(image.mode, image.size) image_without_exif.putdata(data) # Create new file with image_without_exif instead of input image. thumb_io = StringIO.StringIO() image_without_exif.save(thumb_io, format=image.format) io_len = thumb_io.len thumb_file = InMemoryUploadedFile(thumb_io, None, strip_tags(img.name), img.content_type, io_len, None) # DEL AND CLOSE EVERYTHING thumb_file.seek(0) img.close() del img thumb_io.close() image_without_exif.close() del image_without_exif image.close() del image return thumb_file I basically take an InMemoryUploadedFile and return a new one with just the pixel data. del and closes may be redundant, but they represent my attempt to fix the situation where Heroku memory usage keeps growing and is not released every time this function terminates, even remaining overnight: Running this on localhost with Guppy and following the tutorial, there are no remaining InMemoryUploadedFiles nor StringIOs nor PIL … -
Is it possible to pass grouped query parameters via Django's {% url %} template tag?
Im currently querying a model with this query to get the count of item and i would like to generate a redirect link to a list view showing the item that would be in the count requests.filter(Q(state__iexact='render') & Q(entered_render_at__date__gte=last_week) & (Q(expires_at__date__gte=last_week) | Q(denied_at_state__iexact='render'))).count() I would like to generate a {% url %}. Is this possible ? I can't find anything on it. -
Django writing generic update view restricted to certain user
I am building a small blog using django.I want to build a function that allow post author to delete and update their own posts. Then I find django has LoginMixin for generic view,but it only block those who don't login. My article Model is like below class Article(models.Model): author = models.ForeignKey(User) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=50) context = models.TextField() genre_choice = (('O','Others'),('P','Programming'),('L','Learning'),('E','Entertainment')) genre = models.CharField(max_length=2,choices=genre_choice,default='O') def __str__(self): return "{} - {}".format(self.title,self.author) def get_absolute_url(self): return reverse("article-detail",args=str(self.id)) This is the generic article detail view. class ArticleDetail(DetailView): model = Article I firstly want to add something like this in the detail template: {% if article.author == user.username%} <!-- Some a tag that directs to the update view --> {% endif %} Then I realize that this just hides the a tag ,it can't stop other users to touch the update url simply change the url. Is there anyway in django can restricted the update and delete permissions to the original user by simply using generic view?Even if they directly enter the update url,they will be rejected. -
Misago's (Django forum engine) JavaScript localization not working
I tried to localize Misago forum. Misago is Python and Django application. http://misago.readthedocs.io/en/latest/setup_maintenance.html I added new locale with makemessages. The localization of the templates works. I changed django.po file: /usr/local/lib/python2.7/dist-packages/misago/locale/ru/LC_MESSAGES/django.po The localization of Javascript files doesn't work. I change this file. /usr/local/lib/python2.7/dist-packages/misago/locale/ru/LC_MESSAGES/djangojs.po I made 'django-admin compilemessages' and I see processing file django.po in /usr/local/lib/python2.7/dist-packages/misago/locale/ru/LC_MESSAGES processing file djangojs.po in /usr/local/lib/python2.7/dist-packages/misago/locale/ru/LC_MESSAGES processing file django.po in /usr/local/lib/python2.7/dist-packages/misago/locale/en/LC_MESSAGES processing file djangojs.po in /usr/local/lib/python2.7/dist-packages/misago/locale/en/LC_MESSAGES When I reload the forum page I see my changes in during one second, but after all becomes the same as before. This means ru/LC_MESSAGES/djangojs.po loads, but then something reloads it. Web browser developer console shows that forum's .js files were reloaded (Status 200, not 304). Please, tell me why this happened? What did I lost? -
Why can't this Url resolve/why doesn't this redirect work? (Django)
So, it involves views where users sign up for accounts. Here's my view file for account sign up: @transaction.atomiq def profile_new(request): if request.method == "POST": user_form = UserForm(request.POST) profile_form = ProfileForm(request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save(commit=False) user.username = user.email profile = profile_form.save(commit=False) profile.user_id = user.pk profile.save() user.save() return redirect('profile_detail', pk=user.pk) else: messages.error(request, ('Please correct the error below.')) else: user_form = UserForm() profile_form = ProfileForm() return render(request, 'accounts/update.html', { 'user_form': user_form, 'profile_form': profile_form }) Which basically mostly works, except for the fact that most of the profile data ends up being null in the database, except for the user_id which was explicitly stated. I want to save the onetoone relationship both at once, so I can access all that User data later when I redirect to the users page. from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) avatar = models.ImageField(upload_to = 'avatars/', default = 'avatars/default.jpg') location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() Heres my profile model, which should automatically save when I save … -
Running Django in Pycharm 17.1
I'm trying out the new Pycharm 17.1 Pro edition. I'm trying to run a Django 1.7 project. At the git-bash command line in Win 7, I can run it using: $ python manage.py runserver I can't figure out how to configure pycharm 1.7 to do this though. The screenshot of my setup is as above. -
Sending multiple parameters in url as GET request in django accpets only first parameter
I am sending a GET request using the following URL: http://localhost:8000/abcd/efgh?param1="hello"&param2="hi" and in urls.py file: url(r'^abcd/efgh', views.monitor) And the view: def monitor(request): param1 = request.GET.get('param1') param2 = request.GET.get('param2') But when I try to print the two parameters, param1 gets printed but param2 does not get printed. Instead it prints None. -
Using custom permissions in view after log in django
I have 3 types of users in my models.py class Customer(models.model) user = models.OneToOneField(User, on_delete=models.CASCADE, related_name=‘Customer’) class ClientTypeA(models.model) user = models.OneToOneField(User, on_delete=models.CASCADE, related_name=‘ClientA’) class ClientTypeB(models.model) user = models.OneToOneField(User, on_delete=models.CASCADE, related_name=‘ClientB’) I was using permissions in my base template to render the correlating sidebar, but now I am also incorporating a specific dashboard for each user along with the sidebar, so I find it would be simpler to create home views for each of the user types. Once I log a user in it redirects them to my home view - so I came up with this in my views.py def home(request): if request.user.is_customer: return redirect(customer_home) elif request.user.is_clientA: return redirect(clientA_home) elif request.user.is_clientB: return redirect(clientB_home) else: return render(request, 'home.html') The redirects called will simply take them to there corresponding home pages. I know my is_customer, is_clientA, is_clientB do not automatically come with django, how and where do i add these custom permissions? to my models.py? What would I set them equal to in order to simply check is the type of user active? Do I even need custom permissions or is there a simpler way to call the type of user? Am i using to many if statements? (I'm trying to keep … -
EXtra field check on Django oauth2 login - Django Rest API
I have implemented oauth2 code for login in django rest api. I already copied oauth2 folder in my app section. I want to check an extra status field in login. So what I have to change in the code to check a status field? -
Django model field validator is not raising an Exception as it should
I have the following model in models.py: @python_2_unicode_compatible class Session(ModelCommon): # ModelCommon is an abstract Model which extends from models.Model with the fields name(CharField) and enabled(BooleanField). """ Model Session with foreign key to Model Event. """ event = models.ForeignKey(verbose_name=_('Event'), to=Event, default=None, null=False, blank=False) start_datetime = models.DateTimeField(verbose_name=_('Session Starts'), default=None, null=False, blank=False) end_datetime = models.DateTimeField(verbose_name=_('Session Ends'), default=None, null=False, blank=False) available = models.BooleanField(verbose_name=_('Available'), default=True, null=False, blank=False) price = models.DecimalField(verbose_name=_('Price'), max_digits=10, decimal_places=2, validators=[MinValueValidator(0.00)], default=None, null=False, blank=False) When I test my Model that it shouldn't be saved in Database if price is negative, it doesn't raise an Exception as it should. test_models.py: class SessionTestCase(TestCase): """ Case of tests for Model Session. """ def setUpTestData(cls): """ This method is used to declare dummy data that could be used by all tests. """ cls.test_event = Event(name='Test Event Name for Session', enabled=True) cls.test_event.save() def setUp(self): """ This method is used to run code before each test. """ self.session = Session(event=self.test_event, name='Session No1', enabled=True, start_datetime=timezone.now() + timedelta(days=1), end_datetime=timezone.now() + timedelta(days=3), price=0) def test_session_price_cannot_be_negative(self): """ :return: Passed if Session object with negative price raises Exception. """ self.session.price = -20.0 self.assertRaises(Exception, lambda: self.session.save()) Finally, as I run my test_models.py, I get the following message: Failure Traceback (most recent call last): self.assertRaises(Exception, … -
How to increment a database model in django rest framework?
I have a model called Statistics. I want to create an endpoint in django-rest-framework that will select an instance of Statistics based on the user who requested it and increment a couple of the fields on that instance such as "games_played" and "games_won". -
Django Google maps API location
I copied this code from the Google maps API website: <script> function initMap() { var uluru = {lat: -25.363, lng: 131.044}; var map = new google.maps.Map(document.getElementById('map'), { zoom: 4, center: uluru }); var marker = new google.maps.Marker({ position: uluru, map: map }); } </script> It works fine but I now need to change the coordinates, I've tried this: var uluru = {lat: {{ item.locationx }}, lng: {{item.locationy}} }; The variables contain the correct coordinates (I've tested them else where and are working) what is the correct notation for using those variable in the coordinates? Thanks -
Add Custom Disposition for file names using django-storages S3 in python
I have a Django model that saves filename as "uuid4().pdf". Where uuid4 generates a random uuid for each instance created. This file name is also stored on the amazon s3 server with the same name. I am trying to add a custom disposition for filename that i upload to amazon s3, this is because i want to see a custom name whenever i download the file not the uuid one. At the same time, i want the files to stored on s3 with the uuid filename. So, I am using django-storages with python 2.7. I have tried adding content_disposition in settings like this: AWS_CONTENT_DISPOSITION = 'core.utils.s3.get_file_name' where get_file_name() returns the filename. I have also tried adding this to the settings: AWS_HEADERS = { 'Content-Disposition': 'attachments, filename="%s"'% get_file_name(), } no luck! Do anyone of you know to solve this. -
Django Template double entry table
I have these models set up: class Bar: name = models.CharField() foos = models.ManyToManyField( through='FooBar' through_fields=('bar','foo') ) class Foo: name = models.CharField() class FooBar: foo = models.ForeignKey(Foo) bar = models.ForeignKey(Bar) value = models.DecimalField() I'm trying to make a double entry table to show for each Bar, the value of its Foos, and n/a if the Bar doesn't have a value for this Foo. This is what I want it to look like: [Foo1] [Foo2] [Foo3] [Bar1] 4 n/a n/a [Bar2] 3 n/a 9 [Bar3] n/a 1 n/a And this is the code I have: <tr> {%for foo in foo_list%} <th>{{foo.name}}</th> {%endfor%} </tr> {%for bar in bar_list%} <th>{{bar.name}}</th> {%for foobar in bar.foobar_set.all%} //if foobar.foo == foo -> put value else n/a {%endfor%} </tr> {%endfor%} I can't figure out how to check if the foobar correspond to the foo. I could do it with a for i in range(0,foo_list.count()) and mess with the i, but I can't do this in Django Template Langage. -
Show events in a specific time range
My problem is that I want to show all events that are for example in years 2016-17, 2017-18, 2018-19 etc, for example from 1.07.2016 to 31.08.2017. I use Django 1.6. When I go to url: http://127.0.0.1:8000/en/production/2016-17 I got an error: Event matching query does not exist. Event model: class Event(models.Model): name = models.CharField('Name', max_length=255) start = models.DateField('Start') end = models.DateField('End') def __unicode__(self): return self.name Here is my url: url(r'^(?P<branch_slug>/production/(?P<year1>[0-9]{4})-(?P<year2>[0-9]{2})$', EventView.as_view()), Here is my view: class EventListView(ListView): def get_queryset(self): filter_ = {'online': True} season_start = Event.objects.get(start=datetime.date(int(self.kwargs['year1']), 7, 1)) season_end = Event.objects.get(end=datetime.date(int(self.kwargs['year1']), 8, 31)) filter_['start__gte'] = season_start filter_['end__lte'] = season_end return self.model.objects.filter(**filter_) Please for help or some hint. -
Applying Taggit tags within csv and uplaod script
I am trying to uplaod new components into my projects database, It all works fine until i bring my tag field into the mix. Telling me it needs to be a tag instance. So my problem is i need to uplaod components already tagged into the system, using a CSV file and a python script. Is there any clean way of doing this? -
Django Rest Framework: Custom ordering on a CharField of Serializer
I'm using django rest framework and I would like order with custom list of fields. For example, I would like to create something like /api/?ordering=brand,article_structure to order on 'brand' and on 'article_structure'. The problem is that the default django filters are implemented on the database side, so I'm not able to create filters on custom fields. # serializers.py class ArticlePhotobookSerializer(ModelSerializer): brand = CharField(source='order.brand') season = CharField(source='order.season') collection = CharField(source='order.collection') class Meta: model = Article fields = ('uuid', 'brand', 'collection', 'season', 'article_structure') # views.py class PhotobookViewSet(AbstractOrderWriterViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer filter_backends = (filters.DjangoFilterBackend,) Is there any way to implement this kind of ordering? -
Global variable in django changing on its own
My code is as below: f=0 def load(request): global f if f == 0: login f=f+1 else: some commands the function load is called several times.so every time the function is called value of 'f' will be set to zero? -
ManyToManyField references the 'id' field when I am using a custom primary key
I am using a custom primary key for a model that has a few ManyToManyFields. When I update the model and add an object to a ManyToManyField (using add(new_object)), I get an error signifying that its looking up the primary key using the id field (which perhaps exists in the intermediary table, but not in the model). psycopg2.DataError: invalid input syntax for integer: "TL98GK" LINE 1: ...WHERE ("placedir_place_place_categ"."place_id" = 'TL98GK' A... I have been searching on SO for a while but havent been able to zero in the exact issue. I guess I may have to use custom through table for ManytoManyFields (as a punishment for using custom primary key) but I honestly dont want to go down that route. Using Django 1.10 and Python 3