Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Static file changes are not reflected on browser refresh
I'm new to Django and trying to figure out why the changes in static css and js files are not picked up by the browser. Only after I run python manage.py collectstatic followed by restarting the server do I see the desired results. Using Django 1.11 and python 2.7 Here is a glimpse of my settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [u'customizeittoday.herokuapp.com', u'localhost'] # Application definition TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ #STATIC_URL = '/static/' #static media settings STATIC_URL = 'https://' + AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/' MEDIA_URL = STATIC_URL + 'media/' # STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) # STATIC_ROOT = 'staticfiles' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' STATICFILES_FINDERS = ('django.contrib.staticfiles.finders.FileSystemFinder','django.contrib.staticfiles.finders.AppDirectoriesFinder',) -
How to make Triple Relationship Between Django Models
I have a Request Model which can has a many to many relationship with RequestProduct Model through a Product Model: request_product = models.ManyToManyField(Product, through='RequestProduct', null=False, blank=False) this works fine, I added RequestProduct model to Request Inlines so user could choose between products and add them to the Request. I need another inline model (RequestProductVariance Model) inside Request Model which user could only select items from related RequestProduct. in this picture first inline is RequestProduct so the user could select from all products, I want the second inline to only show products from above. I thought this would work if I add a field like I did for RequestProduct Model but it won't work, the dropdown shows all product from other requests. variance = models.ManyToManyField(RequestProduct, through='RequestProductVariance', null=False, blank=False) The first inline always will be saved before the second so i don't want it to be realtime. is there anyway to do this or any other solution which will do what i want? let me know if my question is unclear. thank you -
Python catch previous exception in broad handler
Some of my api views have something like this: try: do_stuff() except KeyError as exc: logger.log(exc) raise APIException("No good") Ideally I don't want to log in every piece of code like this but use a general exception handler that catches APIException, so I changed my code to: try: do_stuff() except KeyError as exc: raise APIException(exc) exception_handler.py def exception_handler(...): logger.log(exc) # I want to log the KeyError... return Response({"message": "try again sam"}, status_code=400) My problem is the exc in the handler isn't the keyerror but the apiexception, can I somehow get the KeyError from sys.exc_info or stacktrace? -
Django: add atributes to filter.fields
How to add placeholder an custom css class atributes to form with filter. filter.py class PlaceFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Places fields = ['name'] html <form method="GET"> {{ filter.form.name }} <label for="name"></label> </form> -
Initial data for Django Admin inline formset is not saved
I'm trying to pre-fill some inlines in Django Admin with data passed as query params (in case of adding a new object in DB). class TestCaseInlineFormSet(BaseInlineFormSet): class Meta: model = TestCase fields = '__all__' def __init__(self, *args, **kwargs): super(TestCaseInlineFormSet, self).__init__(*args, **kwargs) ids_string = self.request.GET.get('ids') if ids_string: ids = [int(x) for x in ids_string.split(',')] self.initial = [{'test_case': id} for id in ids] class TestCaseInline(admin.TabularInline): model = TestCase raw_id_fields = ('test_case',) extra = 1 formset = TestCaseInlineFormSet def get_formset(self, request, obj=None, **kwargs): formset = super(TestCaseInline, self).get_formset(request, obj, **kwargs) formset.request = request return formset def get_extra(self, request, obj=None, **kwargs): extra = super(TestCaseInline, self).get_extra(request, obj, **kwargs) requested_extras = len(request.GET.get('ids', '').split(',')) return max(extra, requested_extras) The data is pre-filled fine with this solution, however there's an issue when trying to submit: the pre-filled inlines are not marked as changed, so they're not saved. I've tried overriding has_changed() on the TestCaseInlineFormSet however it doesn't solve the problem - it seems has_changed() for the formset is never called? Any idea how to fix this? -
ValueError: invalid literal for int() with base 10: 'SOME STRING'
I have a problem when I write in cmd this "python manage.py migrate" I found this error {ValueError: invalid literal for int() with base 10: 'SOME STRING'} this is my code class GameScore(models.Model): FirstTeam = models.CharField(max_length=256, null=True) SecondTeam = models.CharField(max_length=256, null=True) first_team_score = models.IntegerField(default=0) second_team_score = models.IntegerField(default=0) game_date = models.DateTimeField(auto_now=True) def __str__(self): return '{} {} - {} {}'.format(self.FirstTeam, self.first_team_score, self.SecondTeam, self.second_team_score) I don't know how to solve this problem -
How to fetch HTML and copy verbatim into template?
I am using this code to fetch some HTML, that I want to include in my template: def index(request): data = {} url = "http://1.2.3.4/some.html" data['html'] = urllib.request.urlopen(url).read().decode('ascii') return render(request, 'index.html', data) then, in my template, I use the data as such: {{ html }} but, all entities are escaped! When I look at the rendered source, I find &lt; and &gt; everywhere. How can I fetch HTML and copy that verbatim in my template? -
show a list of fields based on selection first field
I have 2 classes and I´d like to show a list of fields from the second class based on the first class. For example: servico: id desc_servico 1 teste1 2 teste2 itemservico: id desc_itemservico servico 1 itemteste1 1 2 itemteste2 2 In this example, if I choose servico=1, the itemservico has to show me itemteste1. If I choose servico=2, the itemservico has to show itemteste2. Models.py: class servico(models.Model): desc_servico = models.CharField('Descrição', max_length=50, default='', blank=False, null=False) class itemservico(models.Model): desc_itemservico = models.CharField('Descrição', max_length=50, default='', blank=False, null=False) val_itemservico = models.DecimalField(max_digits=8, decimal_places=2) servico = models.ForeignKey(servico, default='', blank=True, null=True) # Chave estrangeira da Classe Serviço ind_selecionado = models.BooleanField(default=False) forms.py: class itemservicoForm(forms.ModelForm): servico = forms.ModelChoiceField(queryset=servico.objects.all().order_by('desc_servico'), empty_label="Serviço") class Meta: model = itemservico fields = ( 'servico', ) template.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ORÇAMENTO</title> </head> <body> <h2>ORÇAMENTO</h2> <form class=" bd-form-20 " action="" name="form-name" method="POST" enctype="multipart/form-data"> {% csrf_token %} <label class="bd-form-label" >Serviço </label>{{form.servico}}<br><br> <p><h1>{{form.servivo.id}}</h1></p> <div class=" bd-customhtml-29 bd-tagstyles bd-custom-table"> <div class="bd-container-inner bd-content-element"> <table border="1" rules="all" cellspacing="0" cellpadding="10"> <tbody> <tr> <th>Testar</th> <th>Selecionar</th> <th>ID Item Serviço</th> <th>Item Serviço</th> <th>Valor Serviço</th> <th>Serviço</th> </tr> {% for item in instance_itens %} <tr> <td> <input type="checkbox" id="item.ind_selecionado"></td> <td>{{ item.ind_selecionado }}</td> <td>{{ item.id }}</td> <td>{{ item.desc_itemservico }}</td> <td>{{ item.val_itemservico }}</td> <td>{{ item.servico_id}}</td> </tr> … -
Django DateField gives validation errors
This question is similar to Resolving ValidationError: [u"'' value has an invalid date format. It must be in YYYY-MM-DD format."] in Django 1.9.2? but I can't see what to do. I'm using django 2.0.4 and they were using 1.9.2 I have the following models.py from django.db import models import datetime class Flight(models.Model): date = models.DateField(default=datetime.date.today) dep_time = models.TimeField() dep_delay = models.CharField(max_length=100) arr_time = models.TimeField() arr_delay = models.DurationField() cancelled = models.BooleanField() carrier = models.CharField(max_length=100) tailnum = models.IntegerField() flight = models.CharField(max_length=100) origin = models.CharField(max_length=100) dest = models.CharField(max_length=100) air_time = models.CharField(max_length=100) distance = models.CharField(max_length=100) duration = models.DurationField() def __str__(self): return f'{self.flight} {self.dest} {self.date}' I'm trying to run this script from the django shell to update my database: data = data.applymap(str) data['month'] = data['month'].str.pad(2,side='left',fillchar='0') data['day'] = data['day'].str.pad(2,side='left',fillchar='0') data['date'] = data[['year', 'month', 'day']].apply(lambda x: ''.join(x), axis=1) data['date'] = pd.to_datetime(data['date'],infer_datetime_format=True) data['dep_time'] = pd.to_datetime(data['dep_time'].str.pad(4,side='left',fillchar='0'),format='%H%M',errors='coerce').dt.time data['arr_time'] = pd.to_datetime(data['arr_time'].str.pad(4,side='left',fillchar='0'),format='%H%M',errors='coerce').dt.time data['duration'] = data[['hour', 'min']].apply(lambda x: ''.join(x), axis=1) data['duration'] = pd.to_datetime(data['duration'].str.pad(4,side='left',fillchar='0'),format='%H%M',errors='coerce').dt.time data['date'] = data[['month', 'day', 'year']].apply(lambda x: '/'.join(x), axis=1) data = data.drop(['year', 'month', 'day', 'hour', 'min'], axis=1) cols = ['date', 'dep_time', 'dep_delay', 'arr_time', 'arr_delay', 'cancelled', 'carrier', 'tailnum', 'flight', 'origin', 'dest', 'air_time', 'distance', 'duration'] data = data.reindex(columns=cols) print(data.tail()) # def timeStrFormat(time): time = str(time) newTime = time[:-2] + ':' + time[-2:] return … -
Django duplicate queries with manager related
I'm working on optimizing my ORM queries. I have two apps, 'app1' and 'app2'. One class of 'app2' has a foreign key to a class of app1 as follows: #app1/models.py class C1App1(WithDateAndOwner): def get_c2_app2(self): res = self.c2app2_set.all() if res.count() > 0: return res[0] else: return None #app2/models.py class C2App2(WithDateAndOwner): c1app1 = models.ForeignKey("app1.C1App1") is_ok = models.BooleanField(default=False) Now I display the C2App2 for all instances of C1App1 in the admin page: #app1/admin.py @admin.register(C1App1) class C1App1Admin(admin.MyAdmin): list_display = ("get_c2_app2") list_select_related = () list_prefetch_related = ("c2app2_set",) list_per_page = 10 prefetch_related reduces this query: SELECT ••• FROM `app2_c2app2` WHERE `app2_c2app2`.`c1app1_id` = 711 Duplicated 19 times. to: SELECT ••• FROM `app2_c2app2` WHERE `app2_c2app2`.`c1app1_id` IN (704, 705, 706, 707, 708, 709, 710, 711, 702, 703) ORDER BY `app2_c2app2`.`id` DESC And it's fine. Now if I want to filter the query on C2App2's attribute 'is_ok': #app1/models.py class C1App1(WithDateAndOwner): def get_c2_app2(self): res = self.c2app2_set.filter(is_ok=False) if res.count() > 0: return res[0] else: return None I still have this prefetched query: SELECT ••• FROM `c2app2_set` WHERE `app2_c2app2`.`c1app1_id` IN (704, 705, 706, 707, 708, 709, 710, 711, 702, 703) ORDER BY `app2_c2app2`.`id` DESC but with that one duplicated for each displayed instance of C1App1 (10). : SELECT ••• FROM `app2_c2app2` WHERE (`app2_c2app2`.`c1app1_id` … -
jQuery event preventdefault and continue
I am currently working on a Django project and am using the Django admin and its jQuery to add a modal between the submit button and the real form submit. To achieve this I've implemented the following: var submit_form; django.jQuery('form').submit(function (event) { event.preventDefault(); submit_form = this; modal.open(); }); and in modal close function I'm using: submit_form.submit(); This actually works, but I loose the Django admin functionality of the "Save and add another" and "Save and continue editing" buttons. They all do now the same action as the default submit button. The only thing added to the two other submit buttons is a name attribute: <input type="submit" value="Save" class="default" name="_save"> <input type="submit" value="Save and add another" name="_addanother"> <input type="submit" value="Save and continue editing" name="_continue"> I did also check into event and used event.currentTarget.submit(); in modal close function, but this did not actually work either. Does someone have an idea how to properly prevent default submit and execute it later? Thanks. -
Django, Deferred Attribute Error
I am in a ListView that is named PortfolioView. I am trying to retrieve all the items that a user has entered into the model, which is named "Prospect". To do this, I try the following: def get_context_data(self, **kwargs): Prospect.objects.all().filter(owner__username=self.request.user) context = MakeGraphs(Prospect.psuccess, Prospect.hc_type) return super(PortfolioView, self).get_context_data(**context) However, when I run the function MakeGraphs I get an error saying that the operation cannot be ran on a Deferred Attribute. I don't understand why it is getting returned as a Deferred Attribute. Suggestions? -
Sphinx + AutoDoc Fails in when using django.contrib.auth.models import User
Hi I am currently trying to setup of sphiinx for setting up my documentation in my django project. My Django Version is 2.0.5 Here is my Conf.py file import os import sys import django sys.path.insert(0, os.path.abspath('..')) os.environ["DJANGO_SETTINGS_MODULE"] = "settings.development" from django.conf import settings settings.configure() django.setup() Whenever I try to run make html on a model referencing django.contrib.auth.models import User it fails with the following error RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I have made sure that django.contrib.contenttypes is present in installed apps. If I go an give explicit app labels into the django package files, it does work, but i dont want to follow that hackish way. -
How to get last updated product in Django restframe work?
Here i have mentioned my model,serializer and view. Actually im new to this concepts. I don't how to get the last added product. Models.py class Products(models.Model): name = models.CharField(max_length=100) image = models.CharField(max_length=100, null=True) categories = models.ArrayModelField( model_container=Category, model_form_class=CategoryForm ) specifications = models.ArrayModelField( model_container=Specifications, model_form_class=SpecificationsForm ) description = models.CharField(max_length=1000) reviews = models.ArrayModelField( model_container=Reviews, model_form_class=ReviewsForm ) drizzly = models.BooleanField(default=False) complete = models.BooleanField(default=False) comment = models.CharField(max_length=500) click_count = models.IntegerField() serializer.py class ProductsSerializer(serializers.ModelSerializer): class Meta: model = Products fields = ('id', 'name', 'image', 'categories', 'specifications', 'description', 'reviews', 'drizzly', 'complete', 'comment', 'click_count') views.py class ProductsViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = Products.objects.all() serializer_class = ProductsSerializer Please tell me how to do that?. -
'Cannot interpret feed_dict key as Tensor: ' + e.args[0])
I have retrained the model using this code. Then followed instruction from this repo after cloning. Replaced newly generated labels.txt and graph.pb file. Then when posting an image to classify using this code , then it shows the following error. predictions = SESS.run(GRAPH_TENSOR, {'DecodeJpeg/contents:0': image_data}) File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 905, in run run_metadata_ptr) File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 1083, in _run 'Cannot interpret feed_dict key as Tensor: ' + e.args[0]) TypeError: Cannot interpret feed_dict key as Tensor: The name 'DecodeJpeg/contents:0' refers to a Tensor which does not exist. The operation, 'DecodeJpeg/contents', does not exist in the graph. -
Nested for loop in django template for variables
<tbody> {% for j in dat %} <tr> {%for h in hed %} <td>{{j.h}}</td> {% endfor %} </tr> {% endfor %} </tbody> want to get value by object.field_name from the model. I've tried {{ j }}.{{ h }} but it does not return the value instead returns obj1.field_name. Any possible method i should try. -
Why is request object not the same between a "native" view and a ModelViewSet?
I am building an API with Django Rest Framework (DRF) and enabled the authentication/registration through social apps. For authenticating users via their social accounts I use Django rest-framework Social Oauth2 and it works like a charm. To be sure my user is logged in I created a very simple view in the views.py of my app: def index(request): return HttpResponse("is_anonymous: %s" % request.user.is_anonymous) The result in the browser is the following (it means that the user is logged in): is_anonymous: False Now as I am building an API with DRF I may need to retrieve some data of the current user (from request.user) in one of my viewsets but in the following code, the result is not what I expected: class HelloViewSet(viewsets.ModelViewSet): queryset = Hello.objects.all() serializer_class = HelloSerializer # This is just a random ViewSet, what is # important is the custom view below @action(detail=False) def test(self, request): return Response(request.user.is_anonymous) Here the result shows that the user not logged in: True So the first view shows that request.user.is_anonymous = False and the second shows that request.user.is_anonymous = True. Both views are in the same file views.py in the same app. What do I miss here? We are not supposed to … -
How to use a variable from a custom registration form django
I have created a custom registration form in django but i can't seem to use the adress variable in my html code this is what i have for now: forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class RegistrationForm(UserCreationForm): email = forms.EmailField (required=True) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) address = forms.CharField(required=True) class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'address', 'password1', 'password2', ) def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] user.address = self.cleaned_data['address'] if commit: user.save() return user Views.py from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate from accounts.forms import RegistrationForm def index(request): return render(request, 'user_example/index.html') def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username= username, password=password) login(request, user) return redirect('index') else: form = RegistrationForm() context = {'form': form} return render(request, 'registration/register.html', context) Html {% if user.is_authenticated %} Your name is {{ user.username }} Your address is {{ user.address }} {% else %} You are not logged in {% endif %} And does anyone have an idea of how you make that each field is on a … -
Trying to Grab all the groups a User is a member of, But i'm not querying correctly
I am trying to grab all the groups that a user is a member of. here are the relevant files: groups.models from django.db import models from django.contrib.auth.models import User class Group(models.Model): name = models.CharField(max_length=255, unique=True) description = models.TextField(blank=True, default='') image = models.ImageField(upload_to='images/') members = models.ManyToManyField(User) def __str__(self): return self.name accounts/views.py def profile(request, user_id): user = get_object_or_404(User, pk=user_id) groups = Group.objects.filter(???) return render(request, 'accounts/profile.html', {'user':user}) I'm a bit of a newbie when it comes to querying, any help would be really appreciated! -
template tag add requires 2 arguments, 1 provided
I have used add before but getting this strange error this time: django.template.exceptions.TemplateSyntaxError: add requires 2 arguments, 1 provided in the following code: {% render_field form.full_name type="hidden" class="form-control" \ value=user.first_name|add:"something" %} However I dont get the error if I move add to with: {% with fullname=user.first_name|add:"something"%} {% render_field form.full_name type="hidden" class="form-control" value=fullname %} {% endwith %} -
Django template iteration / loop count based on condition
I'm trying to create an iteration like the a $i==0; $i++; from PHP in Django, based on a condition. {% for item in event.products %} {% if item.category = "Treat" %} Now - I want to be able to tell how many times has this condition been met (category = treat) and how to stop the for loop after 2 items that match that loop. Thanks! -
How to model an ERD when the relationships have own attributes in Django?
enter image description here Hi everyone! i have a problem that i don't know how to model "Brrowe by" relationship in the image in django? -
Inlineformset Saving Validation
I'm working on a project where i have two forms.I want to save its data using inlineformset_factory but i'm stuck with inlineformset_factory can't save. it generates a validation error instead. Here are my models,forms&views Models class Property(models.Model): title = models.CharField(max_length=100, null=False, blank=False) class Property_Image(models.Model): image = models.ImageField() Property = models.ForeignKey('Property', on_delete = models.CASCADE) Forms class PropertyForm(forms.ModelForm): class Meta: model = Property fields = [ "title", ] class ImageForm(forms.ModelForm): class Meta: model = Property_Image fields = [ "image", ] ImageinlnFormSet = inlineformset_factory(Property, Property_Image, form=ImageForm, extra=10) Views from .forms import ( PropertyForm, ImageinlnFormSet, ) def newlisting(request): current_user = request.user #listing = Property.objects.get(pk=Property_id) newproperty = PropertyForm(request.POST, request.FILES or None) rimg = ImageinlnFormSet(request.FILES or None, instance=instance) if newproperty.is_valid(): instance = newproperty.save(commit=False) rimg = ImageinlnFormSet(request.FILES or None, instance=instance) instance.user = request.user instance.save() newproperty.save_m2m() propertyimg = instance.id if rimg.is_valid(): instances = rimg.save(commit=False) for instance in instances: instance.Caption = 'image' instance.Property = propertyimg instance.save() return HttpResponseRedirect('/dashboard/') context = { "form": newproperty, 'user': current_user, "rimg": rimg, } return render(request, "new.html", context) Thanks for your help. -
What's the advantage of nested class over a class attribute?
Django nests the Meta class inside to the plural in models.py: class Entry(models.Model): .... class Meta: verbose_name_plural = 'entries' 'entries' overrides 'entrys'. I guess this could be done easily without enploying a class if I design Django. class Entry(models.Model): verbose_name_plural = 'entries' # set verbose_name_plural as a class attribute What's the advantage of nested class over a class attribute? -
Facing Device discovery agent issue in BEMOSS3.5
I am trying out BEMS system for which I am using device discovery agent, I am new to this so kindly provide proper guidance, Thank you in advance. 101 GET /socket_agent/devicediscoveryagent (::1) 3