Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Force exception to be raised when setting invalid field on model instance
If I accidentally typo the field name on a model, I want to raise an exception rather than silently failing: obj = MyModel() obj.fieldsdoesnotexist = 'test' # No exception is raised How can I make Django raise exceptions when setting invalid fields? -
count data using ajax
data:{ longitude:$('#x').val(), latitude:$('#y').val(), ***NUAVs:$('#NUAV').val(),*** Time:$('#Time').val(), } } how can I get the NUAVs (number of UAVs from the ID of UAVs)? I have not an attributes NUAVs in my django model, I have only IdUAV -
Django FieldError at / Unknown field(s) (type) specified for Model
I have a FieldError at / Unknown field(s) (type) specified for Model My model: class SocialNetwork(models.Model): contact = models.ForeignKey(Contact, related_name='social_networks') handle = models.CharField(max_length =50) types = models.CharField(max_length=20, choices = SOCNET_TYPES) public_visible = models.BooleanField(default=False) contact_visible = models.BooleanField(default=False) @property def url(self): prefixes = social_net_prefixes prefix = getattr(settings, '%s_PREFIX' % self.type.upper(), prefixes[self.type]) return '%s%s' % (prefix, self.handle) def __unicode__(self): return "%s %s: %s" % (self.contact.first_name, self.type, self.handle) my formModel: class SocialNetworkForm(ModelForm): class Meta: model = SocialNetwork fields = ('handle', 'type', 'public_visible', 'contact_visible') what am I doing wrong ? -
How to add class label ul CheckboxSelectMultiple django
MY FORM 'warranty': forms.CheckboxSelectMultiple(attrs={'class': 'list-inline'}), MY TEMPLATE <div class="col-md-12" style="height: 50px; width: 900px;"> <label class="list-inline col-xs-6" for="{{form2.warranty.name}}" style="width: 140px; padding-right: 20px;padding-left: 20px;">{{ form2.warranty.label }}</label> {{ form2.warranty}} </div> Result <ul id=id_class> <li class="list-inline id="id_warranty_1" name="warranty">opcion 1</li> <li class="list-inline id="id_warranty_2" name="warranty">opcion 2</li> <li class="list-inline id="id_warranty_3" name="warranty">opcion 3</li> </ul> But I need my class LIST-INLINE on the <ul class="MYCLASS" id=id_class> <li class="list-inline id="id_warranty_1" name="warranty">opcion 1</li> <li class="list-inline id="id_warranty_2" name="warranty">opcion 2</li> <li class="list-inline id="id_warranty_3" name="warranty">opcion 3</li> </ul> PROBLEM ACTUAL Current unwanted result desired result desired result -
Django-material : from material.forms ImportError: No module named forms
I'm trying to test an apps that use material.forms but i got this error:- from material.forms import ModelForm, InlineFormSetField ImportError: No module named forms Did i miss something? -
django-easy-pdf 'NotImplementedType' object is not iterable
I've followed as in their documentation but shows 'NotImplementedType' object is not iterable at line number 184 picture below when using @font-face or @import in css. How can I fix the issue. I'm using - python 3.5 django 1.10.6 easypdf xhtml2pdf --pre reportlab -
Required field only when editing
I'm using a ModelForm in Django app. This form is used to set a value and again to change it. When changing it, a reason needs to be specified, but not when setting it. I change the display of the field 'reason' to none when the value is None, but since the field is required, the user can't submit the form because the field is not filled. When clicking on confirm: Also, when editing, the value is pre filled, it also displays an error because the 'reason' field is not filled. Before clicking anywhere: What can I do so that the field is only required when editing? -
How to generate thumbnail for file. File can be Image or Video file
I am creating an album with following fields: album_name = models.CharField() file = models.FileField() where file can be either image or video. I am developing rest api in django. I am facing problem in generating thumbnail for the file(if it is a video). How to generate thumbnail for video file? -
rename and move a uploaded file in django template
I want to rename and move user uploaded image but i dont khow about rename uploaded file and move it. my code: upload.html <form action="../validupload/" method="POST" enctype="multipart/form- data"> {% csrf_token %} <p> <input id="id_image" type="file" name="image"> </p> <input type="submit" name="send" value="send" /> </form> my urls.py : url(r'upload_image', views.upload_image, name='upload_image'), url(r'validupload/', views.valid_upload, name='valid_upload'), my views.py : def upload_image(request): if 'username' in request.session: return render( request, 'mrdoorbeen/upload_image/index.html',{'username' : request.session['username']}) else: return HttpResponseRedirect('/login/') def valid_upload(request): if 'username' in request.session: return HttpResponse(request.FILES['image'].size/1000) *** i want to rename uploaded image here and move to a folder*** *** no*** **add to db now** #file.name # Gives name #file.content_type # Gives Content type text/html etc #file.size #give size else: return HttpResponseRedirect('../login/') if there is a progect on github or in doc.django say to me .or if there is a function say me.i nneed you help .tnx a lot. -
Heroku Django translations
I am using rosetta in my Django app. I have set all the translation strings and it is working with my local environment. The problem is when I push the code to heroku, I get the error: CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed. when running the code heroku run python manage.py makemessages -l en -
Django getting a model from another model
I have two models, a Author and a Article. Each Article is needs to refer back to its Author so I can access its values in my template. What is the most efficient way of doing this? class Author(models.Model): name = models.CharField(max_length=256) picture = models.CharField(max_length=256) class Article(models.Model): title = models.CharField(max_length=256) author = #The Author model that wrote this article date = models.DateTimeField(default=datetime.now) body = models.TextField() -
Invalid block tag - bootstrap-form, expected endblock
I am working on a django project, but for some reason the template I am using brings up an invalid block tag error. I have looked at some other similar questions, but nothing seems helpful, so if you can see the problem please do tell me.Here is the template: {% extends "learning_logs/base.html" %} {% load bootstrap3 %} {% block header %} <h2>Register an account.</h2> {% endblock header %} {% block content %} <form method="post" action="{% url 'users:register' %}" class="form"> {% csrf_token %} {% bootstrap-form form %} {% buttons %} <button name="sumbit" class="btn btn-primary">register</button> {% endbuttons %} <input type="hidden" name="next" value="{% url 'learning_logs:index' %}" /> </form> {% endblock content %} Thanks, Milo -
filter data in django model form factory
i am new in django, try to put a dropdown from the given model, class Account(DomainEntity): name = models.CharField(max_length=60) hotel = models.ForeignKey(Hotel) account_type = models.CharField(choices=ACCOUNT_TYPE, max_length=30) def __unicode__(self): return self.name class Meta: unique_together = (('name', 'hotel'),) i.e trying to create dropdown of name field values but per hotel wise,see there is a foreign field hotel, initially my view was something like this(not aware of having hotel wise name field value in drop down) @staff_only def account_list(request, hotel): form = modelform_factory(Account, exclude=['hotel'])() return render(request, 'pms/domains.html', {'hotel': hotel,'form': form, 'page': 'account'}) here i have used modelform_factory and its returning name field values of all hotel,but i need a hotel wise filtered drop down of name field values. i don't find any way to filter data here(per hotel wise) in modelform_factory.So i have decided to use django model form. Is there any way to filter data using django model form? -
import numpy into flask app
I'm was trying to run my python code on a web server and found out i have to use flask or django so I decided to use flask and after reading some articles i wrote a hello world script and it ran but when i tried do more complex things like import numpy and pandas I kept giving me internal server errors and I have googled it but haven't got what I wanted. Please is this possible with flask or is there a better way to run my script online and am still a new to this. Thank you in advance. This is the script am trying to run import numpy as np import pandas as pd from flask import Flask app = Flask(__name__) @app.route("/") def hello(): file = pd.read_csv('movies.csv') print('man') if __name__ == "__main__": app.run() This is the logs * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) man [2017-03-12 22:12:06,757] ERROR in app: Exception on / [GET] Traceback (most recent call last): File "C:\Users\hp\AppData\Local\Programs\Python\Python35\lib\site-packages\flask\app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "C:\Users\hp\AppData\Local\Programs\Python\Python35\lib\site-packages\flask\app.py", line 1615, in full_dispatch_ request return self.finalize_request(rv) File "C:\Users\hp\AppData\Local\Programs\Python\Python35\lib\site-packages\flask\app.py", line 1630, in finalize_request response = self.make_response(rv) File "C:\Users\hp\AppData\Local\Programs\Python\Python35\lib\site-packages\flask\app.py", line 1725, in make_response raise ValueError('View function did … -
Reduce traffic by moving json data to url
I'm begginer to develop API in django rest framework. I want to create API for app mobile. For reduce traffic I need to delete "user_id" from json and determinate it from url. How can i do it? url: urlpatterns = [ url(r'^measurement/(?P<user>\d+)$', views.usermeasurement), ] model class UserMeasurement(models.Model): user_id = models.IntegerField(blank=True, null=True) numb = models.DecimalField(max_digits=20, decimal_places=10, blank=True, null=True) measurent_code = models.CharField(max_length=50, null=True) def __unicode__(self): return self.sync_id def save(self, *args, **kwargs): return super(UserMeasurement, self).save(*args, **kwargs) class Meta: managed = False db_table = 'user_measurement' Serializer: class UserMeasurementSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UserMeasurement fields = ('user_id', 'numb', 'measurent_code',) views: def usermeasurement (request,user): try: usermeasurement = UserMeasurement.objects.filter(user_id=user) except UserMeasurement.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) elif request.method == 'POST': uv = UserMeasurement(user_id=user) serializer = UserMeasurementSerializer(uv, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Staticfiles don't load when deploying django app with prefix
I'm trying to deploy django application together with wordpress under the same domain. Django app should be under a suburl: "domain.com/djangoapp". I tried to set SCRIPT_NAME variable to that prefix in nginx conf file as well as in django settings.py. It worked and django app can be accessed under /djangoapp url, but staticfiles don't load. I have the following nginx configuration: server { server_name domain.com www.domain.com; root /var/www/domain.com/htdocs; index index.php index.html index.htm; include common/redis.conf; include common/wpcommon.conf; location /static { root /home/user/project; } location /djangoapp/ { include proxy_params; proxy_pass http://unix:/home/user/project/project.sock proxy_set_header SCRIPT_NAME /djangoapp; } } and settings.py: FORCE_SCRIPT_NAME = '/djangoapp' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Also I tried to deploy django app on a separate domain and there staticfiles do load. The configs were the same except SCRIPT_NAME parts. Can somebody help? -
Simplify multiple conditioned filters query in Django
I have something like this: if year: if year and max_speed: cars = Car.objects.filter(brand=brand,year=year,max_speed=max_speed) else: cars = Car.objects.filter(brand=brand,year=year) This could become even more complex, having a bunch of "if" and "for" everywhere and duplicated code. Is there a way to simplify this? -
django url resolvers reverse lookup
NoReverseMatch I'm trying to make a basic website with the following urls /congregation/ - home page /congregation/archives - archives for that page There are multiple 'congregations', each with an archive page. I have the following url patterns: church/urls.py urlpatterns = [ url(r'^admin/', admin.site.urls, name='admin'), url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), url(r'^', include('congregation.urls', namespace='congregation')), ] church/congregation/urls.py page_patterns = [ url(r'^$', CongregationView.as_view(), name='home'), url(r'^archive/', SermonList.as_view(), name='archive') ] urlpatterns = [ url(r'^(?P<congregation>\w{3,20})/', include(page_patterns, namespace='page')) ] The pages display as I expect they should, but if I use links in header nav-bar, reverse lookup fails with this message NoReverseMatch at /spokane/archive/ Reverse for 'archive' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['(?P<congregation>\\w{3,20})/archive/'] The error is caused by an invalid reverse match in the template <li class="{% if request.resolver_match.url_name == 'archives' %}active{% endif %}"> <a href="{% url 'congregation:page:archive' %}">Archives</a></li> I'm sure it's simple, but I'm having difficulty finding the solution. Thank you! -
django rest framework - object permission does not trigger
I have the following setup: permission.py def get_permission_level(request, obj): try: level = PasswordListACL.objects.get(list=obj, user=request.user) except PasswordListACL.DoesNotExist: level = None return level class IsPasswordListOwner(permissions.DjangoObjectPermissions): def has_permission(self, request, view): return True def has_object_permission(self, request, view, obj): print(get_permission_level(request, obj)) if get_permission_level(request, obj) == None: print('false') return False else: level = AccessLevel.objects.get(pk=get_permission_level(request, obj).level_id).name if level == 'Owner': return True else: return False I can confirm through my print('false') that the permission is being acted on and it is returning the correct value (I'm expecting False) however the view is still returning the data instead of a 403. views.py class PasswordListViewSet(viewsets.ModelViewSet): queryset = PasswordList.objects.all() serializer_class = PasswordListSerializer permission_classes = (IsPasswordListOwner,) def list(self, request): self.permission_classes = [IsPasswordListOwner, ] queryset = self.get_queryset().filter(passwordlistacl__user=request.user) serializer = PasswordListSerializer(queryset, many=True, context={'request': request}) return Response(serializer.data) def retrieve(self, request, pk=None): self.permission_classes = [IsPasswordListOwner, ] queryset = self.get_queryset() if get_object_or_404(queryset, pk=pk): password = get_object_or_404(queryset, pk=pk) else: pass serializer = PasswordListSerializer(password, context={'request': request}) return Response(serializer.data) -
Django Rest Framework - try/except permission on None
I'm trying the below code. What is happening is level returns as None in the function get_permission_level which is good. Unfortunately when I try to pass it in the try/except in has_object_permission I get the following Traceback: File "D:\Projects\myapp\api\core\permissions.py" in has_object_permission 21. level = AccessLevel.objects.get(pk=get_permission_level(request, obj).level_id).name Exception Type: AttributeError at /api/v1/passwordlists/1/ Exception Value: 'NoneType' object has no attribute 'level_id' Code: def get_permission_level(request, obj): try: level = PasswordListACL.objects.get(list=obj, user=request.user) except PasswordListACL.DoesNotExist: level = None return level class IsPasswordListOwner(permissions.DjangoObjectPermissions): def has_permission(self, request, view): return True def has_object_permission(self, request, view, obj): try: level = AccessLevel.objects.get(pk=get_permission_level(request, obj).level_id).name if level == 'Owner': return True except AccessLevel.DoesNotExist: return False -
Shift Queryset result
all. Got a little problem with my Queryset result iwhanna shift it by wayve effect. menus = ShopMenu.objects.filter(shop=shop_id) he is return result for my: 1 --- 2 --- 3 --- 4 --- But that's not really what I need. I would like to receive 4 ---- 1 --- 2 --- 3 --- Haw i can get that result? -
Django : Migrate the test database to original database
I wrote a simple django web and use a test database with db.sqlite3, but I'll migrate it to the original database on MSSQL. I tried MSSQL document, but what should I do to modify my model.py and admin.py after migrating it? Has anyone experienced on it? -
Django import issue in Pycharm
I am trying to set up a remote django server on pycharm in my local machine. The problem I am facing is I am getting this error:- "ImportError: No module named settings". I have given all the server configurations correct in pycharm. When I run the same from the server, it works perfectly fine. I was using Sublime Text before this and everything works fine there, but since I wanted breakpoints and running a remote server locally, I moved on to the full-blown version of Pycharm. Please help me if anyone knows what is the issue here!! -
Why do I receive a django error when trying to create a model instance with a foreign key?
I am receiving the following error: ValueError: Cannot assign "u'ben'": "Entry.author" must be a "MyProfile" instance. From this line: form.author = request.session['username'] Note: Entry.author is a foreign key as seen below. models.py class MyProfile(models.Model): user = models.CharField(max_length=16) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) def __unicode__(self): return u'%s %s %s' % (self.user, self.firstname, self.lastname) class Entry(models.Model): headline= models.CharField(max_length=200,) body_text = models.TextField() author=models.ForeignKey(MyProfile, related_name='entryauthors') def __str__(self): return u'%s %s %s' % (self.headline, self.body_text, self.author) The error says Entry.author must be a "MyProfile" instance, but when I go into the django shell and run a query, I see an instance exists with username ben. <QuerySet [<MyProfile: ben ben 97201 None>]> I am now wondering if request.session['username'] is maybe not returning a correctly formatted username and I have no way to test this (that I know of) in the django shell because I don't think you can access the request object from the shell. In my login form, I have this line which is passing the username to the request.session. if form.is_valid(): username = form.cleaned_data['username'] request.session['username'] = username -
Dynamic URL with ShareThis
I have a page with users' photos. Each photo is in a card. I would like to allow users to share each picture separately. This is my html: <div class="sharethis-inline-share-buttons" data-url="http://{{recent.photo.url}}" data-title="Check out this picture by {{uploaded_by}}"></div> But it only shares the base website (http://myexample/photopage/) I see I could also use or javascript, but it doesn't look like that allows for sharing different links within a page. Thanks