Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible for Django to act as a Backend Framework for a SAAS and Smartphone App together?
I want to create an SAAS for businesses and release an App for their customers, which can interact with the SAAS in real time. Please give your valuable suggestions on how can I achieve this using the best tools if not the ones I mentioned in the question. -
Duplicate records when treeforeignkey is null in django mptt
I have this model: class Genre(MPTTModel): id = models.CharField(max_length=100) name = models.CharField(max_length=100) parent = TreeForeignKey( 'self', null=True, blank=True, related_name='subgenre' ) def __str__(self): return self.name class Meta: unique_together = (('id', 'parent'),) I didn't want to have duplicate records, so I'm using unique_together with the id and the TreeForeignKey. Even with unique_together, I'm still able to add duplicates when I set the parent to null. How can I avoid that? -
How does the model __init__ work with django admin inlines
I've been trying to use the model init to store field values when the instance is loaded so I can check certain fields for changes in the save() method and perform certain actions. I got the code from Odif's answer on this question: django - comparing old and new field value before saving class Company(models.Model): company_name = models.CharField(max_length=100, blank=False, null=False) pim_company = models.ForeignKey(PIMCompany, null=True) STATUS = ( ('ACTIVE', 'Active'), ('INACTYIVE', 'In-active'), ) status = models.CharField(choices=STATUS, max_length=20, default='ACTIVE') system = models.ForeignKey(SourceSystem, db_index=True) def __init__(self, *args, **kwargs): super(Company, self).__init__(*args, **kwargs) self.__important_fields = ['status', 'system'] for field in self.__important_fields: setattr(self, '__original_%s' % field, getattr(self, field)) def important_field_has_changed(self): for field in self.__important_fields: orig = '__original_%s' % field if getattr(self, orig) != getattr(self, field): return True return False This works fine when just interacting with the model itself, but it doesn't work when the model is included as an inline in it's parent model. When I do this I get the error: Request Method: GET Request URL: https://.....url.... Django Version: 1.8.4 Exception Type: RelatedObjectDoesNotExist Exception Value: Company has no system. The inlines work fine if the fields included in self.__important_fields = ['status', 'system'] Are normal fields and not ForeignKeys. As soon as there is a … -
"django-rest-auth" DoesNotExist: Site matching query does not exist
I am using django-rest-auth for facebook integration with android as front-end. I followed all the steps mentioned in integrating django-rest-auth. I have only one SITE and set SITE_ID to 1 I have also set Client ID and Secret ID of my app and made sure i have choosen my site. Here is a screenshot Below is my code INSTALLED_APPS = [ 'rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', ] My custom Login Serializer REST_AUTH_SERIALIZERS = { 'LOGIN_SERIALIZER': 'cut_veggie_user.serializers.NormalUserSerializer', } AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) SITE_ID = 1 In the urls I have also included the FacebookLogin urlpatterns = [ url(r'^rest-auth/facebook/$', FacebookLogin.as_view(), name='fb_login'), ] Can anyone tell my what am i missing? -
Django AttributeError: 'Alias' object has no attribute 'urls'
I've just finished writing out my model for my Heroes App: I adjusted my settings.py file under the Installed Apps: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #custom apps 'heroes', ] And then I adjusted my admin.py file: from django.contrib import admin # Register your models here. from .models import Hero, Stats, Team, Status, Alias admin.site.register(Hero, Stats) admin.site.register(Team) admin.site.register(Status, Alias) In the Command Prompt I typed out: python manage.py makemigrations and I got this error - "AttributeError: 'Alias' object has no attribute 'urls'": (secondproject) C:\Python34\Scripts\secondproject\heroes4Hire>python manage.py emigrations aceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Python34\Scripts\secondproject\lib\site-packages\django\core\managem \__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Python34\Scripts\secondproject\lib\site-packages\django\core\managem \__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python34\Scripts\secondproject\lib\site-packages\django\core\managem \base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python34\Scripts\secondproject\lib\site-packages\django\core\managem \base.py", line 342, in execute self.check() File "C:\Python34\Scripts\secondproject\lib\site-packages\django\core\managem \base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "C:\Python34\Scripts\secondproject\lib\site-packages\django\core\managem \base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "C:\Python34\Scripts\secondproject\lib\site-packages\django\core\checks\ istry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python34\Scripts\secondproject\lib\site-packages\django\core\checks\ s.py", line 14, in check_url_config return check_resolver(resolver) File "C:\Python34\Scripts\secondproject\lib\site-packages\django\core\checks\ s.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "C:\Python34\Scripts\secondproject\lib\site-packages\django\utils\functi l.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python34\Scripts\secondproject\lib\site-packages\django\urls\resolve py", line 313, in url_patterns … -
Django Rest Framework 3 - Many to many with extra fields
I have a problem with the serializers on Django Rest Framework... first my models are: class Transaction(Model): type_choices = ( (1, 'deposit'), (2, 'withdrawal') ) status_choices = ( (1, 'pending'), (2, 'made'), (3, 'canceled'), (4, 'completed') ) name = CharField(null=True, blank=True,max_length=50,) description = TextField(null=True, blank=True) amount = FloatField() type = IntegerField(choices=type_choices, ) status = IntegerField(choices=status_choices, ) client = ForeignKey(User, related_name='transaction_client', blank=True, null=True) cards = ManyToManyField(Card, through='TransactionCard') created_by = ForeignKey(User, related_name='transaction_created_by') created_at = DateTimeField(auto_now_add=True, editable=False) updated_by = ForeignKey(User, null=True, related_name='transaction_updated_by') updated_at = DateTimeField(auto_now=True, editable=False) class Meta: ordering = ('-created_at',) def __str__(self): return self.name class TransactionCard(Model): transaction = ForeignKey(Transaction, related_name='transactioncard_transaction') card = ForeignKey(Card, related_name='transactioncard_card') amount = FloatField() class Card(Model): name = CharField(null=True, blank=True, max_length=100,) description = TextField(null=True, blank=True,) card_number = TextField(max_length=16, ) month_exp = IntegerField() year_exp = IntegerField() month_acq = IntegerField(null=True, blank=True,) year_acq = IntegerField(null=True, blank=True, ) card_type = ForeignKey(CardType, related_name='cards_card_type') provider = ForeignKey(Provider, related_name='cards_provider') balance = FloatField() active = BooleanField() created_by = ForeignKey(User, related_name='cards_created_by') created_at = DateTimeField(auto_now_add=True, editable=False) updated_by = ForeignKey(User, null=True, related_name='cards_updated_by') updated_at = DateTimeField(auto_now=True, editable=False) class Meta: ordering = ('month_exp', 'year_exp',) def __str__(self): return self.name And my serializers are: class TransactionCreateSerializer(ModelSerializer): created_by = StringRelatedField() updated_by = StringRelatedField() class Meta: model = Transaction fields = [ 'id', 'name', 'description', 'amount', … -
Python - How to output matplotlib plots as images to the browser in Django
I'm using Python- Pandas, Numpy to implement some financial indicators and strategies. I'm also using the Matlab library in Python to plot my data. On the other hand, I'm using Django for the web-end part of my project. What I want to do is to output my matlab plot as an image to the browser using Django. Any recommendation is appreciated. Thank you so much! -
WebRTC with django channel giving error "InvalidStateError: Cannot set remote answer in state stable"
WebRTC giving error InvalidStateError: Cannot set remote answer in state stable.I am using Django channel for signaling.I am building this only for two peer. Below is my javascript code var ws = new WebSocket(location.href.replace('http', 'ws').replace('room', 'ws')); var pc; var initiator; function initiatorCtrl(event) { if (event.data == "fullhouse") { alert("full house");//If more than two peer } if (event.data == "initiator") { initiator = false; init(); } if (event.data == "not initiator") { initiator = true; init(); } } initiatorCtrl(isInitiator); function init() { var constraints = { audio: true, video: true }; getUserMedia(constraints, connect, fail); } function connect(stream) { pc = new RTCPeerConnection(null); if (stream) { pc.addStream(stream); $('#local').attachStream(stream); } pc.onaddstream = function(event) { $('#remote').attachStream(event.stream); logStreaming(true); }; pc.onicecandidate = function(event) { if (event.candidate) { ws.send(JSON.stringify(event.candidate)); } }; ws.onmessage = function (event) { console.log(event) var signal = JSON.parse(event.data); if (signal.sdp) { if (initiator) { receiveAnswer(signal); } else { receiveOffer(signal); } } else if (signal.candidate) { pc.addIceCandidate(new RTCIceCandidate(signal)); } }; if (initiator) { createOffer(); } else { log('waiting for offer...'); } logStreaming(false); } function createOffer() { log('creating offer...'); pc.createOffer(function(offer) { log('created offer...'); pc.setLocalDescription(offer, function() { log('sending to remote...'); ws.send(JSON.stringify(offer)); }, fail); }, fail); } function receiveOffer(offer) { log('received offer...'); pc.setRemoteDescription(new RTCSessionDescription(offer), function() { log('creating answer...'); … -
Django - Models with Abstract Classes
I'm using an app (Github link here). I've been stuck trying to make it so 1 field, that I choose, as the developer, becomes 'default', and present in every custom form that's ever created in the admin, no matter what. I'm still relatively new to Django. So far I've attempted to make do with changes in the admin (admin.py file), but they did not turn out too well. The app's models.py file: There are 'Fields' and 'Forms'. Each 'Form' can have multiple 'Fields' in it, as expected. The most important class for me here seems to be 'AbstractField': https://github.com/stephenmcd/django-forms-builder/blob/master/forms_builder/forms/models.py#L159 There's a concrete class that implements the AbstractField I've linked to above, it's called Field (and that also establishes a relation with 'Form'). It's here: https://github.com/stephenmcd/django-forms-builder/blob/master/forms_builder/forms/models.py#L275 #models.py ... Here is the Field class... class Field(AbstractField): """ Implements automated field ordering. """ form = models.ForeignKey("Form", related_name="fields") order = models.IntegerField(_("Order"), null=True, blank=True) #... A) My only (vague) idea, is for me to create an extra class, derived from AbstractField, going for something like: class DefaultLocationField(AbstractField): form = models.ForeignKey("Form", related_name="thelocationfield") and go from there and modify the app's code from forms.py + views.py (so that that this new 'DefaultLocationField' actually ends up appearing together … -
Django-paypal doesn't recieve signals
I'm trying to create a simple Paypal pay in my project, just to see if it works and then make it more custom. The problem is that it doesn't work as I expected. When I make a payment (using sandbox), myemail-buyer@gmail.com sents money succesfully but myemail-facilitator doesn't have any notifications there (but recieved money). Moreover, no signal is being recieved and no Paypal IPNS rows are in Django-admin Paypal IPNs. It can be probably many things and since I'm new in django-paypal I can't figure out what's the problem. I'm using developlment server but it is accessible from outside. VIEW def payment(request): items = Job.get_unpaid_orders_for_user(request.user) table = PaymentTable(items) total_price = 0 payment = Payment.objects.create() for item in items: if item.invoice.final_price: payment.invoices.add(item.invoice) total_price += item.invoice.final_price payment.total_price = total_price payment.save() context = {} context['items'] = items context['table'] = table context['total_price'] = total_price paypal_dict = { "business": "myemail-facilitator@gmail.com", "currency_code":"EUR", "amount": total_price, "item_name": payment.get_desc(), "invoice": payment.payment_identifier, "notify_url": "http://my_public_ip:8000/" + reverse('paypal-ipn'), "return_url": "http://my_public_ip:8000/return", "cancel_return": "http://my_public_ip:8000/cancel", "custom": "Upgrade all users!", # Custom command to correlate to some function later (optional) } form = PayPalPaymentsForm(initial=paypal_dict) context["form"]=form return render(request, "ordersapp/payment/payment.html", context=context) BOTTOM OF MODELS.PY OF ORDERSAPP from paypal.standard.models import ST_PP_COMPLETED from paypal.standard.ipn.signals import valid_ipn_received def show_me_the_money(sender, **kwargs): ipn_obj … -
Django python Can not import FunctionType from module types
I am trying to use django channels and asgi to run a simple chat server. I have channels and daphne installed, but when I try to run the development server, I get the following error. Unhandled exception in thread started by <function wrapper at 0x1062fdc80> Traceback (most recent call last): File "/Users/yash/code/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/yash/code/lib/python2.7/site-packages/channels/management/commands/runserver.py", line 63, in inner_run "layer": self.channel_layer, File "/Users/yash/code/lib/python2.7/site-packages/channels/asgi.py", line 86, in __str__ return "%s (%s)" % (self.alias, name_that_thing(self.channel_layer)) File "/Users/yash/code/lib/python2.7/site-packages/channels/utils.py", line 25, in name_that_thing return name_that_thing(thing.__class__) File "/Users/yash/code/lib/python2.7/site-packages/channels/utils.py", line 16, in name_that_thing if hasattr(thing, "__class__") and not isinstance(thing, (types.FunctionType, types.MethodType)): AttributeError: 'module' object has no attribute 'FunctionType' I have checked out the last file and found that the error is with the types module. the line import types worked fine, but when the script trys to call types.FunctionType it gives an AttributeError. When I imported the script on the shell, `It worked as expected Any help is greatly appreciated. :) -
Django Proxy Model Permissions
Good day, i have proxy model class NewZalobiNotifications(Zalobi): class Meta(): proxy = True verbose_name = 'New zalobi' verbose_name_plural = 'New zalobi' app_label = 'notifications' objects = NewZalobiManager() def __unicode__(self): return format('%s' % self.title) Hgow can i put permissions for this model in admin to group users? -
Ensure a django model field is written only once ? Atomicity guaranteed without locks
I am looking for a reliable way to ensure that for any given instance of a django model, a specific field is written only once. The expected behavior is like the auto_now_add option to datefields. The code should run in both views or tasks using celery. I am thinking about the following : from django.db import transaction from django.utils.timezone import now ... def perform_writeonce(object_pk): with transaction.atomic(): instance = MyModel.objects.get(pk=object_pk) if instance.value is None: instance.value = 'Value written now : {}'.format(now()) instance.save() Are you confident in this snippet or is there something I missed ? I am using multiple gunicorn instances and celery workers but a single postgresql database server. I am trying to avoid locks at all costs, so any solution with application-land locks are no good. Thanks for any help. -
Getting ImageField file path post_delete
I'm making a little piece of software with Django and JS that will handle image uploads. So far, so good. I'm getting nice little images via AJAX from dropzone.js. They are saved on the file system and have an ImageField in my Photo model to keep track of what is stored and where. I even stabbed dropzone.js to nicely ask my dev server to delete the database entries and the files themselves. I find that the latter part is lacking a bit. So I started writing a function that catches a post_delete signal from my Photo model and has the task of handling the deletion from the file system. The problem is, I can't seem to find a way to get my hands on the file path that's stored in database. If I've understood correctly, the following should work: from django.db import models from django.db.models.signals import post_delete from django.dispatch import receiver class Photo(models.Model): imageFile = models.ImageField(upload_to=generateImageFileNameAndPath) @receiver(post_delete, sender=Photo) def cleanupImageFiles(sender, **kwargs): print("Cleanup called") p = kwargs['instance'] path = p.imageFile.name print(path) But when I try to output path to the console, there's nothing. Sorry about the upperCasing instead of using under_scores as seems to be Python convention. I personally find the … -
Django dynamic urls with multiple arguments
I am somewhat new to Django and I figured I would start of by building a standard library app. What I had initialy created was a url pattern using slugs that shows you all the articles in a journal via http://127.0.0.1:8000/Albums/[album name]/. This worked. What I then tried to do was make the article names clickable so that they would refer you to a page containing details about the song. Particularly I wanted these details to be accessible via a link of the form http://127.0.0.1:8000/Albums/[article name]/[article_id]/. Where article_id at the moment is the primary key in a database table containing all articles. In order to do so I defined two url patterns: urlpatterns = [ url(r'^(?P<slug_journal>[\w-]+)/$', views.Journal_Article_Page, name='Journal_Page'), url(r'^(?P<slug_journal>[\w-]+)/(?P<id>\d+)/$', views.Journal_Article_Page, name='Journal_Article_Page'), ] and a view: def Journal_Article_Page(request, slug_journal=None, id=None): if slug_journal: if id: farticle = get_object_or_404(Article_Draft_Table_1, DRAFT_ID = id) return render(request, 'journal_article_details.html', { 'farticle': farticle, 'fjournal': slug_journal }) else: fjournal = get_object_or_404(Journal_Table, Journal_slug = slug_journal).JOURNAL_ID articles = Article_Draft_Table_1.objects.filter(JOURNAL_ID = fjournal) return render(request, 'journal_articles.html', { 'articles': articles }) And finally a template: {% extends 'base.html' %} {% block content %} <p>List of articles.</p> <br> {% for article in articles %} <div class="col-sm-10"> <a href='{% url "Journal_Article_Page" slug_journal=fjournal id=article.DRAFT_ID %}'>{{ article.Draft_title }}</a> … -
Display Form Data to the Same Page
The form works. The input is displayed on the rule. But the template displays a blank page. Help! views.py class StandingsView(FormView): form_class = SelectTeam template_name = 'teamsports/standings.html' model = Teams success_url = None def form_valid(self, form): form=SelectTeam data = self.request.GET.get('team_name') team = Teams.objects.filter(team_name__icontains=data).values() return render(self.request, 'teamsports/standings.html', {'team': team}) template.html {% extends 'teamsports/base.html' %} {% block content %} <h1>Pick your team, chump</h1> <form form_name = SelectTeam action="" method="GET"> {{ form }} <input type="submit" value="Submit" /> {{ form.errors }} </form> <h1> {{ team }} </h1> {% for team in Teams %} <h1>{{ team.team_name }}</h1> {% endfor %} {% endblock %} -
Django login always return anonymous user
I wrote a simple login function as below. The Django development version is 1.9.8 and python version is 3.5. The login function def login(req): if req.method == "POST": username = req.POST.get("username") password = req.POST.get("psw") kwargs = {'username': username, 'password': password} user_ = auth.authenticate(**kwargs) if user_ is not None and user_.is_active: auth.login(req,user_) return render(req, "home.html", {"status": "Logged In Successess"}) else: return render(req, "home.html", {"status": "Log In Failed. Check!"}) else: return render(req, "login.html") else: return render(req, "login.html") settings.py AUTHENTICATION_BACKENDS=[ 'django.contrib.auth.backends.ModelBackend', ] AUTH_USER_MODEL = "shop.customer" After inserting lots of breakpoints to observe the authentication behavior, I found that the error occurs in the instruction(line 18~19) in the Django source https://github.com/django/django/blob/stable/1.9.x/django/contrib/auth/backends.py. if user.check_password(password): return user It always returns me an anonymous user. So I turn to create a superuser and try it again. The same result continues. Somebody please give me hints and suggestions, thank you!!! -
Django form is_valid not working with x-editable jquery plugin
My current system is built on python-django. I am a beginner though in python. I am trying to edit a text using x-editable plugin but form.is_valid() returns false. HTML: <a href="#" data-type="text" class="text-title editable editable-click" data-name="section_title">Title</a> jQuery: $('a[data-name="section_title"]').editable({ type: 'text', url: "work/", ajaxOptions: { dataType: 'json', type: 'POST' }, params: { action: 'edit', key: 'ymnywgm4pqd72lozqvo68k510zrvjx9p', csrfmiddlewaretoken: $("meta[name=csrf_token]").attr("content"), pk: 1, _edit: 1 }, name: 'section_title', }); python: def edit(self, request): form = self.Form(request.POST, request.FILES, initial=self.data) if not hasattr(form, "helper"): form.helper = FormHelper() form.helper.form_tag = False if request.POST and request.POST.has_key("_edit"): if form.is_valid(): for key, value in form.cleaned_data.items(): if key not in ("_edit", "action", "key"): self.data[key] = value self.save() success = True content = self.render(request) else: success = False content = render_to_string(self._meta.edit_template, {"form": form, "key": self.instance.get_pk_hash()}) else: form = self.Form(initial=self.data) if not hasattr(form, "helper"): form.helper = FormHelper() form.helper.form_tag = False success = False content = render_to_string(self._meta.edit_template, {"form": form, "key": self.instance.get_pk_hash()}) return JsonResponse({ "success": success, "content": content, }) The line form.is_valid returns false. action/key/_edit is posting via jquery but I cannot understand why it returns false. Any help is highly appreciated. Thanks in advance. -
How to get the "request" data in the __init__ function in a Django Class Based View
class myClass(View): def __init__(self, *args, **kwargs): """ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ I want the request data over here. @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ """" def get(self, request, *args, **kwargs): """do stuff""" return render(request, template.html, locals()) def post(self, request, *args, **kwargs): """do stuff""" Is it possible to obtain the "request" data inside the __init__ funtion. -
Making a custom Boolean field in Django REST Framework
I'm new to django rest framework. The relevant part of my models looks something like this (simplified): class Action(models.Model): type = models.CharField() bonus = models.IntegerField() class User(models.Model): auth = models.OneToOneField(AuthUser) display_name = models.CharField() class Comment(models.Model): contributor = models.ForeignKey(User) content = models.TextField() class Activity(models.Model): user = models.ForeignKey(User) target_comment = models.ForeignKey(Comment) action = models.ForeignKey(Action) I want one of my API endpoints to be able to return something like this: { ... "comments": [ { "id": 1, ... "curr_user_upvoted": true }, ... ] } I know the query I need to execute in order to get the value for "curr_user_upvoted", but I don't know how to make it part of the API representation. I know how to create custom relational fields, but it doesn't help since "curr_user_upvoted" is neither a field nor a relation. Any idea? -
Python Django Forms
I'm quite new for the web development using Python. I am using the following example (given in some of the questions in this website) python and HTML files in order to create a django form with Python 3.5.2: urls.py from django.conf.urls import patterns, url import views urlpatterns = patterns( '', url(r'^email/$', views.email, name='email' ), url(r'^thanks/$', views.thanks, name='thanks' ),) forms.py from django import forms class ContactForm(forms.Form): from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea) views.py from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, redirect from yourapp.forms import ContactForm def email(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('thanks') return render(request, "yourapp/email.html", {'form': form}) def thanks(request): return HttpResponse('Thank you for your message.') email.html <form method="post"> {% csrf_token %} {{ form }} <div class="form-actions"> <button type="submit">Send</button> </div> </form> However, everytime I run the html file I can't get the form on the page. Instead I get the following screenshot: Screenshot What can be the problem? Thanks for the help! -
Django with Jpegoptim and Optipng
I have a website developed with Django 1.10. The users can send images to the website. Unfortunately there are images very heavy ! ( > 1 mo). Currently when the dimension is greater or equal to 4000*4000, I resize to 128*128 but it's not sufficient for the weight... Google advises to use Jpegoptim and Optipng. So I tried to use these tools directly in my Django code but it doesn't works... (I already install jpegoptim and optipng) : def optimize(path): runString = { ".jpeg": u"jpegoptim -f --strip-all '%(file)s'", ".jpg": u"jpegoptim -f --strip-all '%(file)s'", ".png": u"optipng -force -o7 '%(file)s' && advpng -z4 '%(file)s' && pngcrush -rem gAMA -rem alla -rem cHRM -rem iCCP -rem sRGB -rem time '%(file)s' '%(file)s.bak' && mv '%(file)s.bak' '%(file)s'" } ext = splitext(path)[1].lower() if ext in runString : print("ok") subprocess.Popen(runString[ext] % {'file': path}, shell=True) class ImageUser(models.Model): image = models.ImageField(upload_to="imageUser/", null=True) def save(self, *args, **kwargs) : super(ImageUser, self).save() image = Image.open(self.image.path) optimize(self.image.path) image.save(self.image.path) I want to reduce the weight of the images before the saving if it's possible. Where I am wrong ? Thank you -
How to access to remote Postgresql database in django
Greeting. My simple project was set for local Mysql database but my client required that the database should be Postgresql on AWS. He sent me the url and Access key pair. The information he sent are following. https://0387XXXXXX98.signin.aws.amazon.com/console User name: "xxxxx" Password:"" # he did not send password Access key ID: "AKIXXXXXXXXXXXMAA" Secret access key: "XXXXXXXXXXXXXXXXXXXXXX/XXXXXXXXXXXXXX" Please help me to migrate my project. I am not familar with AWS. What I want to know is 1. How to access to AWS Postgresql instance. 2. How can I set up my project for remote AWS Postgresql with above information. Thanks. -
Django bulk create with using="" param
When I save objects using django model of save like this: rank = Rank() rank.save(using="test") I would like to save bulk of ranks like this: Rank.objects().bulk_create(ranks) - how can I send to is also the using parameter? -
Django copy modifies queryset?
help me not to go crazy. Consider this code import copy def my view(): #... for v in vendors: vendor = Vendors.objects.get(id = v) vendor_orders = order_suggestions_qs.filter_vendor(v) centralized_order = None for legal_entity_own in legal_entity_own_qs: vendor_agreement = vendor.get_agreement(legal_entity_own) if vendor_agreement: if vendor_agreement.is_centralized: vendor_order_legal_entity_qs = vendor_orders.filter_legal_entity_own([legal_entity_own]) initial_vendor_order_legal_entity_qs = copy.copy(vendor_order_legal_entity_qs) The last command modifies vendor_order_legal_entity_qs and vendor_orders ! Specifically, it makes the querysets empty ! I have nothing to add :) Complete mistery. Any ideas ????