Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to used django loop {% %} to created multiple<div>
I have created this code in html file: {% for i in uniindicatorproduct1 %} <div id='container'+{{ i }}></div> {% endfor %} Where uniindicatorproduct1 is actually equal to 2, and I plan to have the output like this: <div id=container1></div> <div id=container2></div> Anyone can help me edit this code in order to have the above output? -
proper use of setup_eager_loading
I have a serializer which has a nested relationship where 4 additional tables need to be fetched which can create a loop inside loop inside loop and the django ORM is lazy. I thought of using setup_eager_loading to improve the performance. I have a Eagerloadingmixin as follow class EagerLoadingMixin: @classmethod def setup_eager_loading(cls, queryset): if hasattr(cls, "SELECT_RELATED"): queryset = queryset.select_related(*cls.SELECT_RELATED) if hasattr(cls, "PREFETCH_RELATED"): queryset = queryset.prefetch_related(*cls.PREFETCH_RELATED) return queryset class RentSerializer(serializers.ModelSerializer, EagerLoadingMixin): #owner = serializers.SerializerMethodField() timeLaps = serializers.SerializerMethodField() #gallery = GallerySerializer(read_only=True, many=True) #property_category = CategorySerializer() SELECT_RELATED = ['owner',] PREFETCH_RELATED = ['gallery', 'property_category', ] class Meta: model = Rental read_only = ('id', 'token', 'created_on', 'modified_on', 'slug', ) fields = ('__all__') class Rent(APIView): """ List all the rents if token is not provided else a token specific rent """ serializer_class = RentSerializer def get(self, request, token=None, format=None): reply={} try: rents = Rental.objects.all() if token: rent = Rental.objects.get(token=token) reply['data'] = self.serializer_class(rent).data else: reply['data'] = self.serializer_class(rents, many=True).data except Rental.DoesNotExist: return error.RequestedResourceNotFound().as_response() except: return error.UnknownError().as_response() else: return Response(reply, status.HTTP_200_OK) How can i use this in my APIView if i am not overriding get_queryset method? -
query times within time range with exclusion/specific case
Assume I have Item model which have a start and end timefield. class Item(models.Model): start = models.TimeField() end = models.TimeField() I need to get all Items which are in a specific range (between some start and end), BUT, assume I have two Items in my database: Item 1 that start 5pm and end 8pm and Item 2 that start 8pm and end 11pm I want to query to get all Items that are between and on (inclusive) 5pm to 8pm, so it should only return the Item 1, and even though Item 2 starts at 8pm, I do not want Item 2, because the end on Item 2 is different than the start of Item 1. -
Django rest framework - NOT NULL constraint on a foreign Key
I have this Error : IntegrityError at /api/post_flight_schedule/ NOT NULL constraint failed: flights_tailnumber.aircraft_type_id When I try to add a new PosFlightSchedule Object to DB over http://127.0.0.1:8000/api/pos_flight_schedule (Website/APIView) I have the below serializer : class PosFlightScheduleModelSerializer(ModelSerializer): class Meta: model = PosFlightSchedule fields = ['pos_route_id', 'tail_number', 'pos_flight_number', 'pos_flight_departure_time', 'pos_flight_date', 'pax_count'] class PosFlightScheduleSerializer(serializers.Serializer): pos_route_id = serializers.CharField(source='pos_route_id.route_id', read_only=False) tail_number = serializers.CharField(source='tail_number.tail_number', read_only=False) pos_flight_number = serializers.CharField(source='pos_flight_number.flight_number', read_only=False) pos_flight_departure_time = serializers.CharField(source='pos_flight_departure_time.flight_departure_time', allow_null=True, read_only=False) pos_flight_date = serializers.CharField(source='pos_flight_date.flight_date', read_only=False) pax_count = serializers.IntegerField(read_only=False) def create(self, validated_data): tail_number_data = validated_data.pop("tail_number") tail_number = TailNumber.objects.create(**tail_number_data) flight_number_data = validated_data.pop("pos_flight_number") flight_number = FlightSchedule.objects.create(**flight_number_data) flight_departure_time_data = validated_data.pop("pos_flight_departure_time") print "DEP_TIME" + str(flight_departure_time_data) flight_departure_time = FlightSchedule.objects.create(**flight_departure_time_data) route_id_data = validated_data.pop("pos_route_id") route_id = FlightScheduleDetail.objects.create(**route_id_data) flight_date_data = validated_data.pop("pos_flight_date") flight_date = FlightScheduleDetail.objects.create(**flight_date_data) pax_count = validated_data.pop("pax_count") schedule_obj = PosFlightSchedule.objects.create(**validated_data) # if tail_number: schedule_obj.set_tail_number(tail_number) schedule_obj.set_pos_flight_number(flight_number) schedule_obj.set_pos_flight_departure_time(flight_departure_time) schedule_obj.set_pos_route_id(route_id) schedule_obj.set_pos_flight_date(flight_date) schedule_obj.set_pax_count(pax_count) schedule_obj.save() return schedule_obj def update(self, instance, validated_data): tail_number = validated_data.pop("tail_number") flight_number = validated_data.pop("pos_flight_number") flight_departure_time = validated_data.pop("pos_flight_departure_time") route_id = validated_data.pop("pos_route_id") flight_date = validated_data.pop("pos_flight_date") pax_count = validated_data.pop("pax_count") instance.__dict__.update(validated_data) if tail_number: instance.set_tail_number(tail_number) if flight_number: instance.set_pos_flight_number(flight_number) if flight_departure_time: instance.set_pos_flight_departure_time(flight_departure_time) if route_id: instance.set_pos_route_id(route_id) if flight_date: instance.set_pos_flight_date(flight_date) if pax_count: instance.set_pax_count(pax_count) instance.save() return instance The model of the field which is giving error looks like : class TailNumber(models.Model): tail_number_id = models.AutoField(null=False, primary_key=True) tail_number = models.CharField(max_length=20, null=False, blank=False, unique=True) aircraft_type = models.ForeignKey(AircraftType, … -
Unit tests simulating two connections
First of all I'm sorry for my English, I'm supported by the translator. I'm using Django 1.11.1 and Channels 1.1.3 and trying to simulate 2 simultaneous connections in my unit tests, but channel name gets repeated and causes the system to "ignore" one of the connections. class BindingTestCase(ChannelTestCase): def _pre_setup(self): super(BindingTestCase, self)._pre_setup() self.client = Client() def _post_teardown(self): Redis(port=PORT).flushall() def test_user_login_success(self): self._send_and_consume('websocket.connect', {"text": "", "path": "/"}) ..Other methods for first connection.. self._send_and_consume('websocket.connect', {"text": "", "path": "/"}) ..Methods after second connection.. However, when the unit test passes the first connection call, a name is created for the channel. When it passes the second connection it is holding the same channel name. The problem that all my logic uses as primary key is the name of the channel. First call: print(message.reply_channel.name) defaultwddHR Second call: print(message.reply_channel.name) defaultwddHR This makes the tests impossible, since to guarantee the precise operation wait for the response that the second user should receive. But since the primary key is the name of the channel that is repeated, the system understands that it has only one user. -
Reuse the decorator of a view from a template
Some of my views have decorators that restrict access, like so: @user_passes_test(my_validation_function) def my_restricted_view(request): ... The thing is, in my templates I would like to hide the links for which the user does not have access, according to the logic in my_validation_function. I understand that one way of doing this would be defining a custom filter that basically calls my_validation_function (say my_validation_filter), and shows/hides the link accordingly. Something like this: {% if request | my_validation_filter %} <a href="{% url 'my_restricted_view' %}"></a> {% endif %} The problem I see here is that I'm linking the validation twice: once in the view, and once in the template. Suppose I have many views, each with different validation logic behind them: @user_passes_test(my_validation_function) def my_restricted_view(request): ... @user_passes_test(my_other_validation_function) def my_other_restricted_view(request): ... This would means that, when I'm writing the templates, I have to be careful to always remember which validation function goes with which view. Is there a way to define a function or that reverses the URL, and then checks the validations defined in the decorator of the view? I'm thinking something like these: {% if can_access 'my_restricted_view' %} {# this implicitly calls 'my_validation_function' #} ... {% endif %} {% if can_access 'my_other_restricted_view' %} {# … -
My Custom User authentication wont work
I created a custom user model for my Django project so that the user could login in with their email. However, the authentication wouldn't work. Here is my code: Views: def login_view(request): if request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = authenticate(usename=email, password=password) if user: print(True) login(request, user) return redirect('/account/') else: print(str(password)+" "+str(email)) print(False) else: form = LoginForm() return render(request, 'users/login.html',{'form': form}) my backend: def authenticate(self, username=None, password=None,): try: user = User.objects.get(email=username) if user.check_password(password): return True except User.DoesNotExist: return True def get_user(self, user_id): try: user = User.objects.get(pk=user_id) if user.is_active: return user return None except User.DoesNotExist: return None My User Model: class UserManager(BaseUserManager): def _create_user(self, first_name, last_name, username, email, is_admin, password=None, **extra_fields): """ creates a User with first name, last name, username, email, password """ if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model( first_name=first_name, last_name=last_name, username=username, email=email, is_admin=is_admin, is_active=True, **extra_fields, ) user.set_password(password) user.save(using=self._db) return user def create_user(self, first_name, last_name, username, email, password, **extra_fields): return self._create_user( first_name, last_name, username, email, False, password, **extra_fields ) def create_superuser(self, first_name, last_name, username, email, password=None, **extra_fields): return self._create_user( first_name, last_name, username, email, True, password, **extra_fields ) class User(AbstractBaseUser): first_name = … -
How I can pass a list or data from javascript to the view in django?
I am working on a project and I want to pass a list or data from javascript to the view in django?? Thanks in advance -
Slow Python Django Mysql Update Query
I have a user table which has columns user_id, update_time, etc and an action table, which has columns user_id, action and create_time table. class User(models.Model): user_id = models.CharField(db_index = True, max_length = 255, unique = True, null = False) update_time = models.DateTimeField(db_index = True, default = timezone.now, null = True, blank = True) class Action(models.Model): user_id = models.CharField(db_index = True, max_length = 255, null = False) action = models.CharField(db_index = True, max_length = 15, unique = False, null = False) create_time = models.DateTimeField(db_index = True, auto_now_add = True, null = True) I want to save user's last active time in update_time column. I am getting many actions by many users per day. So I don't update user table update_time column while inserting an action. I update the update_time column by a background job, which finds the max of create_time of all actions corresponding to a user_id and update his update_time column in the user table. The background job runs below code/query for this purpose. But the performance of this piece of code not so good. Can anyone help me optimize it, either a better MySQL query or even in a format of Django ORM query or any different strategy to … -
Django is not serving media files in debug environment
I've looked at many other stack overflow posts and I'm at a loss as to why this isn't working I've followed other posts and come up with this: # settings.py MEDIA_ROOT = 'media/' MEDIA_URL = 'http://localhost:8000/media/' # myapp/models.py class Profile(models.Model): avatar = models.ImageField(upload_to='profile/', blank=True, null=True) # myapp/urls.py if (settings.DEBUG): urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I am getting a 404 response from django, not sure if there is something I'm missing or not. Running Python 3.6.1 and Django 1.10.6 -
Returning JSON Response in Django
I'm attempting to return a JSON response from a query. I've seen examples such as (https://rayed.com/wordpress/?p=1508), but they don't incorporate passing the HTML template. I'm receiving an error "ictionary update sequence element #0 has length 510; 2 is required" Model class APCPlats(models.Model): PlatsProjected = models.IntegerField(db_column='Projected', blank=True, null=True) PlatsCompleted = models.IntegerField(db_column='Complete', blank=True, null=True) Month = models.CharField(db_column='Month', max_length=200 , blank=True, null=True) def __str__(self): return self.Month class Meta: managed = True db_table = 'APCPlats' View def APCChart(request): apcdata = APCPlats.objects.all() apcchart = serializers.serialize('json', apcdata) return render(request, 'apc.html', JsonResponse(apcchart, safe=False)) -
Editing session variable in Django
I want to store a Python list in my session variable and edit it on subsequent view calls. I just did this (in a view): if 'x' not in request.session: request.session['x'] = [] request.session['x'].append('test') This only works on the first try, i.e. the session will actually contain ['test'] under dict key 'x' after the first time this view is called. However, when I try to do this a second time, the list is updated (as I can see when debugging) but the value is not persisted, as evidenced by debugging any subsequent calls: the value remains ['test'] long-term, instead of becoming ['test','test']. I have found the following step as a workaround, but I'm unsure whether I should try working around it: does this code circumvent a reasonable constraint imposed by Django ? temp_var = request.session['x'] temp_var.append('test') request.session['x'] = temp_var -
Using supervisor and gunicorn to start up django-celery processes?
Confusion! Its easy to launch django using supervisor, such as below - based on a tutorial I found: supervisord.conf: [program:gunicorn] command=/home/me/.virtualenvs/app/bin/gunicorn app.wsgi:application --bind 127.0.0.1:8000 ; Yet celery seems to require its own startup method: celery -A app worker -l info So in my ignorance/confusion it appears I have to either start with Gunicorn or Celery. Obviously I'm confused since no doubt many use celery within Supervisor. Where am I going wrong? How do I use supervisor to start up a celery-django app within Gunicorn? -
Django: Looking for a string in the template
How do I look for a string inside in django template? Let's say I want to make every occurrence of {{ my_variable }} bold, how do I do that? -
Elasticbeanstlalk application and environment not appearing in my AWS console
I installed awsebcli using pip and am following this tutorial: http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html I have a aws_access_key_id and aws_secret_access_key in my ~/.aws/config file so from my understanding AWS is using that profile (it has Admin, PowerUser and AmazonS3Full access). When I do eb init it asked me to select a default region (default value was us-west-2 so I wen't with that). Asked me to enter application name (default was ebdjango - the name of my django project - so I went with that). Asked me to select a platform, I selected Python 3.4. It then said Cannot setup CodeCommit because there is no Source Control setup, continuing with initialization and asked me if I want to set up SSH for my instance (default was Yes). Told me to select a key-pair (aws-eb was the default option so I went with that - although I'm not sure where it got this key-pair from and where it is located). I then did eb status and this came up: ERROR: This branch does not have a default environment. You must either specify an environment by typing "eb status my-env-name" or set a default environment by typing "eb use my-env-name". Now, I did eb create ebdjango-env. … -
Recursive QuerySet with django
I have this model referencing itself to allow building a tree: class PartCategory(models.Model): parent = models.ForeignKey('PartCategory', on_delete=models.DO_NOTHING, null=True, default=None, blank=True) name = models.TextField() I now have an SQL query to get one element and all of its childs in one select (in this exemple the element with id=64): WITH RECURSIVE under_partcategory(id,name, parent_id,level) AS ( select api_partcategory.id,api_partcategory.name,api_partcategory.parent_id,0 from api_partcategory where api_partcategory.id=64 UNION ALL SELECT api_partcategory.id,api_partcategory.name,api_partcategory.parent_id, under_partcategory.level+1 FROM api_partcategory JOIN under_partcategory ON api_partcategory.parent_id=under_partcategory.id ORDER BY 2 ) SELECT * FROM under_partcategory; I am searching for way to express this query inside a QuerySet to allow adding filtering options and fields constrution from my model but I don't quite know if it's kind of possible. Can I construct a composite QuerySet made from some kind of raw query built from my model, and at the same time allowing to use the filter and order_by capabilities? -
form and ModelMultipleChoiceField with existing data
This post is very helpful on the subject. However, I am working with a Class-Based View and am wondering how to accomplish the task of adding "selected" items to a ModelMultipleChoiceField when the queryset depends on an instance of the model with which I am working. Models: class OfferGroup(models.Model): name = models.CharField(max_length=64, null=False) priority = models.IntegerField(null=False, unique=True) class Meta: verbose_name = _('OfferGroup') ordering = ['priority', ] class ConditionalOffer(AbstractConditionalOffer): groups = models.ManyToManyField('auth.Group', verbose_name=_("User Groups"), blank=True) offer_group = models.ForeignKey(OfferGroup, related_name='offers', null=True) ... class Meta: ordering = ['priority', ] Where AbstractConditionalOffer provides fields 'name', 'offer_type', start and end datetimes as well as foreign keys to other models. Form: class OfferGroupForm(forms.ModelForm): offers = ModelMultipleChoiceField(queryset=ConditionalOffer.objects.all(), widget=forms.widgets.SelectMultiple(), required=False) class Meta: model = OfferGroup fields = ('name', 'priority', 'offers') this form isn't really what I need, see below View: class OfferGroupUpdateView(UpdateView): model = OfferGroup template_name = 'dashboard/offers/offergroup_edit.html' form_class = OfferGroupForm success_url = reverse_lazy('dashboard:offergroup-list') def save_offers(self, offer_group, form): selected_offers = form.cleaned_data['selected'] for offer in selected_offers: offer_group.offers.add(offer, bulk=False) other_offers = form.cleaned_data['not_selected'] for offer in other_offers & offer_group.offers.all(): offer_group.offers.remove(offer) form.save() return HttpResponseRedirect(reverse('dashboard:offergroup-list')) def form_valid(self, form): offer_group = form.save(commit=False) return self.save_offers(offer_group, form) Now, the problem with this approach is that the queryset provided to OfferGroupForm doesn't provide any information about what … -
Display message after HttpResponseRedirect in Django Class Based View
Either I'm not getting enough sleep or I'm missed something obvious. No matter what I do, I can't get messages to display from a class based view after a HttpResponseRedirect. Here's my view: class Add(SuccessMessageMixin, LoginRequiredMixin, CreateView): template_name = "apps/add.html" form_class = forms.Add success_message = "Report was added successfully" def form_valid(self, form): team = get_object_or_404(t_models.Team, owner=self.request.user) self.object = form.save(commit=False) self.object.team = team self.object.recorded_by = self.request.user self.object.save() form.save_m2m() return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('thing_detail', kwargs={'pk': self.object.id}) So far I've double checked that I have all the sessions settings right, all the messages set up right and I've rebooted the VE and flushed the cache. Any suggestions? -
Using network_mode='host' in docker-compose break run: host type networking can't be used with links
I dockerized a django app, and it need to connect to the HOST PostgresDB database. For that I do in the docker-compose: version: '2' services: web: build: context: . dockerfile: DockerfileWeb command: gunicorn --timeout=300 --graceful-timeout=30 -w 2 --threads 2 -b 0.0.0.0:8000 cobros.wsgi volumes: - .:/code - /tmp:/tmp network_mode: "host" ports: - "8000:8000" restart: always environment: - DATABASE_URL=postgres://postgres@127.0.0.1/postgres - PRODUCTION="true" This work fine, EXCEPT if I try to run a command inside the docker, like: docker-compose run web python manage.py periodico Now I get this error: [192.168.1.70] out: ERROR: Cannot create container for service web: b"Conflicting options: host type networking can't be used with links. This would result in undefined behavior" -
Query JSONField for with keys of numerals only
I've taken the following example from Django's documentation, except replaced added a key '99': >>> Dog.objects.create(name='Rufus', data={ ... 'breed': 'labrador', ... 'owner': { ... 'name': 'Bob', ... 'other_pets': [{ ... 'name': 'Fishy', ... }], ... }, ... }) >>> Dog.objects.create(name='Meg', data={'breed': 'collie', '99': 'FINDME',}) >>> Dog.objects.filter(data__breed='collie') <QuerySet [<Dog: Meg>]> I want the following to also return the "Meg" Dog: Dog.objects.filter(data__99='FINDME') However, it seems that because my key is an integer, Django doesn't handle this properly. How do I have integer keys that are strings in python jsonfields? -
MongoEngine with django-tables2
I'm trying to use MongoEngine to store/query data and django-tables2 to render the data in nice tables in my django app. But I couldn't find any document or examples to make the two working together. The django-tables part is working fine: models.py from django.db import models class User(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=10) tables.py import django_tables2 as tables from models import User class UserTable(tables.Table): class Meta: model = User views.py from tables import UserTable def users(request): data = [{'id': 1, 'name': 'Bob'}, {'id': 2, 'name': 'Jack'}] return render(request, 'users.html', {'users': UserTable(data)}) users.html {% block content %} <!DOCTYPE html> <html lang="en"> <body> {% load render_table from django_tables2 %} {% render_table users %} </body> </html> {% endblock %} And I get my table rendered as expected. Now to do the same with MongoEngine: models.py from mongoengine import * class UserDB(Document): id = IntField(primary_key=True) name = StringField(max_length=10) (same 'model' but using mongoengine fields) tables.py: class UserTableDB(tables.Table): class Meta: model = UserDB (so no change except the model now pointing to my mongo doc) And now I create a user, save it then load the data back: views.py user = UserDB(name='Bob', id=1) user.save() dataDB = UserDB.objects() return render(request, 'users.html', {'users': UserTableDB(dataDB)}) But it … -
how recognize media urls in django
I have the following entry in my urls.py: url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}) Since I upgraded to django 1.10 I now get the error: I get the error: TypeError: view must be a callable or a list/tuple in the case of include(). How can I reconfigure this url to satisfy the error and have my media show up in django 1.10? -
Django - CSS path not found
Output in console when server is running: Not Found: /css/bootstrap.css I'm pretty sure I'm getting the paths wrong but I don't know what are the right paths given my project structure (below). settings.py: STATIC_URL = '/static/' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] project tree: Grand Folder app1 static app1 css bootstrap.css app2 app3 templates base.html base.html: {% load i18n %} {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="{{ STATIC_URL }}/css/bootstrap.css" /> <title>{% block title %}User test{% endblock %}</title> </head> -
Django database inputs not being validated
I have this class: class Object(models.Model): value=models.IntegerFiled(validators=[MaxValueValidator(100)]) I get user input for the value attribute, create an object according to the user input and save it to the database. The problem is that the user can enter e.g. 120 in the form that is used to get the input from the template/html-page to the view's method. Then an invalid object is saved to the database. How exactly does the MaxValueValidator work? When does it do anything? What purpose do validators serve?( I really couldn't find any answer to my questions in the documentation) I do check if the input form is valid in the view, but this doesn't seem to prevent saving invalid objects by just changing the HTML attributes in the form via developer tools in the browser -
Django. How to make multiple file uploading in admin interface?
There are the following models: class Category(models.Model): ... class CategoryPhoto(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='фото') image = models.ImageField(upload_to='category_photos', verbose_name='фото') name = models.CharField(max_length=50, blank=True, verbose_name='название') ... admin.py file is: class CategoryPhotoInline(admin.StackedInline): model = CategoryPhoto extra = 0 ... class CategoryAdmin(admin.ModelAdmin): ... inlines = [CategoryPhotoInline] And I have following interface: But uploading files one by one is uncomfortable. Is there a way to make django to load all files from the directory instead of loading each file manually?