Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the exact usage of exists()?
I am using it as if ModelName.objects.get(fieldname=value).exists(): I either get the error 'ModelName' object has no attribute 'exists' or it throws a DoesNotExist exception. Related doc: https://docs.djangoproject.com/en/1.10/ref/models/querysets/#django.db.models.query.QuerySet.exists -
Django all-auth - is it possible to do graph request to Facebook?
I have Django with all-auth. Is is possible using token, that persists in socialtoken, table to perform requests to Facebook Graph API ? -
Accessing a List out of order in Jinja
I have setup the following list of lists being passed through to my Jinja template: [(u'2nd Principle', 1, 1, 3, 33, 1, 100), (u'Test Principle', 1, 2, 6, 33, 1, 100)] And thus far I am handling displaying this in a table as follows: <tbody> {% for p in performance %} <tr> {% for a in p %}<td>{{ a }}</td>{% endfor %} </tr> {% endfor %} </tbody> This works perfectly in printing out each of the lists as a row. However, I have been trying to work with the same list in a different view where I want to show one less item and in a different order. However, the following does not seem to work for me: <tbody> {% for p in performance %} <tr> <td>{{ p[6] }}</td> <td>{{ p[1] }}</td> <td>{{ p[3] }}</td> <td>{{ p[2] }}</td> <td>{{ p[5] }}</td> <td>{{ p[6] }}</td> </tr> {% endfor %} </tbody> The above throws the following error: Could not parse the remainder: '[6]' from 'p[6]' How do I access list items directly without looping through it? -
Accepting input in Django ListView
In a Django website, I have a paginated ListView that shows a listing of certain objects, 100 per page. I want to include a text box on this page and accept+process user input. But in Django, this would require me to either: i) Use a FormView (in which case I lose pagination), or ii) Write non-cbvs where I handle pagination and form processing manually. Is there a third way to achieve what I'm trying to do, ideally without disrupting the ListView? -
Best way to draw django grafient bar in view - looking for python library
Ma goal is to draw progress bar like this: http://kottenator.github.io/jquery-circle-progress/ , but not in js but without animation. Must be static. Django view function must returns it as http response with content type 'image/png' or 'image/jpg' And I need gradient colours inside bar area. My final goal is to use it in facebook og:image content. And I want to do this without saving file on a drive. Image must be created dynamically. I tried do this as image with base64 code (as img src), but facebook did not respect it. Any suggestions? Thank you. -
django import export M2M field, TypeError: coercing to Unicode: need string or buffer, NoneType found
i have test models, i need m2m field import from excel class T1(models.Model): t1 = models.CharField(max_length=255, null=True, blank=True) def __unicode__(self): return self.t1 class T3(models.Model): t3 = models.CharField(max_length=255, null=True, blank=True) def __unicode__(self): return self.t3 class T2(models.Model): t2 = models.CharField(max_length=255, null=True, blank=True) t1 = models.ForeignKey(T1) t3 = models.ManyToManyField(T3) def __unicode__(self): return self.t2 i tried to create a custom m2m widget but i get TypeError: coercing to Unicode: need string or buffer, NoneType found class T1FkWidget(ForeignKeyWidget): def clean(self, value, row): try: val = self.model.objects.get(t1= value) except self.model.DoesNotExist: val = self.model.objects.create(t1=value) return val def render(self, value, row): return value.t1 class T3M2MWidget(ManyToManyWidget): def __init__(self, model, m2mfield, separator=u', ', field='pk', defaults=None, create=False, *args, **kwargs): self.model = model self.m2mfield = m2mfield self.separator = separator self.field = field self.defaults = defaults self.create = create super(T3M2MWidget, self).__init__(self.model, separator=self.separator, field=self.field, *args, **kwargs) def clean(self, value): values = filter(None, value.split(self.separator)) if self.create: results = [self.model.objects.get_or_create(defaults=self.defaults, **{self.field: v})[0] for v in values] caller_frame = inspect.stack()[1].frame caller_args = inspect.getargvalues(caller_frame) data = caller_args.locals['data'] this_row = data[self.field] existing_obj = self.model.objects.get(**{self.field: this_row}) existing_related = getattr(existing_obj, self.m2mfield).all() existing_related_objs = [self.model.objects.get(**{self.field: r}) for r in existing_related] combined_results = results + list(set(existing_related_objs) - set(results)) return combined_results else: try: val = super(T3M2MWidget, self).clean(value) except ObjectDoesNotExist: model_name = self.model.__name__ error = β¦ -
How to handle Django connection loss with database gracefully?
I am no database expert. I need a very basic solution to handle Django connection loss with my Oracle database. I want to handle the exception and display overall site and empty tables with message that db connection is lost. What is the most painless way to do this? Any help is appreciated. -
MobileApp Architecture: Allow Client to Class a server class through an API
I am working on capstone project and I am looking for ideas to implement this one. I have a working web application that was created using OpenCV Python and deployed on a Django Framework. Now I want to also create a hybrid mobile application for the project. The idea is, the mobile app will allow the user to upload an image to the server, and then the web server will process the image then finally return a response to the mobile app. =============================== Client (Mobile app): Take image and upload it to database View HttpResponse from server Web server: Save image to Django Model Call Image Processing class (views.py) Return HttpResponse to Client ============================ I know that it is possible to save an image to the database through REST API, however, I have no idea if it is possible for the client side to call a class from the server side through REST API? If no, then is there any other way to implement this method? Do know any references that can give me some ideas on how to implement it? -
Customize query in forms with specific arguments for ManyToManyField in Django
I have an app called projects. One of the fields is contributors where list of users is stored with ManyToManyField. I'm trying to make it possible to add and remove users to and from the list. Adding has been fairly easy using ModelChoiceField with passed query set of all users. Removing a user from the list still eludes me. What I'm trying to understand is how and where to pass additional arguments so that I can process the query in form, so it would list only users from a specific project. Adding user models.py # Model for projects class Project(models.Model): ... contributors = models.ManyToManyField(User, blank=True) ... forms.py class AddUserForm(forms.Form): user = forms.ModelChoiceField(queryset=User.objects.all()) class Meta: model = Project fields = [ "user", ] views.py # Add task to a project @login_required() def projects_adduser(request, id): # Fetch the project if it exists project = get_object_or_404(Project, id=id) # Form for adding users to contributors list form = AddUserForm(request.POST or None) # Validate the form if form.is_valid(): user = form.cleaned_data.get("user") project.contributors.add(user) project.save() messages.success(request, "User successfully added to project!") return HttpResponseRedirect(project.get_edit_url()) # Context dict to return for template context = { "title": "Add user to project: " + project.title, "form": form, "instance": project, } return β¦ -
Strange Django session KeyError
I am learning to use sessions in Django. Here is simple code that I wrote. It was working yesterday, however, I keep getting KeyErrors 'score' today. Where is the problem? def home(request): request.session.get('score',0) if request.GET.get('add'): request.session['score'] += 1 if request.GET.get('restart'): request.session['score'] = 0 return render_to_response('home.html', {'zero':request.session['score']}) -
Using pip to install MySQLdb error on Mac OS X 10.12
I am current using Mac OS X 10.12.I am trying to install MySQLdb but kept getting these error. When I running sudo pip install MySQLdb,the error message is: Collecting MySQL-python Downloading MySQL-python-1.2.5.zip (108kB) 100% |ββββββββββββββββββββββββββββββββ| 112kB 233kB/s Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/tmp/pip-build-m1bhp0l0/MySQL-python/setup.py", line 13, in <module> from setup_posix import get_config File "/private/tmp/pip-build-m1bhp0l0/MySQL-python/setup_posix.py", line 2, in <module> from ConfigParser import SafeConfigParser ImportError: No module named 'ConfigParser' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-build-m1bhp0l0/MySQL-python/ and then I try to download MySQL-python-1.2.4b4, and use that to directly running setup.py.Then I got this error: Traceback (most recent call last): File "/Users/phil/Downloads/MySQL-python-1.2.4b4 2/setup.py", line 18, in <module> metadata, options = get_config() File "/Users/phil/Downloads/MySQL-python-1.2.4b4 2/setup_posix.py", line 32, in get_config metadata, options = get_metadata_and_options() File "/Users/phil/Downloads/MySQL-python-1.2.4b4 2/setup_common.py", line 12, in get_metadata_and_options metadata = dict(config.items('metadata')) File"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ConfigParser.py", line 642, in items raise NoSectionError(section) ConfigParser.NoSectionError: No section: 'metadata' Tried lots of solutions out there.Still got lots of errors. Plz help here. -
UpdateView gives blank form in django inline formset
MY CreateView worked fine but when I try to update this form data, it gives blank form. No data was shown. Here is my views.py: @require_authenticated_permission( 'member.add_person') class PersonCreate( FormsetMixin, CreateView): template_name = 'member/person_form.html' model = Person form_class = MemberForm formset_class = PersonFormSet @require_authenticated_permission( 'member.change_person') class PersonUpdate( FormsetMixin, UpdateView): template_name = 'member/person_form.html' model = Person form_class = MemberForm formset_class = PersonFormSet Here is my formset: class MemberForm(ModelForm): class Meta: model = Person exclude = ('user',) def __init__(self, *args, **kwargs): super(MemberForm, self).__init__(*args, **kwargs) self.fields['name'].widget.attrs['placeholder'] = 'Your full name' self.fields['tele_land'].label = 'Land phone' self.fields['tele_cell'].label = 'Cell phone' self.fields['passing_year'].label = 'Passing year' self.fields['passing_year'].help_text = 'According to your session year' def save(self, request, commit=True): person = super().save(commit=False) if not person.pk: person.user = get_user(request) if commit: person.save() self.save_m2m() return person class ChildrenForm(ModelForm): class Meta: model = Children fields = '__all__' PersonFormSet = inlineformset_factory(Person, Children, extra=0, min_num=1, fields=('child_name', 'child_birth_date','blood_group' )) Url: url(r'^person/create/$', views.PersonCreate.as_view(), name='person-create'), url(r'^person/(?P<slug>[\w\-]+)/update/$', views.PersonUpdate.as_view(), name='person-update'), My formset mixin: class FormsetMixin(object): object = None def get(self, request, *args, **kwargs): if getattr(self, 'is_update_view', False): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) formset_class = self.get_formset_class() formset = self.get_formset(formset_class) return self.render_to_response(self.get_context_data(form=form, formset=formset)) def post(self, request, *args, **kwargs): if getattr(self, 'is_update_view', False): self.object = self.get_object() form_class = β¦ -
excluding id field in an inline formset when saving
I have two models, connected by a foreign key. One is an inline formset. For some reason, the formset ids are being identified as Primary Keys in the database, and every time the form is submitted, the table belonging to the formset is basically overwritten. When saving, how do I ignore the formset ids models.py class Student(models.Model): first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) email = models.EmailField() class Courses(models.Model): student = models.ForeignKey(Student) course_name = models.CharField(max_length=40) start_time = models.TimeField() forms.py class CoursesForm(forms.ModelForm): class Meta: model = Courses exclude = ("student",) class StudentForm(forms.ModelForm): class Meta: model = Student fields = "__all__" views.py ... def post(self, request, *args, **kwargs): sform = StudentForm(request.POST, instance=Student()) CourseSchedule = inlineformset_factory(Student, Courses, form=CoursesForm, can_delete=False, extra=0, min_num=1) cforms = CourseSchedule(data=request.POST) if sform.is_valid() and cforms.is_valid(): sform_obj = sform.save() for cform in cforms.forms: cform_obj = cform.save(commit=False) cform_obj.student = sform_obj cform_obj.save() .... -
Trying to filter based upon a value in another table
I have 2 tables as class ItemFollowers(models.Model): item = models.ForeignKey(Items, models.DO_NOTHING, db_column='item') user = models.ForeignKey(AuthUser, models.DO_NOTHING, db_column='user') And the other one is class UsrPosts(models.Model): item = models.ForeignKey('Items', models.DO_NOTHING, db_column='item') # Some other fields How can I select the UsrPosts related to the items followed by some user? i.e. I can have records in ItemFollowers like (item0, user0), (item1, user0), (item5, user0). I need to filter UsrPosts based upon the user (aka. request.user.id) Here is a inefficient non-working way to get UsrPostts itms = ItemFollowers.objects.filter(user_id=request.user.id) qry = Q(item_id=itms[0].item.id) | ..... | Q(item_id=itms[N].item.id) posts = UsrPosts.objects.filter(qry) Is there some filter magic to get it in one transaction? -
Stripe API - calling specific values
I am running python 3.5, django 1.10. This is the 1st time I have used an api, and I am struggling to understand what to do. Yes, I am a noob. I am attempting to display stripe invoice details on a template page. I have been given some code that can display the basic information, but I am having difficulties displaying the plan name that the invoice relates to. I have included a screen shot of the invoice api displaying the necessary available details of the invoice, but I am unsure how to display the plan name (circled in red below): Here is my template code: {% for invoice in invoices %} <tr> <td>{{ invoice.date|date:'dS F, Y P' }}</td> <th style="display: none;">{{ invoice.stripe_id }}</td> <td>{{ invoice.period_start|date:'dS F, Y' }}</td> <td>{{ invoice.period_end|date:'dS F, Y' }}</td> <th style="display: none;">{{ invoice.charge }}</td> <td>{{ invoice.plan.name }}</td> <td>{{ invoice.paid|yesno:'Yes,No' }}</td> <td>{{ invoice.refunded|yesno:'Yes,No' }}</td> </tr> {% endfor %} Here is what the display looks like: I am hoping someone can push me in the right direction, to display the plan name. -
django-parler doesn't show tabs in admin
For some reason I'm not seeing any language tabs when adding to the admin. I'm using Django 1.9.10. I was using django-hvad but decided to try parler. I have tried the same exact code in a fresh project and it worked but in my existing project it doesn't. Please note that I'm also using django-mptt. Tried parler in separate from the mptt model and vice versa. settings/base.py # Translations gettext = lambda s: s LANGUAGES = ( ('en', gettext('English')), ('ar', gettext('Arabic')), ) LOCALE_PATHS = ( os.path.join(BASE_DIR, "locale"), ) # # Parler Configuration PARLER_LANGUAGES = { None: ( {'code': 'ar', }, {'code': 'en',}, ), 'default': { 'fallback': 'ar', # defaults to PARLER_DEFAULT_LANGUAGE_CODE 'hide_untranslated': False, # the default; let .active_translations() return fallbacks too. } } PARLER_DEFAULT_LANGUAGE_CODE = 'ar' Model class Category(MPTTModel, TranslatableModel): slug = models.SlugField(max_length=50, unique=True, null=True, blank=True) translations = TranslatedFields( title = models.CharField(max_length=90, unique=True, null=True, blank=True) ) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) parent = TreeForeignKey('self', null=True, blank=True, related_name='children') objects = CategoryManager() def __unicode__(self): return unicode(self.slug) or u'' def get_absolute_url(self): return reverse("category:detail", kwargs={"slug": self.slug}) class Meta: ordering = ["slug"] verbose_name = _("Category") verbose_name_plural = _("Categories") admin.py class CategoryAdminForm(MPTTAdminForm, TranslatableModelForm): pass class CategoryAdmin(TranslatableAdmin, MPTTModelAdmin): form = CategoryAdminForm def get_prepopulated_fields(self, request, obj=None): return {'slug': ('title',)} β¦ -
Django url template with a filter
I'm getting url reverse errors and think this line is to blame. {% if has_change_permission %} <a href="{% url 'opts|admin_urlname:changelist' %}"> {{ opts.verbose_name_plural|capfirst }}</a> {% else %}{ { opts.verbose_name_plural|capfirst }} {% endif %} Am I corect in placing the entire filter within single quotes or do I need a double quote around the changelist argument? -
Django permissions hiccup
I had all my static and media files working perfectly. However, when I wanted to create a new news article and therefore upload a new picture I got the following error: [Errno 13] Permission denied: At the following link I found: Django [Errno 13] Permission denied: '/var/www/media/animals/user_uploads' sudo groupadd varwwwusers sudo adduser www-data varwwwusers sudo chgrp -R varwwwusers /var/www/ sudo chmod -R 770 /var/www/ Now none of my static files will display on the site at str8red.com Can anyone help with getting the file permissions back and also allowing the webpage to allow upload of new images. Many thanks, Alan. -
How I can create a PointField using an api?
I am using django-rest-framework for the API, but when I make a post request sends me this error: { "location": [ "Invalid format: string or unicode input unrecognized as GeoJSON, WKT EWKT or HEXEWKB." ] } Body request: { "location":{ "type":"Point", "coordinates":[37.0625,-95.677068] } } My model is as follows: class Address(models.Model): location = geo.PointField(srid=4326, blank=True) objects = geo.GeoManager() My serializer is a follow: class AddressCreateSerializer(serializers.ModelSerializer): class Meta: model = Address fields = ('location') Help me please! -
Django Rest Framework 'RelatedManager' object has no attribute
The original error is: Got AttributeError when attempting to get a value for field `original` on serializer `ProductImageSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `RelatedManager` instance. Original exception text was: 'RelatedManager' object has no attribute 'original'. This is my models.py: class Product(models.Model): name = models.CharField(max_length=100, db_index=True) ean = models.CharField(max_length=13, db_index=True) ... class ProductImage(models.Model): product = models.ForeignKey(Product, null=True, related_name='images', on_delete=models.CASCADE, db_index=True) original = models.ImageField(upload_to=get_uuid_image) medium = models.ImageField(upload_to=get_uuid_image) small = models.ImageField(upload_to=get_uuid_image) The serializers: class ProductBasicSerializer(serializers.ModelSerializer): tags = TagSerializer(many=True) brand = BrandSerializer() images = ProductImageSerializer(required=False) class Meta: model = Product fields = ['tags', 'brand', "ean", "name", "quantity", "unit", "images"] class ProductImageSerializer(serializers.ModelSerializer): class Meta: model = ProductImage exclude = ("product",) And in the view: product = Product.objects.get(ean=ean) serializer = ProductBasicSerializer(product) Why do I get the error RelatedManager' object has no attribute 'original' ? The reverse relationship ProductImage, with related_name="images" does have the attribute original. -
Django rest framework create-only serializer field
I'm have a Django model that serves as a request description. It is created to issue a request by a REST client, serves to record the tasks current status, and record historical requests received by clients. This model has a few fields that are used to fine-tune and control the requested task (say, a target object and the type of action). Obviously, I'd like the client to control those fields on object creation but not afterwards (you can't change the object this task has started running on). I was hoping for something similar to serializers.ReadOnlyField, so I could have something similar to: class TaskSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') task_id = serializers.ReadOnlyField() target_object = serializers.CreateOnlyField() but couldn't find it in the documentation or google. -
combingin multiple country id's to the region they are associated with
I am currently trying to combine the list of countries id's to their region so when routed to the browser it shows up at "the region", #number of countries in that region. For example, I am currently getting western europe listed 9 times, instead of once with the number 9 next to it. How do I combine the two using django and sqlite3. below is an example of my code. countries = Countries.objects.values('region', 'id').order_by('-region') total_countries = Countries.objects.count() print(total_countries) print(countries.query) return render(req, 'worldApp/index.html', context={'countries':countries}) -
DJango admin filter many-to-many selection dynamically
This is a simplified version of my scenario: class test(models.Model) subjects = models.ManyToManyField(subject) questions = models.ManyToManyField(question) class subject(models.Model) class question(models.Model) subject_id = models.ForeignKey(subject) When adding a new test via the django admin page both the "subjects" and "questions" can be chosen using a multiple select box. I'm looking for a way to dynamically filter the "questions" box based on the selection from the subjects box. ie only display the questions related to the selected subjects -
Is there any working example/boilerplate of Django + REST + JWT?
It seems there's nothing available anywhere. I'd appreciate if anyone could point me at a working boilerplate of these. -
Inserting video in webpage - Path not found
I am attempting to play a video on my webpage and i am using the code below for testing <video width="320" height="240" controls> <source src="somepath/test.mp4 " type="video/mp4"> Your browser does not support the video tag. </video> However the code above does not work as chrome states that the video cannot be retrieved as it attempts to retrieve it from http://127.0.0.1:8000/somepath/test.mp4 How do I tell i tell it that it should looks into the directory structure and not try to retrieve it through a request.