Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework - Create if object's field is unique, else return existing object (bulk create)
Is there a good solution to this problem? My object, Person, must have a unique 'ssn' field in the db. Also, many=True, so a consumer of this API can POST an array of Person objects. For the Person objects specified in the array: If an instance's 'ssn' field is unique, create new object If an instance's 'ssn' field already exists on an object in the db, return the existing instance. For example, suppose Person = {'name':'Kyle','ssn':'005'} exists in the db. Then a new POST request comes in as follows: [{'name':'Bryan','ssn':'007'},{'name':'Kyle','ssn':'005'}] I want the response payload to be: [{'name':'Bryan','ssn':'007'},{'name':'Kyle','ssn':'005'}], instead I get [{},{'ssn':'This field must be unique.'}] I am currently overwriting the to_internal_value() method in my PersonSerializer to identify duplicates, but I do not know how to prevent subsequent validate and create for these duplicates while also returning an array of mixed created/existing object instances. I took a look at many other questions about this but haven't yet found a working solution. I'm sorry, though, if I've missed the solution somewhere else. Thanks! -
Django model reload_from_db() vs. explicitly recalling from db
If I have an object retrieved from a model, for example: obj = Foo.objects.first() I know that if I want to reference this object later and make sure that it has the current values from the database, I can call: obj.refresh_from_db() My question is, is there any advantage to using the refresh_from_db() method over simply doing?: obj = Foo.objects.get(id=obj.id) As far as I know, the result will be the same. refresh_from_db() seems more explicit, but in some cases it means an extra line of code. Lets say I update the value field for obj and later want to test that it has been updated to False. Compare: obj = Foo.objects.first() assert obj.value is True # value of foo obj is updated somewhere to False and I want to test below obj.refresh_from_db() assert obj.value is False with this: obj = Foo.objects.first() assert obj.value is True # value of foo obj is updated somewhere to False and I want to test below assert Foo.objects.get(id=obj.id).value is False I am not interested in a discussion of which of the two is more pythonic. Rather, I am wondering if one method has a practical advantage over the other in terms of resources, performance, etc. I … -
With Django Rest Framework, how can I grab the sub-objects of a specific entity?
If I want to, say, grab all of the questions of survey 5, a “RESTful” url for that would look something like “http://domain.com/api/survey/5/question/“. Does DRF provide something for that such that I wouldn’t have to override get_queryset() and manually grab the survey ID out of the URL and manually filter down the Question queryset? It seems like something like that would be built in to DRF such that I wouldn’t need to re-invent the wheel each time I wanted to grab the sub objects of a specific object, but I'm not finding it so far... I'm using DRF 3. -
Django - allow user to browse active sessions/clear all of them
I am currently working on a small website powered by Django. I want to implement a system where users are able to view how many active sessions are currently logged into their account (along with some misc data - such as MAC/WINDOWS) and the ability to clear all active sessions - effectively logging the account out globally. Kind of like Dropbox Currently I implement accounts in Django by simply setting an id key in sessions def is_user_logged_in(request): return request.session['user_id'] is not None def log_user_in(request, user): request.session['user_id'] = user Does anyone have any ideas/suggestions on how to do this? Ive thought about just creating another model in the database that specifically logs all of these separately def SessionModel(models.Model): session_id = ... mac_or_win = ... etc Would this be a feasible implementation, what if the Django session_id changes? Does anyone know where in the documentation it specifies when session_id changes? Anyone have any better ideas? -
Debugging django-channels
I'm trying to incorporate django-channels into my next project but I am having issues debugging. I have tried pycharms debugger and also pdb but it does not hit the breakpoints. -
Django tag HTML is not close
I use pycharm. 1 on my fail have error this is code <p> <a href="{% url "blog:post_share" post.id %}"> Udostepniac post </a> </p> Error is between url " and " post.id %}" Mby this problem is working with this The view blog.views.post_share didn't return an HttpResponse object. It returned None instead -
how to pass variable to bash from python without any other files exepct file.py and bash.sh
Header 1 When I start bash script from django i want to pass some arguments in order to ssh to computer with bash script to send data. -
How to serialize related models in Django Rest API?
I have tried all the solutions. Still cannot resolve it. Here are the codes. models.py class Car(models.Model): car_name = models.CharField(max_length=250) car_description = models.CharField(max_length=250) def __str__(self): return self.car_name + ' - ' + str(self.pk) class Owners(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE, default=0) owner_name = models.CharField(max_length=250) owner_desc = models.CharField(max_length=250) def get_absolute_url(self): return reverse('appname:index') def __str__(self): return self.owner_name + ' - ' + self.owner_desc serializers.py class OwnersSerializer(serializers.ModelSerializer): class Meta: model = Owners fields = '__all__' class CarSerializer(serializers.ModelSerializer): owners = OwnersSerializer(many=True, read_only=True) class Meta: model = Car fields = '__all__' views.py class CarList(APIView): def get(self, request): cars = Car.objects.all() serializer = CarSerializer(cars, many=True) return Response(serializer.data) def post(self): pass I can't get to view all the 'Owner' objects related to a certain object of the 'Car' class. -
Django No module named backendssocial.apps.django_app.context_processors
I'm adding an authentication via facebook and when I run my localhost I'm getting this error in terminal: xx-MacBook-Pro:bookstore xx$ python manage.py runserver /Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py:22: RemovedInDjango110Warning: SubfieldBase has been deprecated. Use Field.from_db_value instead. RemovedInDjango110Warning) /Library/Python/2.7/site-packages/django/db/models/fields/subclassing.py:22: RemovedInDjango110Warning: SubfieldBase has been deprecated. Use Field.from_db_value instead. RemovedInDjango110Warning) Performing system checks... /Library/Python/2.7/site-packages/social/apps/django_app/urls.py:12: RemovedInDjango110Warning: Support for string view arguments to url() is deprecated and will be removed in Django 1.10 (got auth). Pass the callable instead. name='begin'), /Library/Python/2.7/site-packages/social/apps/django_app/urls.py:14: RemovedInDjango110Warning: Support for string view arguments to url() is deprecated and will be removed in Django 1.10 (got complete). Pass the callable instead. name='complete'), /Library/Python/2.7/site-packages/social/apps/django_app/urls.py:17: RemovedInDjango110Warning: Support for string view arguments to url() is deprecated and will be removed in Django 1.10 (got disconnect). Pass the callable instead. name='disconnect'), /Library/Python/2.7/site-packages/social/apps/django_app/urls.py:19: RemovedInDjango110Warning: Support for string view arguments to url() is deprecated and will be removed in Django 1.10 (got disconnect). Pass the callable instead. 'disconnect', name='disconnect_individual'), /Library/Python/2.7/site-packages/social/apps/django_app/urls.py:19: RemovedInDjango110Warning: django.conf.urls.patterns() is deprecated and will be removed in Django 1.10. Update your urlpatterns to be a list of django.conf.urls.url() instances instead. 'disconnect', name='disconnect_individual'), System check identified no issues (0 silenced). September 12, 2016 - 19:22:13 Django version 1.9, using settings 'bookstore.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. … -
Heroku. Django dumpdata
How can I get the data on Heroku and create a fixture I can load locally? heroku run python manage.py dumpdata --natural > data.json is the command, but how can I download the file? -
Loading thumbnails from vimeo video api in django model property
I have a django app to show videos from vimeo. My model Video contains @property thumbnail where I'd like to return the url of the thumbnail to be embedded in template. However, after calling requests.get method, it raises Permission denied error. Trying it in python shell it works and loads the json properly. Here I'm showing thumbnail property code. @property def thumbnail(self): url = 'http://vimeo.com/api/oembed.json?url=http%3A//vimeo.com/{0}' try: response = requests.get(url.format(self.video_id), timeout=10) return response.json()["thumbnail_url"] except requests.exceptions.Timeout: return "" -
object() takes no parameters in django 1.10
I'm trying to allow CORS in my app, so that my cross-domain javascript client can access my API, I've installed django-cors-headers. And I'm now trying to add the middleware: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', # Remove this and it works 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] However this gives me a TypeError: TypeError: object() takes no parameters This worked fine before the django 1.10 update. Any ideas? -
Django - request.session not being saved
I have a pretty simply utility function that gets an open web order if their is a session key called 'orderId', and will create one if there is no session key, and the parameter 'createIfNotFound' is equal to true in the function. Stepping through it with my debugger I can see that the piece of code that sets the session key after an order has been created does get hit with no exceptions, but when I check the Http request object' session field, it does not have that attribute ? Utility def get_open_web_order(request, createIfNotFound=False): # Check for orderId in session order_id = request.session.get('orderId') web_order = None if None != order_id: try: web_order = WebOrder.objects.get(id=order_id, status='O') logging.info('Found open web order') except WebOrder.DoesNotExist: logging.info('Web order not found') if (None == web_order) and (createIfNotFound == True): logging.info('Creating new web order') web_order = WebOrder() web_order.status = 'O' web_order.save() request.session['orderId'] = web_order.id # Assign logged in user and default billing and shipping if request.user.is_authenticated() and hasattr(request.user, 'customer'): customer = request.user.customer web_order.customer = customer web_order.set_defaults_from_customer() web_order.save() return web_order -
Is there any way to call a django method on SelectBox change??? with JS
I want to call a WebService that I've defined on a Django function. This is dependant on a Selectbox parameter that I have to pass to this function. Thanks -
How can I annotate a Django queryset with a count in a way that's conditional to some property of each item in the queryset?
Sorry about the title, I think some pseudo-code will clarify the question: class Image(Model): user = ForeignKey(User) class Group(Model): members = ForeignKey(User) images = ForeignKey(Image) autosubmission = BooleanField() As you can see, we have a Group, consisting of some members and some images. If the group is autosubmission then members don't submit images manually to it, but all images belonging to a member automatically show up in the group. If the group is not autosubmission then the members need to submit the images manually, and they end up in the images ForeignKey. Now, I want to have a queryset that's annotated by the number of images the the group. Group.objects.all().annotate(num_images = Count('images')) Obviously, the code above only works for groups that are not autosubmission, i.e. the images are actually in the images relation. So how can I annotate the queryset so it works both for groups that are autosubmission and groups that are not? Thanks! -
What does django controllers are in views.py
I have followed several django tutorials. I do not know why controllers are stored in a file called views.py. I am confuse with this filename. I am looking for a MVC development. Are there other files in django for "real" controllers ? -
Django {% if custom_template_tag > 0 %} does not work
i've got these template tags @register.assignment_tag def test1(): return 2 @register.simple_tag def test2(): return 2 In my template i've got this {% test1 as test1_var %} {% if test1_var > 0 %}Test1{% endif %} {% if test2 > 0 %}Test2{% endif %} results in Test1 What i want is a template tag which only appears if it is greater than 0, but i cannot believe that the assignment_tag is the right solution for that. Why does Test2 not work? -
Django ajax url to json not working
Im trying to display a json file using ajax and jquery on my django site and i cant get it to load. I moved the json file into the same folder as my html file to try and rectify it but it still wont work. The console is saying 404 file not found. When i load the html file into my browser without the django sever running it loads the json fine. Is there a way of linking my ajax to my json folder in django? -
Django: jinja code not working inside the html when used multiple times
I have an html file in my django project as follows: <body> <div class="row"> <div class="col-sm-3"> <ul class="list-group"> {% for image in images %} <li class="list-group-item">{{ image.name}} <img class="img-responsive" src='http://krishna.com{{ image.path }}' /> </li> {% endfor %} </ul> </div> <div class="col-sm-9"> <ul class="list-group"> {% for image in images %} <li class="list-group-item">{{ image.name}} <img class="img-responsive" src='http://krishna.com{{ image.path }}' /> </li> {% endfor %} </ul> </div> </div> </body> the content is showns for the <div class="col-sm-3"> but no content is being shown for <div class="col-sm-9"> -
AuthGroup doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I got the error in the title when I moved my app files to a newly created project (I actually started my project as an app then I now need to make it normal project). There was a popular question about this problem and I tried many solution in it to no avail so far. I have this in my settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'cacheops', ] MIDDLEWARE_CLASSES = [ # Debug toolbar 'debug_toolbar.middleware.DebugToolbarMiddleware', # ## 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] So, If I understand the problem properly, it is caused by either that I have no 'django.contrib.auth' in INSTALLED_APPS (which I have as listed above) or it runs before the app is initiated, which I don't know how that can happen. If it may help, I construct my models.py using the inspectdb command. -
Full text search with Django
Trying to set up a website which allows full text search along with features like: Auto suggest or search assist Faceting Spell checker Highlights Spell checker Faceting Highlights Additional details: Setting it up on AWS Using Python3 & Django I am still trying to find my way through different open source solutions available like Solr, Elasticsearch and then there is Amazon's Cloudsearch. I started to dabble with Cloudsearch first as AWS has a easy interface to get started with it. Now I need to connect Django with Cloudsearch. Is Haystack the only way to do that? Not sure if it has support for Python3. Are there alternatives to connect Django with Cloudsearch? Would really appreciate pointers to any tutorials / training videos. -
how to save the ModelMultipleChoiceField--checkbox label in djangoadmin
I want to change one of admin attribute to check box, i can see the checkbox, but when i click the save, nothing happened. how to save the checked value in database from Django admin? I have defined the following models: class Travel(models.Model): owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name='travels', ) name = models.CharField(max_length=40) slug = models.SlugField(max_length=255, unique=True, help_text='Unique value for product page URL, created automatically from name.') description = models.CharField(max_length=300) price = models.FloatField() is_published = models.BooleanField(default=True) is_featured = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(null=True) objects = models.Manager() active = ActiveTravelManager() featured = FeaturedTravelManager() class Meta: verbose_name_plural = 'travels' def __str__(self): return self.name class Amenity(models.Model): TYPE_CHOICES = ( ('1', 'City View'), ('2', 'Night life'), ('3', 'Culture'), ('4', 'Local shopping'), ('5', 'Campus'), ('6', 'Religion'), ('7', 'Local food'), ('8', 'Boating'), ('9', 'Fishing'), ('10', 'Biking'), ) name = models.ForeignKey( 'travel.Travel', on_delete=models.CASCADE, related_name='amenities' ) title = models.CharField(max_length=50, choices=TYPE_CHOICES) def __str__(self): return self.title class Meta: verbose_name_plural = 'amenities' and form.py class AmenityForm(forms.ModelForm): amenity = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=Amenity.TYPE_CHOICES, ) class Meta: model = Amenity fields = ['name', 'amenity'] admin.py class AmenityInline(admin.StackedInline): model = Amenity form = AmenityForm max_num = 1 @admin.register(Travel) class TravelAdmin(admin.ModelAdmin): list_display = ['pk', 'name', 'is_published'] inlines = [AmenityInline] @admin.register(Amenity) class AmenityAdmin(admin.ModelAdmin): list_display … -
django login_required defaults request.LANGUAGE_CODE to default language in settings
login_required decorator sets request.LANGUAGE_CODE to default language that has been set in settings.py. How can I bypass this behavior ? thanks! -
admin panel, show date_created and date_updated?
I tried following an answer at this previous post: DateTimeField doesn't show in admin system But maybe I'm just too dim to understand it. No field of created_at shows up. Could anyone point me in the right direction? model class holding_transaction(models.Model): holdingname = models.ForeignKey(holding, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) admin.py class holding_transactionAdmin(admin.ModelAdmin): readonly_fields = ('created_at', ) admin.site.register(holding_transaction, holding_transactionAdmin) -
Custom user model and custom authentication not working in django. Authentication form is not passing validation tests
I am trying to implement the custom User model and custom authentication for my application. I am able to create models and make migrations. But when I created a form and implemented the login template, I am getting this error - login User model with this Login already exists. View where I am authenticating user - from django.shortcuts import render_to_response, redirect, render from django.template import RequestContext from django.contrib.auth import login, logout , authenticate from accounts.forms import AuthenticationForm from django.contrib.auth.decorators import login_required def accounts_login(request): context = {} if request.method == "POST": form = AuthenticationForm(request.POST) #getting error here print(form) if form.is_valid(): Authentication form: from django.forms import ModelForm from accounts.models import UserModel class AuthenticationForm(ModelForm): class Meta: model = UserModel fields = ['login', 'password'] My custom user model and user manager - from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.utils import timezone from django.db.models import Max class MyUserManager(BaseUserManager): use_in_migrations = True def create_user(self,login, parent_type, last_name, first_name, password): return create_superuser(self,login, parent_type, last_name, first_name, password) def create_superuser(self,login, parent_type, last_name, first_name, password): maxx = self.model.objects.all().aggregate(Max('sys_id')) print(maxx) user = self.model( sys_id = maxx["sys_id__max"] + 1, login = login, password = password, parent_type = parent_type, last_name = last_name, first_name = first_name, display_name = last_name + " …