Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django test discovery does not find non django test cases
I have am building an application that involves and some non-django functionality. I have an app 'wit' under the source directory that is a django application and that has test cases that are being deferred. src/wit/ test_django_file1.py, test_django_file2.py etc. But there are also test cases under that are not being discovered or run src/utils/ test_nondjango1.py and test_nondjango2.py When I run do cd src/ python manage.py test I am using django jenkins report coverage to get coverage reports. I would idealy like all the test cases to be invoked with one invocation so that over all code coverage reporting works. Or else I would like to know how to invoke separately if the above is not possibly so that I get to run all my test cases anyway. -
Refresh Django view using Ajax
I've been looking for the best way to asynchronously refresh the contents of a view in Django using Ajax but all posts I've come across on Google are either for forms or are terribly outdated. A quick example of what my view and template looks like. views.py def MyView(request): object = MyObject.objects.get(pk=1) return render(request, 'template.html', {'object': object}) template.html <body> {{ object.value1 }} {{ object.value2 }} {{ ... }} </body> My objective is to refresh the values every X seconds. So far I have in mind placing those values inside of a div and replacing the entire div on Ajax success, but it doesn't look like a pretty solution. I have also read about having two templates, and the main template updates the second which includes a div with the values, but I don't know how would that go. I've never tried it and the only explanation I found about it wasn't clear enough. Maybe something with JSON would be the best approach? Hopefully you can point me to what's the best practice for achieving this in Django. -
Updating object from a list of model objects in Django
I am new to Django and I am trying to create a single view which will list all the different objects of a particular model and then provide users with the option to update one/some of them. I am looking for thoughts on a general approach to go this. Just things like what type of mixins/viewsets or whatever else I could/should use. Any help is appreciated! -
Form from ModelAdmin
I have ModelAdmin with a few fieldset and inlines. I'd like to use form which ModelAdmin generate as form for advanced search (inside of admin site). Is there any simply way to reuse this form instead of overriding methods from ModelAdmin class? -
Oscar Dashboard requests /static/css/base.css instead of /static/oscar/css
I'm somewhat new to Django, but I have previously installed Django Oscar on it's own to test it out and it was working perfectly fine. However I'm now building a project which uses Django-Allauth with a Custom User Model, and I have installed Django-Oscar, however when I launch the Dashboard it doesn't load in it's entirety, (Screenshot of Dashboard) I see from the Run log that it currently requests my static/css/base.css, however when I launched it before I see it goes to /static/oscar/css to get it's stylesheets. I believe that this may be the problem (please let me know if you think otherwise). I've gone through my settings time and time again to see if there is an issue somewhere but I can't seem to pinpoint anything, so I wanted to post here in help of a resolution. Thanks in advance. Below is my settings.py posted: from oscar.defaults import * from oscar import OSCAR_MAIN_TEMPLATE_DIR from oscar import get_core_apps # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'Users', 'crispy_forms', 'widget_tweaks', 'allauth', 'allauth.account', 'allauth.socialaccount', # ... include the providers you … -
Django Nested To Do List
I'm learning Django and I've figured out how to create a model for my task and assign it to a user, but I don't how I can have sub-lists (and sub-lists of sub-lists) underneath Here is my model: class task(models.Model): name = models.CharField(max_length=100) notes = models.TextField() created = models.DateTimeField() created_by = models.ForeignKey(User) What is the best way to implement lists of lists of lists...? -
Foreward base URL to specific page with Django
I took over a Django web app from a coworker who quit. Currently users of the app have to type in a very long URL to login to the app and use it, like: http://myapp.company.com/djangoapp/mydir/login whereas the base (is that the correct term?) URL of http://myapp.company.com/ points to nothing. So now they would like http://myapp.company.com/ to automatically forward to http://myapp.company.com/djangoapp/mydir/login Sounds simple enough and I could do it with HTML or the Spring framework, but with Django I can't seem to figure this out. I have a feeling I need to edit urls.py but I'm not sure in what way to do so. I have access to the Django app and the server hosting it, but there's not like a cPanel or any simplifying tool like that to manage the domain. The domain itself is set up and owned by some unknown IT person in a department far, far away. -
Trouble overriding save method on Django model with ManyToManyField
I'm having trouble overriding the save method on a Django model to check a restriction on a many-to-many field. Say I have the following models: class Person(models.Model): name = models.CharField() class ClothingItem(models.Model): description = models.CharField() owner = models.ForeignKey(Person) class Outfit(models.Model): name = models.CharField() owner = models.ForeignKey(Person) clothing_items = models.ManyToManyField(ClothingItem) I would like to put a restriction on the save method of Outfit that ensures that each ClothingItem in a given outfit has the same owner as the Outfit itself. I.e. I'd like to write: class Outfit(models.Model): name = models.CharField() owner = models.ForeignKey(Person) clothing_items = models.ManyToManyField(ClothingItem) def save(self, *args, **kwargs): for ci in self.clothing_items: if ci.owner != self.owner: raise ValueError('You can only put your own items in an outfit!) super(Outfit, self).save(*args, **kwargs) but when I try that I get an error about <Outfit: SundayBest>" needs to have a value for field "outfit" before this many-to-many relationship can be used. Any ideas what's going wrong here? -
How to use @property in raw sql or add alias for the django ORM query
I used SQL query like this: SELECT ns.id, ns.title, ns.image, ns.briefDescr as description, ns.url, um.team_id as team FROM app_news ns INNER JOIN app_news_teams nsts ON ns.id = nsts.news_id INNER JOIN app_userteam um ON nsts.team_id = um.team_id WHERE um.user_id = %s AND ns.isActive = 1 GROUP BY ns.id ORDER BY ns.id DESC But I need to add some more logic for the field 'image', I decided to use decorator @property to the model: @property def image(self): '''some logic here''' return self._image But now sql code doesn't work. Also I tried annotation to add 'um.team_id as team'. Could you please give me some idea have can I use @property and save the current structure of sql response (id, title, image, url, description and team)? -
Xcode 8.1 - Cordova 6.4 - Angular 1 - $http request problems
I have an ionic v2.1 application that works when I develop locally in browser, but when I build the ios project and simulate it on the ipad in xcode, I have trouble making https calls to my django app using django rest framework. I did test to make sure I could make http calls to an arbitrary endpoint and I tested my endpoint with curl and other methods so I know my service is up. I have also tried stuff in this post: CFNetwork SSLHandshake failed iOS 9 trying to update the .plist file. $scope.buttonPress = function(){ // this one works - some random endpoint $http.get('https://jsonplaceholder.typicode.com/posts/1').then(function(data){ console.log(data.data); }).catch(function(err){ console.log('some err getting json placeholder'); }); // mine does not work in xcode, it just prints the .catch console.log in // xcode console. this endpoint works any other time i try it accept // through xcode. $http.get('https://mycoolapp.menu/getBartenderInfo/').then(function(data){ console.log(data.data); }).catch(function(err){ console.log('some err getting the info'); }); } Updating the .plist to allow for arbritary or doing something like this: <key>NSAppTransportSecurity</key> <dict> <key>NSExceptionDomains</key> <dict> <key>mycoolapp.menu</key> <dict> <key>NSIncludesSubdomains</key> <true/> <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key> <true/> <key>NSTemporaryExceptionMinimumTLSVersion</key> <string>TLSv1.0</string> <key>NSTemporaryExceptionRequiresForwardSecrecy</key> <false/> </dict> </dict> has not worked. Any help would be appreciated. If I left anything critical out of the problem statement, … -
Music player next function doesn't work for the first song
I am designing a music player in django. I have a next feature in player which plays the next song form the list. The next feature works well for all song except when the first song is currently playing. When we open the player url, the first song is set as the default song. It would be useful if someone can suggest better design for next and prev feature than mine. I have to run on all the songs to find the current song and then I get the next/prev song. models.py from __future__ import unicode_literals from django.db import models class Playlist(models.Model): genre = models.CharField(max_length = 200) def __str__(self): return self.genre class Song(models.Model): song_title = models.CharField(max_length=250) file = models.FileField(upload_to='/',default = "null") def __str__(self): return self.song_title views.py from django.shortcuts import render from django.http import HttpResponse from django.conf import settings from models import Song def home(request): song = Song.objects.all() context = {"songs":song} return render(request,'music/base.html',context) base.html: {% load staticfiles %} <html> <head> <link rel="stylesheet" href="{% static 'home.css' %}" type="text/css"> </head> <body> <div id = "musicplayer"> <div id = "details"> <p id = "songname">{{ songs.0.song_title }}</p> </div> <div id = "buttons"> <progress id="seekbar" value="0" max="1"></progress> <div id = "menu"> <audio src="{{ songs.0.file.url }}" data-title … -
Using Ajax Button to Filter Django Models
I am attempting to make buttons on my website that, when clicked, apply a specific filter to my database of models. The model item I would like to sort is a "Clothes_Item" and I would like to apply various sorts of filters. I just want to get this working on a very basic level and then I'll be able to figure it out from there, so let's just say I want to have a singular button that will display all clothing items with gender = "unisex" (where gender is a field of my Clothes_Item model). index.html <input class="filter-button" type="button" data="unisex" value="unisex" data_url/> main.js $('.filter-button').on('click', function(event) { event.preventDefault(); var element = $(this); //button that was clicked $.ajax({ url : 'filter_clothes/', type: 'GET', data: { filter_category : element.attr("data") }, }); urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'filter_clothes/', views.filter_clothes, name='filter_clothes'), #more urls... views.py def filter_clothes(request): filter_category = request.GET.get("filter_category") clothes = Clothes_Item.objects.filter(gender=filter_category) return HttpResponseRedirect(reverse('index', kwargs={'clothes': clothes})) def index(request, **kwargs): clothes = Clothes_Item.objects.all() if 'clothes' in kwargs: clothes = kwargs['clohtes'] if request.user.is_authenticated(): favorite_clothes_ids = get_favorite_clothes_ids(request) return render(request, 'index.html', {'clothes': clothes, 'favorite_clothes_ids': favorite_clothes_ids}) return render(request, 'index.html', {'clothes': clothes}) I'm recieving a "NoReverseMatch at /filter_clothes/" error and I haven't been able to fix this for awhile. … -
Django models title = models.CharField(_('title'), max_length=100)
class PersonType(models.Model): """Person type model.""" title = models.CharField(_('title'), max_length=100) slug = models.SlugField(_('slug'), unique=True) I wonder what is _('titile') do here for title. And also what is _('slug') do for slug? -
how can i display extended user data on profile page django
so i was working on extending django user model following this tutorial and after some trial and error i finished it but i can't seem to find a way to show the extended data on the profile profile.html <h2> {{user.first_name}} </h2> <h2> {{user.last_name}} </h2> <h2> {{user.email} </h2> <h2> {{user.website} </h2> <h2> {{user.bio} </h2> <h2> {{user.phone} </h2> <h2> {{user.city} </h2> <h2> {{user.country} </h2> </div> view.py @login_required() # only logged in users should access this def edit_user(request, pk): # querying the User object with pk from url user = User.objects.get(pk=pk) # prepopulate UserProfileForm with retrieved user values from above. user_form = UserForm(instance=user) # The sorcery begins from here, see explanation below ProfileInlineFormset = inlineformset_factory(User, UserProfile, fields=('website', 'bio', 'phone', 'city', 'country', 'organization')) formset = ProfileInlineFormset(instance=user) if request.user.is_authenticated() and request.user.id == user.id: if request.method == "POST": user_form = UserForm(request.POST, request.FILES, instance=user) formset = ProfileInlineFormset(request.POST, request.FILES, instance=user) if user_form.is_valid(): created_user = user_form.save(commit=False) formset = ProfileInlineFormset(request.POST, request.FILES, instance=created_user) if formset.is_valid(): created_user.save() formset.save() return HttpResponseRedirect('/accounts/profile/') return render(request, "account/account_update.html", { "noodle": pk, "noodle_form": user_form, "formset": formset, }) else: raise PermissionDenied urls url(r'^admin/', admin.site.urls), url(r'^$', main_views.home, name='home'), url(r'^accounts/profile/$', main_views.uprofile, name='uprofile'), url(r'^accounts/update/(?P<pk>\d+)/', User_Profile_views.edit_user, name='edit_user'), url(r'^accounts/', include('allauth.urls')), models class UserProfile(models.Model): user = models.OneToOneField(User, related_name='user') website = models.URLField(default='', blank=True) bio = models.TextField(default='', … -
Django REST Serializer Method Writable Field
I'm reading up on Django REST Framework and I have a model that is serialized with getters using the SerializerMethodField(). However, when I POST to this endpoint, I want to be able to set this field as well, but that doesn't work because, as the docs show above, you can't write to a SerializerMethodField. Is there any way in Django REST to have a serializer field that you define a custom getter method for, and a custom setter method? -
How do I allow all Cross Domain Requests on my Django Rest Framework project?
I have tried the following things: Installed Djagno Cors Headers and added the following code to my settings: CORS_ORIGIN_ALLOW_ALL = True I have also added csrf_exempt handlers to all my API views. Yet, nothing works and I still keep on getting CSRF errors. Any help? What am exactly doing wrong. The exact same code was working on my local server, yet now its broken :/ Thanks. -
In Django how do I get code to run after many to many relationships are made from an admin inlineformset?
Lets say I have these models from django.db import models class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): # __unicode__ on Python 2 return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): # __unicode__ on Python 2 return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) And in my admin.py I set it so that the Group uses an inlineformset for its members relationships. class GroupAdmin(admin.ModelAdmin): inlines = [PersonInlne] When the group object is saved in the admin, I want to be able to trigger some code that would run and this code should be able to look at all of the relationships it now has after the save. How do I go about that? post_save signal on Group doesn't runs after Group is saved but before the m2m relationships are made and I can't get m2m_changed to work because the m2m field has a custom through attr. -
Django - customisation doesn't work at Photologue
I've got a web app built on Django Photologue. A want to add same changes (limited access to web). At first I tried to do as example (enter link description here)- change pagination in urls.py, but it doesn't work. It shows still all galleries. urlpatterns = [ url((r'^gallerylist/$', auth_views.login), GalleryListView.as_view(paginate_by=1), name='photologue_custom-gallery-list'), ] I created a new aplication, photologue_custom and did other thinks as in example. Path: /home/celinaitomek/wedding-gallery/mysite -> my app /home/celinaitomek/wedding-gallery/photologue -> photologue /home/celinaitomek/wedding-gallery/photologue_custom/urls.py -> photologue_custom Can you help me? -
Create multiple models using ModelForm
I'm trying to create a form which creates and saves multiple model instances. The model is Job. What I want to do is to create a form with one extra multiplechoice field target_language. If user choose multiple languages, multiple instances will be created and each of this instances will have one target_language. I suppose this could be done using ModelForm and overriding save method but I'm not sure how to continue. class NewOrderForm(forms.ModelForm): target_languages = forms.ModelMultipleChoiceField(queryset=Language.objects.all()) class Meta: model = Job fields = ['language_from', 'target_languages', 'text_to_translate', 'notes','short_description', ] def save(self): for target_language in self.cleaned_data['target_languages']: self.instance.language_to = target_language self.instance.save() The problem is that in this case, the one instance will be overriden instead of creating new instance in each iteration. Do you know how to do that? -
Prevent Django from creating tables -connecting to existing DB
i am developing an application in Django for my company. Planning to use an existing DB. When i was playing around Django, i saw the framework creating django_sessions table when the server fired up, and other tables when migrate command is provided. Since i am planning to use existing DB, how can i prevent Django from creating Django_session. oOher tables, as i understand,are created only when migrate b is fired. django 1.8.6 and python 2.7.11 Completely new to Django= thanks for any help -
Custom query in django admin
I have a Django model of payments. This payments model has a date,a value column then I need to show total sales group by for date in the django admin. I make a function to return a dict with dates with total sales, payments.objects.extra(select={'day': 'date( date )'}).values('day').annotate(available=Sum('value')) but I need show this group by from django admin, but When I put this fuction in the django admin not show this query group by for date -
GeoDjango ORM lookup wrongly transforms geometry to unwanted SRID in SQL
In the query below lookup with geometry variable wrongly transforms geometry to unwanted SRID in SQL. Buildings.objects.annotate( area_krovak=Transform('area', self.KROVAK_SRID), intersection_area=RawSQL('ST_Area(ST_Intersection(ST_Transform(area, {krovak}), ST_GeomFromEWKB(\'\\x{district_geom}\')))'.format(district_geom=geometry.ewkb.hex(), krovak=5514), []) ).filter(area_krovak__intersects=geometry) Building.area is in db a MultipolygonField(), in db there is by default SRID 4326 (WGS84). geometry is GEOSGeometry in Krovak projection (SRID 5514). To make ST_Intersection work I need both in the same projection, so I added the field area_krovak in the corresponding projection. But the =geometry part in lookup area_krovak__intersects=geometry results in the following SQL (when I print .query) ST_Transform(ST_GeomFromEWKB('blabla'::bytea), 4326) For some reason Django transforms it to 4326 and therefore it does not work. -
Django- Test POST with model instance
In my unit tests I have this object: def base_data(cls): cls.HOME = Branch.objects.create( name="Head Office" ) and I am testing with this: def test_create_record(self): c = Client() response = c.post(reverse_lazy("Inventory:create_record"), {'branch':self.HOME.pk}) However, the object is not passed through with this method, instead the view simply gets the pk as a string or integer: ValueError: Cannot assign "'11'": "Purchase.branch" must be a "Branch" instance. How do I deliver the actual model instance to the view? -
Wagtail: Filter results of an InlinePanel ForeignKey
These models allow me to establish multiple human "editors" for a tool: class ToolPageEditors(models.Model): person = models.ForeignKey('people.UserProfile') page = ParentalKey('ToolPage', related_name='toolpage_editors') class ToolPage(BaseAsset): content_panels = BaseAsset.content_panels + [ InlinePanel('toolpage_editors', label="Tool Editors") ] But then each ToolPageEditors instance is a dropdown with more than 3,000 users. I'd like to limit the contents of that dropdown to people in a given group. I know how to do this in Django by overriding the admin form, but am having trouble figuring out how to accomplish it in Wagtail. Suggestions? Thanks. -
Django - How to pass a model to CreateView
I am new to Django, and I got stuck on this problem for a while now. I want to create a generic Create View, that accepts any model and creates a form from it, but I don't know how set the model attribute to the model passed to the view as a URL parameter. urls.py: url(r'^(?P<model>\w+)/new$', views.ModelCreate.as_view(), name='new-record') views.py: class ModelCreate(CreateView): model = ??? fields = [] for field in model._meta.get_fields(): fields.append(field.name) template_name = 'new_record.html' Thanks for the help in advance!