Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin and ImageField dimension restrictions
I'm using Django 1.10.1. I have a model with an ImageField, and I want to trigger an error when someone tries to upload a file with is bigger than 900x900px in the Django Admin site. What's the easiest way to do this? I would prefer to do this in the Model class since it should never be allowed to save a bigger image, but I've read somewhere it's not possible since you can't access the image data as long as the data isn't saved. -
Django 1.9 Crispy forms 1.6 multiple forms
I 'm writing an app in Django 1.9 and installed Crispy forms 1.6 (using bootstrap3 template pack). In that app, I have a profile model, next to the standard User model. Now, I want to allow the users to modify their profile, and I want to display both User fields and Profile fields on one page. The Profile model contains an avatar, which I want to display on to of the page, followed by some fields from the User model, and after that the rest of the Profile form's fields. Something like: > Avatar (Profile model) > First name (User model) > Last name (User model) > E-mail address (User model) > Street (Profile model) > ZIP (Profile model) > Country (Profile model) > Website (Profile model) I've written 2 Forms: class UserForm(forms.ModelForm) class ProfileForm(forms.ModelForm) Both extended with the Crispy forms "FormHelper" In my template, I render the forms as: {% crispy pform %} (profile form) {% crispy uform %} (user form) But, of course, that does not display the fields as I described earlier. Does anyone know how I can tackle this problem? Kind regards! Wim -
How can I create a new url in a Django app?
I have implemented a model in a Django app and I would like add an url to handle the view for this model. class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) Can you help me? -
How to send input from template to a view in django
i need some help, i'm a new in django, i want to get the input and print it in the second textarea!, i tried but i really don't know how. i know that i'm wrong but i don't know how to fix it and do it. help! this is my index.html <form method='POST' action=''> <tr><td align="left"> question: </td> <td colspan="5"> <input name="quest" type="text" value= "{{quest}}" size="40" maxlength="200" value=""><font color="DimGray" size="2"> ask yr question:</font> </td> </tr><tr><td></td><td></td></tr> <tr><td height="23"></td></tr> <tr><td></td> <br><button type="submit">Search</button> {% csrf_token %} </form> <td align="left"> le passage </td> <FORM> <TEXTAREA name="nom" rows=4 cols=40>{{res}}</TEXTAREA> </FORM> <td align="left"> les textes </td> <FORM> <TEXTAREA name="nom" rows=4 cols=40>{{aff}}</TEXTAREA> </FORM> this is my views.py from django.shortcuts import render def affich(request): if request.method == 'POST': question = request.POST['quest'] var = question.POST.get('value') aff = var.get_value() return render(request,"index.html",{'aff': aff}) this is my urls.py from django.conf.urls import url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^index/','journal.views.affich',name='index'), url(r'^admin/', admin.site.urls), ] -
Pillow down scale image Python
I am trying to downscale an image in python. The original image that I have is of resolution 800x800, and dpi is 72 pixels/inch. CODE: from PIL import Image im = Image.open('AXSFZLB_1.jpg') im.thumbnail((240,240), Image.ANTIALIAS) im.save('compressed.jpg', 'JPEG', progressive=True, quality=100) The compressed image is blurry. I have tried the resize function as well, but this too quiet doesn't seem to work. Is there any way to fix this? ps - I want a high resolution thumbnail image. -
Django Apps aren't loaded yet Celery Tasks
What is giving the error below? I'm unsure if this is a problem with an app I have installed or one of mine. The exception below is generated only when running Celery i.e. celery -A demo.apps.wall.tasks worker -Q broadcast -l INFO -n broadcast.%%h , runserver does not generate any errors. Which app ios the issue? Traceback (most recent call last): File "/Users/user/Documents/workspace/demo-api/env/bin/celery", line 11, in <module> sys.exit(main()) File "/Users/user/Documents/workspace/demo-api/env/lib/python3.5/site-packages/celery/__main__.py", line 30, in main main() File "/Users/user/Documents/workspace/demo-api/env/lib/python3.5/site-packages/celery/bin/celery.py", line 81, in main cmd.execute_from_commandline(argv) File "/Users/user/Documents/workspace/demo-api/env/lib/python3.5/site-packages/celery/bin/celery.py", line 770, in execute_from_commandline super(CeleryCommand, self).execute_from_commandline(argv))) File "/Users/user/Documents/workspace/demo-api/env/lib/python3.5/site-packages/celery/bin/base.py", line 309, in execute_from_commandline argv = self.setup_app_from_commandline(argv) File "/Users/user/Documents/workspace/demo-api/env/lib/python3.5/site-packages/celery/bin/base.py", line 469, in setup_app_from_commandline self.app = self.find_app(app) File "/Users/user/Documents/workspace/demo-api/env/lib/python3.5/site-packages/celery/bin/base.py", line 489, in find_app return find_app(app, symbol_by_name=self.symbol_by_name) File "/Users/user/Documents/workspace/demo-api/env/lib/python3.5/site-packages/celery/app/utils.py", line 238, in find_app sym = imp(app) File "/Users/user/Documents/workspace/demo-api/env/lib/python3.5/site-packages/celery/utils/imports.py", line 101, in import_from_cwd return imp(module, package=package) File "/Users/user/Documents/workspace/demo-api/env/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 662, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/Users/user/Documents/workspace/demo-api/demo/apps/Walls/tasks.py", line 14, in <module> from demo.apps.Walls.redis_models import WallSchedule, WallBroadcast, UserWalls File "/Users/user/Documents/workspace/demo-api/demo/apps/Walls/redis_models.py", … -
I want to group by month how to do?in django
sumary = Profile.objects.values('user_report__created_date__month') Error Cannot resolve keyword 'month' into field. Join on 'created_date' not permitted. -
Setting a cookie in a Django view
I am trying to set a cookie in a view using the following code. def index(request): resp = HttpResponse("Setting a cookie") resp.set_cookie('name', 'value') if 'name' in request.COOKIES: print "SET" else: print "NOT SET" return render(request, 'myapp/base.html', {}) When the view is loaded, the console prints out NOT SET, which means the cookie was not set. In every tutorial/doc, this seems to be the method used. However, it simply does not work for me :/ Any help? I am using Django 1.9.8, and I am running the app in my local server, or 127.0.0.1:8000. -
How to use dynamic root path in nginx based on $uri?
When the user visits : http://my-app.example.com/testapp1 I need to serve static with a root path dynamically generated from the $uri, because I am hosting the same app in different versions with different assets. # $uri in this case is /testapp1 location /static { root /home/user$uri/current # root /home/user/testapp1/current <- I want this } The $uri seems not working when used in the root path, any other work ground? -
Django Postgresql Sum Error
I have a model Transaction model.py class TransactionManager(models.Manager): def get_queryset(self): return TransactionQuerySet(self.model, using=self._db) def all_for_user(self, user): # self.get_queryset().mark_all_unread(user) return self.get_queryset().get_user(user) class Transaction(models.Model): reason = ( ("Fund Transfer","Fund Transfer"), ("Fund Recieved","Fund Recieved"), ) recipient_username = models.CharField(max_length=100) sender = models.CharField(max_length=100) recipient_name = models.CharField(max_length=50) purpose = models.CharField(max_length=100, choices=reason) amount = models.DecimalField(decimal_places=2, max_digits=20) transaction_charge = models.DecimalField(decimal_places=2, max_digits=20) message = models.CharField(max_length=255) # total_balance = models.DecimalField(decimal_places=2, max_digits=200, null=True, blank=True) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) objects = TransactionManager() def __str__(self): return self.recipient_name and view.py def useraccount(request): # if not request.user.is_authenticated: # raise Http404 name = request.user # account = get_object_or_404(Transaction, recipient_username=name) notification = Notification.objects.all_for_user(name) trans = Transaction.objects.all_for_user(name) transaction = Transaction.objects.all().filter(recipient_username=request.user).first() user1 = Profile.objects.get(user= name) # trans = Transaction.objects.aggregate(Sum('amount')) # total1 = total = trans.aggregate(price_sum=Sum('amount')) # total = trans.aggregate(price_sum=Sum(Decimal('amount')) # total = Decimal(total) total_price = Decimal(total['price_sum']) # account.total_balance=total_price # account.save() # tra = Transaction.annotate(total=DistinctSum('amount') context = { "notification" :notification, # "account" : account, "user1" : user1, "total_price" :total_price, # "tra":tra, # "total":total, } return render(request, "notification/account.html", context) Now here is the problem. I have this Error when i use PostgreSQL error screen shot but this works well on sqlite3. I don't have this error with sqlite3 but when i use PostgreSQL i have the above error Could anybody point … -
Django collectstatic command for specific file or folder
when I run this code python manage.py collectstatic --clear --noinput it remove all static files and folders in staticroot and colletc all files and folders again. But I want to collect just a specific file or a specific folder. How can i do that? -
Updating model in Django based on dictionary values
I have a dictionary in Django, contains a model's keys and some values. I want to update one of field (score) of the model (A) like this: multiply that field for all the records to a constant, and then, if the record was found in the dictionary, add the corresponding dict value to the field. there are many records, and getting and then saving each object takes lots of time. I tried this update query, but it is not working: A.objects.update(score=F('score') * CONST + (dictionary[F('key')] if F('key') in dictionary else 0)) the problem is that the condition seems to be false for all of the records, I tried to debug the problem, and it seems F('key') doesn't have the desired value (a string). -
Django import-export choices field
I have a model with choices list (models.py): class Product(models.Model): ... UNITS_L = 1 UNITS_SL = 2 UNITS_XL = 3 PRODUCT_SIZE_CHOICES = ( (UNITS_L, _('L')), (UNITS_SL, _('SL')), (UNITS_XL), _('XL'), ) product_size = models.IntegerField(choices=PRODUCT_SIZE_CHOICES) ... Also i added a new class for exporting needed fields(admin.py): from import_export import resources, fields ... Class ProductReport(resources.ModelResource): product_size = fields.Field() class Meta: model = Product #I want to do a proper function to render a PRODUCT_SIZE_CHOICES(product_size) def dehydrate_size_units(self, product): return '%s' % (product.PRODUCT_SIZE_CHOICES(product_size)) fields = ('product_name', 'product_size') Class ProductAdmin(ExportMixin, admin.ModelAdmin): resource_class = ProductReport But this is not working. How can i get a named value of PRODUCT_SIZE_CHOICES in export by Django import-export ? -
How to add placeholder and style the fields with class form-control in Django forms
I have the following django forms and template. I was trying to add placeholder and style my fields with form-control class. I have tried adding the Ex: q = forms.CharField(label='search', widget=forms.TextInput(attrs={'placeholder': 'Search'})). But am getting error. And when I added the method for form-class, the changes are not reflecting opn the template. Any idea guys? Thanks in advance. Forms.py import re from django import forms from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ class RegistrationForm(forms.Form): username = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Username"), error_messages={ 'invalid': _("This value must contain only letters, numbers and underscores.")}) email = forms.EmailField(widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Email address")) password1 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password")) password2 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password (again)")) def clean_username(self): try: user = User.objects.get(username__iexact=self.cleaned_data['username']) except User.DoesNotExist: return self.cleaned_data['username'] raise forms.ValidationError(_("The username already exists. Please try another one.")) def clean(self): if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: if self.cleaned_data['password1'] != self.cleaned_data['password2']: raise forms.ValidationError(_("The two password fields did not match.")) return self.cleaned_data def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): field.widget.attrs.update({'class':'form-control'}) Html {% extends "base.html" %} {% block title %}Login{% endblock %} {% block navbar %} <div align="center" style="padding-top: 5px;"> <h2><b>My Online Journal</b></h2> </div> {% endblock %} {% block content %} {% … -
Chat System Using Django and Node Js
I am hoping to make a chat System for a project as an assignment in Node Js and I am a beginner at Node JS ..Can anyone help me where should i start off Node js??? Any good books and tutorials ?? I am using django .. -
No module named django_auth_ldap
I have deployed application on apache2 server (on ubuntu), virtualenv, using python 3.5, these are installed apps in my virtualenv: All works fine until app is going to use django_auth_ldap package - it is installed as you can see in the picture. apache error.log is 'says' : No module named 'django_auth_ldap'. My settings.py: .... INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'my custom apps' ) .... #ldap conf AUTH_LDAP_SERVER_URI = "ldap://myhost:port" AUTH_LDAP_USER_DN_TEMPLATE = "..." AUTH_LDAP_BIND_AS_AUTHENTICATING_USER = True AUTH_LDAP_USER_ATTR_MAP = { ... } AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) Am I missing something? -
Django is retuning Imagefield path with domain url : Rest API
def upload_location(instance, fileName): extension = fileName.split('.')[-1] random_string = 'IMG-' + datetime.datetime.now().strftime("%Y%m%d-%H%M%S") filename = "images/" + Event._meta.app_label + "/" + random_string + "." + extension return filename class Event(models.Model) : eventId = models.AutoField("Event Id", primary_key=True) eventCoverImage = models.ImageField('Cover image', upload_to = upload_location) def __str__(self): return self.eventTitle class EventDetail(RetrieveUpdateDestroyAPIView): serializer_class = EventSerializer def retrieve(self, request, *args, **kwargs): instance = Event.objects.get(pk=kwargs['eventId']) serializer = self.get_serializer(instance) response = { "status" : status.HTTP_200_OK, "message" : APIConstants.EVENT_DETAIL, "response" : serializer.data } return Response(response) Here is my model and view code. What issue i'm facing is when i'm calling list API it returning Correct response like below { "eventId": 1, "eventCoverImage": "/media/images/IMG-20160924-055658.png", } But in detail list it's returning response with the server domain URL which i don't require { "eventId": 1, "eventCoverImage": "http://192.168.0.113:8000/media/images/IMG-20160924-055658.png", } It was an issue in list API too because i was passing request in context object and updated it with the user object only but in detail i'm not event passing context still its giving issue. in log i have seen than context is passing by default. RetrieveUpdateDestroyAPIView is passing and that why it's giving issue i guess. Is there any way to get out of it? -
Following a tutorial that helps in extending user model. Issue with setting up a property
I am following a tutorial that shows how to extend a User Model using a one to one relationship.I am using Django 1.10 This is what my model looks like so far and suggested by the tutorial class UserProfile(models.Model): user = models.OneToOneField(User) likes_cheese = models.BooleanField() puppy_name = models.CharField(max_length=20) User.profile = property(lambda u : UserProfile.objects.get_or_create(user=u)[0]) #--->Statement A This is what my form looks like class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ('likes_cheese','puppy_name') This is what my view looks like that serves the form looks like (I simply want to display the form and not process it) def user_profile(request): display_page = "register.html" csrf_token = csrf(request) args={} user = request.user profile = user.profile #----->statement B form = UserProfileForm(instance=profile) args.update(csrf_token) args["form"] = form return render_to_response(display_page,args) Now I get an exception on statement B. No such table as UserProfile_userprofile My question is why am I getting this error ? From what I understand from the code is that user.profile is a property added in the models whose getter is a lambda function that takes in one parameter. User.profile = property(lambda u : UserProfile.objects.get_or_create(user=u)[0]) There are a couple of things I dont understand 1 - From what I understand the property getter requires a … -
Mezzanine - static fiels now showing in production environment
I am new learner, for Mezzanine. I was made one site in development environment n it's working fine ! Now, next step is deploy it and make it live. For that, I was used fabric. It's installed and configure all necessary components. and I start server and problems begin !!! Problem is : Each pages loading fine but there are no any static files loaded ! Debug is False. What any other necessary setting left? I just one step back to live it ! I was setup server on RaspberryPi with debian type linux. Any one pleas suggest me or explain it because I am working on this problem with last 2 nights. Any video tutorial regarding deployment ??? I am also putting 2 more images... django_trekmunk -- where I was developed application and fire command fab all mezzanine -- It's created by fab all as a virtual env Thank You. -
elasticsearch-py 2.4.0 for python does not contain delete_by_query() function.
elasticsearch-py 2.4.0 for python does not contain delete_by_query() function. So How can I delete documents based on the query in elasticsearch 2.4.0 library? -
How to secure APIs for Registration and Login in Django Rest Framework?
I have been and nowadays may be almost every Django Framework users using Django Rest Framework for creating REST APIs. I am using it with token authentication using django-rest-framework-jwt and it returns the token when User logged in through our rest API. So the question is how to secure any registration or login views for our API endpoints.Any high-level XSS scripts can have malicious looping for creating registrations.How can we secure it in Django Rest Framework ? -
Invalid pk - object does not exist DRF in CreateAPIView
STFB, I have a view which inherits CreateAPIView. My View looks like this :- queryset = MyModel.objects.all() serializer_class = MyModelSerializer authentication_classes = [AUTH] permission_classes = [Authe2, Permissions] def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) print serializer.data data = {"detail": "Failed"} if serializer.data.field != True: return Response(data, status=status.HTTP_400_BAD_REQUEST) data = {"detail": "Wooho success"} return Response(data, status=status.HTTP_200_OK) And my respective serializer looks like :- file_number = SerializerMethodField() filer_number = SerializerMethodField() class Meta: model = MyModel fields = ("mission", "file_number", "filer_number", "status",) read_only_fields = ("status",) def validate(self, attrs): mission = attrs['mission'] is_relationship_valid = ThiefMission.objects.filter(pk=mission, player_id=self.context['request'].user.player.pk).exists() if is_relationship_valid: return attrs raise ValidationError(UNAUTHORISED_MISSION_MESSAGE) def get_file_number(self, obj): return obj.get_file_number() def get_filer_number(self, obj): return obj.get_filer_number() Now when i add a test case for these API, what i wanted to to test is that validate method of serializer should raise an exception in case Mission and player are related to each other OR we can say there is no corresponding entry for both of them in given ThiefMission model. No issue is when i test it using something like response = self.client.post(self.url, self.incorrect_payload, format="json") response_data = response.data self.assertEqual(response_data["detail"], UNAUTHORISED_MISSION_MESSAGE) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) It throws an error because response_data that is coming out is {'thief_mission': [u'Invalid pk … -
django upload multiple file and then save the path to database
I want to upload multiple image files using form, and the images then save in the ./static/, the path of the images then save to database, when I use request.FIELS/getlist("files") in for, when using the save(), there is only one image's name save in databse, and the real images not save in the ./static/ -
I need to know what this line of code does in django
I have been given this django project. I have been trying to run it and figure it out. I have a view: @csrf_exempt def view(Request,viewName,id): print '-------------------start ' + str(datetime.datetime.now()) try: c = globals()[viewName](viewName, viewName, None, Request, id) data = c.render() print '-------------------end ' + str(datetime.datetime.now()) return data except Exception as ex1: print '----------------' print print 'Error in importing View: %s.' % viewName print ex1 print traceback.format_exc() print '----------------' print '-------------------end ' + str(datetime.datetime.now()) return HttpResponse() What I need to know is what the fifth line does since I get a KeyError Exception there: c = globals()[viewName](viewName, viewName, None, Request, id) -
Django apps integration and model extension
I'm working on small ERP-like project on Django which contains different apps (Products, Sales, Purchases, Accounting, MRP, ...). A few of them are "base-level", while others have dependencies (for example, Sales requires information in Products). For the sake of modularity and loose-coupling, I'm trying to keep the apps as independent as possible: those with dependencies aren't allowed to modify the underlying data. However, it would be extremely useful and make things way simpler if those "higher hierarchy" apps could extend (add fields) some tables in the models of their dependencies (for instance, Sales would add a can_be_sold BooleanField in one of the tables within the scope of Products). This way when a user internally chooses to install an app, a setup function makes the required "upgrades" for it to integrate properly with the dependencies, while the user installs only what he needs without having to provide unnecessary or unrelated information. What is the best way to achieve this? Are there better approaches? Thanks!