Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The names of static files are specified without the static url
Django. The names of static files are specified without the static url. Example: <img src="my.png" /> How to do it? Thank you! -
Python Django Pass variable from template to view then subproccess
I have a django template where the user will input the file number stored as a variable. When submitted from the template the django view will run the subproccess with the variable passed into it. NOTE: when the template has a button the view calls the subprocess correctly but now i need to step it up and make a variable passed all the way through so the subproccess can extract data from said file. When this is a button the subproccess works but as mentioned i need to pass a variable all the way to the subproccess. This is the form in the template, please forgive my formatting as I didn't tab the def etc into this post/question. <form action="does_the_action" method="get" enctype="multipart/form-data"> <textarea id="PASSTHISVARIABLE" class="materialize-textarea"></textarea> <button class="btn blue light">run</button></form> This is the 'function' if you will in the view, everything is correctly imported etc. def does_the_action(request): request.POST.get('PASSTHISVARIABLE') #i had above line commented out when the button was the only thing in the template p = subprocess.Popen([sys.executable, r'C:\Users\navigatetoscript.py']+ PASSTHISVARIABLE) return HttpResponse ("<h4> Now running the script <h4>") extra bit in case your curious what the variable is needed for in the script. It goes into my django uploads folder and opens … -
__str__ returned non-string (type tuple)
I have a form that keeps throwing me an error in django, Ive tried searching online tried str() on my models but wouldnt work at all. Googled a couple of times tried a couple different methods but none worked still get the same django error page everytime i click the link to the form. TypeError: __str__ returned non-string (type tuple) my model # Injury Parameters -> SOI Level 2 # #################################### class SourceOfInjuryLevel2(models.Model): creator = models.ForeignKey('auth.User') id = models.AutoField(primary_key=True) soi_l1 = models.CharField(max_length=80) soi_l2 = models.CharField(max_length=80) status = models.CharField(max_length=8) created_date = models.DateTimeField(default=timezone.now) modified_date = models.DateTimeField(blank=True, null=True) modified_by = models.CharField(max_length=60, blank=True, null=True) def create(self): self.save() def __str__(self): return self.soi_l1, self.soi_l2, self.status my form # Soure of Injury Level 2 # ########################### class SourceOfInjuryLevel2Form(forms.ModelForm): options = (('Enabled', 'Enabled',), ('Disabled', 'Disabled')) soi_l1 = forms.ModelChoiceField( queryset=SourceOfInjuryLevel1.objects.filter(status='Enabled'), widget=forms.Select(attrs={'class': 'form-control'}) ) soi_l2 = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control'}) ) status = forms.CharField( widget=forms.Select( attrs={'class': 'form-control'}, choices=options ) ) class Meta: model = SourceOfInjuryLevel2 fields = ('soi_l1', 'soi_l2', 'status') My Views # New Source of Injury Level 2 # ################################ def new_source_of_injury_level2(request): form = SourceOfInjuryLevel2Form() if request.method == "POST": form = SourceOfInjuryLevel2Form(request.POST) if form.is_valid(): source_of_injury_level2 = form.save(commit=False) source_of_injury_level2.creator = request.user source_of_injury_level2.created_date = timezone.now() source_of_injury_level2.save() messages.success(request, 'Object Has Been Created') return … -
How can I include multiple querysets in a django view?
Is it possible to define multiple querysets within the view function? -
Displaying a foreignkey's value
So I have a model like this: class Season(models.Model): number = models.IntegerField() show = models.ForeignKey("Show") class Show(models.Model): name = models.CharField(max_length=255, null=True, blank=True) Inside my SeasonAdmin I can see that the show field has a dropdown box for the list of Shows, but the problem is that when I click on the dropdown box I just see a list of Show object. How would I make it show the object name instead of just Show object? -
Q object (creating it with OR connection type at once)
Django 1.10.1 from django.db.models import Q q = Q(title__icontains='r') print(q) >>> (AND: ('title__icontains', 'r')) I've just thought whether it is possible to create the same but with OR logical operation. I can obtain OR like this: for item in q_objects: query |= item Or somehow else (using lamdba). But I don't feel this Q object. And this question may help me understand it better. In other words whether it is possible to create via constructor an object which will show (OR: ('title__icontains', 'r'))? -
How to download a custom queryset?
class ExportPlacesView(TemplateView): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super(ExportPlacesView, self).dispatch(request, *args, **kwargs) def post(self, request, *args, **kwargs): print request.POST places_list=[] pk_list=[] if request.POST.get('area_choice')!= "all": selected_areas=self.request.POST.getlist('area_choice') print selected_areas areas = Area.objects.filter(pk__in=selected_areas) for area in areas: places_list.append(Fizzer.objects.filter(coordinates__intersects=area.polygon)) for place in places_list: for p in place: pk_list.append(p.pk) self.places=Fizzer.objects.filter(pk__in=pk_list) else: self.places=Fizzer.objects.all() return self.places This is my view to filter a model named Fizzer.And the resultent filtered querset is sel.places.How to download the queryset self.places using a link in html -
Django - Models.DateTimeField - Changing dynamically auto_now_add value
I have a Django model with a DateTimeField where auto_now_add is set to True. This works well. class Problem(models.Model): ... date_created = models.DateTimeField('created on', auto_now_add=True) I would like, when I create test data or when I load historical data, to bypass this paramater (auto_now_add set to False) to set the date as I want and switch back to the standard behaviour (auto_now_add set to True). Is there a way to dynamically change the class (by changing attribute of the class ?). This parameter has no impact on the database and is probably triggered during the save phase. I don't want :-) date_created = models.DateTimeField('created on', default=timezone.now) Thanks in advance -
Passing HTML Checkboxes into Django view
I am trying to pass the values checked on webpage as a parameter in django views. Right now in my views I hardcoded the value of TestSuite. But what I am trying to do is when I select multiple checkboxes, It should go to views as a parameter to TestSuite. I found some thing like "some_var = request.POST.getlist('checks')" But it is not working. Is there any way I can do this? layout.html <form class="quote-text scroller"> {% csrf_token %} <label class="checkbox"> <input type="checkbox" name="checks" value="1">REG_AGREED_SUITE01 </label> <hr> <label class="checkbox"> <input type="checkbox" name="checks" value="2">REG_AGREED_SUITE02 </label> <hr> <label class="checkbox"> <input type="checkbox" name="checks" value="3">REG_AGREED_SUITE03 </label> <hr> </form> models.py class Test_Suite(models.Model): Test_Suite_Name = models.CharField(max_length=100) class Meta: verbose_name_plural = "Test Suite" def __unicode__(self): return self.Test_Suite_Name forms.py class Test_SuiteMyForm(forms.Form): class Meta: model = Test_Suite fields = ('Test_Suite_Name',) views.py def Revo(request): if request.method == 'GET': cd1 = "<command>" cd2 = "</command>" test_runner_path = "Some_Location" test_runner_path2 = "This_Location" STB = "VMS_01" TestSuite = "REG_AGREED_SUITE02" report_location = "Reports_Location" j = jenkins.Jenkins('http://localhost:8080') mycommand1 = cd1 + test_runner_path + "\n" + STB + "\n" + TestSuite + "\nTrue \n" + report_location + cd2 mycommand2 = cd1 + test_runner_path2 + "\n" + STB + "\n" + TestSuite + "\nTrue \n" + report_location + … -
JQuery-mobile suppresing django form errors?
I have backend form validators, like this: def validate_60(value): if value < 0 or value > 59: raise ValidationError('Value has to be between 0-59') My form generates errors, I printed them from the view and form class: <ul class="errorlist"><li>gender<ul class="errorlist"><li>Please choose gender</li></ul></li><li>hour[&#39;Wrong time. Please, check the time fields.&#39;]</li></ul> They are also visible if I print the form in the terminal, exactly where they should be. `<tr><th><label for="id_hour">Hour:</label></th><td><ul class="errorlist"><li>Wrong time. Please, check the time fields.</li></ul> <select class="signup_select" id="id_hour" name="hour" required>` However nothing arrives to the template {{form.errors}} is empty. The usual loop does nothing. Is jquery-mobile somehow supresing django's errorlist? Can I supress this functionality somehow? On the other hand I discovered this in the response: {"form_errors": {"gender": ["Please choose gender"], "hour": ["Wrong time. Please, check the time fields."]}, "html": ... So far don't know how to use it. Also I probably don't want to. The form I use has around 30 fields, there is more than 100 templates involved in rendering the form all with info tooltips and error handling. It all works fine on a not mobile version. If this turns out to be a jquery thing I'd rather replace jquery-mobile ... however so far I have no clue … -
Launch django server from ide with virtualenv
I"m trying to launch the django server via and IDE (pycharm) via the pycharm gulp tool. The gulp task to run the server is: // Run django server gulp.task('runServer', function() { exec('python manage.py runserver', function (err, stdout, stderr) { console.log(stdout); console.log(stderr); }); }); However although this works fine from the command line it doesn't work within pycharm using the gulp tool. I get the error below for not activating the virtualenv first. Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ImportError: No module named django.core.management Is there a way to activate the virtualenv before running the django server with the gulp tool in pycharm (without breaking it from working in the command line)? -
django-tables2 flooding database with queries
im using django-tables2 in order to show values from a database query. And everythings works fine. Im now using Django-dabug-toolbar and was looking through my pages with it. More out of curiosity than performance needs. When a lokked at the page with the table i saw that the debug toolbar registerd over 300 queries for a table with a little over 300 entries. I dont think flooding the DB with so many queries is a good idea even if there is no performance impact (at least not now). All the data should be coming from only one query. Why is this happening and how can i reduce the number of queries? -
How to use str as a related_name?
In order to decrease duplications, I want to write a function, which should dynamically change the model and related_name. Currently I have this function: def criteria_choices_field(user_lang_group): queryset = PlaceCriteriaGroups.objects.filter( placecriteriatranslations__lang_group=user_lang_group).order_by('placecriteriatranslations__name') translations = OrderedDict() for criteria_group in queryset: name = criteria_group.placecriteriatranslations_set.get(lang_group=user_lang_group).name translations[criteria_group] = name return queryset, translations I need something like: def choices_field(user_lang_group, choice_type): if choice_type == 'places': model_name = PlaceCriteriaGroups translation_path = 'placecriteriatranslations' elif choice_type == 'something_else': model_name = ... translation_path = ... queryset = model_name.objects.filter(**{translation_path + '__lang_group': user_lang_group}).order_by(translation_path+'__name') translations = OrderedDict() for criteria_group in queryset: # How to handle this line? name = criteria_group.translation_path + _set.get(lang_group=user_lang_group).name translations[criteria_group] = name return queryset, translations So, model_name is not a problem, but how to work with translation_path in the line name = criteria_group.translation_path + _set.get(lang_group=user_lang_group).name? -
How can I set dynamic default values using model inheritance in Django?
I'm trying to use inheritance in Django models such that if I instantiate a child model it sets various default values automatically. I've looked at the answer to this question, which gives the following type of configuration: class Parent(models.Model): name = models.CharField(max_length=75, unique=True) class HaroldPerson(Parent): class Meta: proxy = True def __init__(self, *args, **kwargs): self._meta.get_field('name').default = "Harold" super(HaroldPerson, self).__init__(*args, **kwargs) # Other Person objects with different names, e.g., `BobPerson`, `AbigailPerson`. However, this method allows me to create two HaroldPerson objects without overriding the name (which is defined as unique in the Person model). I would want the second call to HaroldPerson() to raise an IntegrityError here. Is there a better way of setting defaults for my child model here? Or a better way of setting dynamic default values for a Django model? -
Django rest framewrok foreign key with generics.ListCreateAPIView
How it is possiable to get foreign key assigned in url with djangorestframework? class CommentList(generics.ListCreateAPIView): serializer_class = CommentSerializer pagination_class = StandardResultsSetPagination queryset = Comment.objects.all() def get(self, *args, **kwargs): serializer = CommentSerializer(comment, many=True) return super(CommentList, self).get(*args, **kwargs) My goal is to use this URL (urls.py): url(r'^event/(?P<pk>[0-9]+)/comments', views.CommentList.as_view()) Somehow i managed to get foreign key with this way class CommentLikeList(APIView): def get(self, request, *args, **kwargs): key = self.kwargs['pk'] commentLikes = CommentLike.objects.filter(pk=key) serializer = CommentLikeSerializer(commentLikes, many=True) return Response(serializer.data) def post(self): pass But i don't know how to get foreign key with such URL using ''generics.ListCreateAPIView'' http://127.0.0.1:8000/event/<eventnumber>/comments -
POST data from modelform_factory generated form
What I'm trying to accomplish is to save the data to the relevant model. Very much looking to mimic the Django admin interface. urls.py url(r'^admin/add/(\w+)', views.admin_add_object, name='admin_add_object'), view.py: def admin_add_object(request, model): if request.method == "POST": # The code I need to save the posted data else: model_name = apps.get_model("product", model) ModelFormSet = modelform_factory(model_name, fields=("__all__")) return render(request, 'product/admin/add.html', {'formset': ModelFormSet}) add.html Here I simply access {{ formset }} to get the relevant input fields. -
Jinja2 Environment ImportError in Django 1.10 with Python 3.5
I have a Django 1.10 project (with Python 3.5) setup like this: *Consider the red marks as mysite File jinja2.py defines this: from __future__ import absolute_import from django.contrib.staticfiles.storage import staticfiles_storage from django.urls import reverse from jinja2 import Environment def environment(**options): env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'url': reverse, }) return env And this file is called in settings.py like this: { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'environment': 'mysite.jinja2.environment', }, }, But when I run the server and visit a URL with view that calls a Jinja2 template, I get the following error: I spent several hours searching the Internet to find a solution, but unable to resolve this. The entire setup was done following the official Django documentation: https://docs.djangoproject.com/en/1.10/topics/templates/#django.template.backends.jinja2.Jinja2 Thanks for your response(s) -
Error 500 using apache 2.4: django ImportError: No module named 'myproject'
I am using Apache 2.4 with python 3.4 and corresponding version of mod_wsgi on a windows 2012 R2 server machine. All 64 bits. Right now after starting apache, I have this problem: Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at admin@example.com to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. So when going through the error log, I found those relevant lines (logging in debug mode): The 'Apache2.4' service is restarting. [Wed Oct 05 12:06:08.561983 2016] [mpm_winnt:notice] [pid 7756:tid 528] AH00424: Parent: Received restart signal -- Restarting the server. [Wed Oct 05 12:06:08.561983 2016] [mpm_winnt:debug] [pid 10092:tid 456] child.c(1157): AH00357: Child: Exit event signaled. Child process is ending. [Wed Oct 05 12:06:08.561983 2016] [mpm_winnt:debug] [pid 10092:tid 1000] child.c(735): AH00348: Child: Accept thread exiting. [Wed Oct 05 12:06:08.561983 2016] [mpm_winnt:debug] [pid 10092:tid 996] child.c(735): AH00348: Child: Accept thread exiting. [Wed Oct 05 12:06:08.577609 2016] [wsgi:warn] [pid 7756:tid 528] mod_wsgi: Compiled for Python/3.4.2. [Wed Oct 05 12:06:08.577609 2016] [wsgi:warn] [pid 7756:tid 528] mod_wsgi: Runtime … -
open edx, cant find resources, and very slow to load
I have the following site http://academia.softwareestrategico.com:86/ if you login/create account and join any course, when click on any content, it takes about 1 or 2 minutes to load. When checking developer tools, we found its a logo.PNG file (its trying to find it in 127.0.0.1 and other 2 or 3 resources are trying to be bound on 127.0.0.1, after 2 minutes it looks like it gives up and shows the page. To reproduce please sign up, and then enroll the course and join the url Example url: http://academia.softwareestrategico.com:86/courses/SoftwareEstrategico/ASE-005/2016_10/courseware/f802a62cd09244279dded3cd158169df/#entendiendo-interfaces-child -
How to customize `FileField` buttons in Django template?
I am trying to upload files and below is the screenshot, does anyone know how to customize the buttons too Bootstrap style buttons? Here's the template code: <form class="form-horizontal" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <p>{{ form.non_field_errors }}</p> {# WL file #} <p>{{ form.wlfile.label_tag }} {{ form.wlfile.help_text }}</p> <p> {{ form.wlfile.errors }} {{ form.wlfile }} </p> {# BL file#} <p>{{ form.blfile.label_tag }} {{ form.blfile.help_text }}</p> <p> {{ form.blfile.errors }} {{ form.blfile }} </p> <div class="form-group"> <div align="right" class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-primary">{% trans "Next" %}</button> </div> </div> </form> -
Nested Serializers in Django rest framework
The code I have these models : class Activity(models.Model): is_child_friendly = models.BooleanField() free_wifi = models.BooleanField() parking_avilable = models.BooleanField() class RouteOrdering(models.Model): route_id = models.ForeignKey(Route, on_delete=models.CASCADE) activity_id = models.ForeignKey(Activity, on_delete=models.CASCADE, related_name='tracks') day = models.IntegerField() order = models.IntegerField() class Meta: ordering = ['order'] And these Serializers: class ActivitySerializer(serializers.ModelSerializer): class Meta: model = Activity class RouteOrderingSerializer(serializers.ModelSerializer): class Meta: model = RouteOrdering fields = ('id','day','order','route_id','activity_id','tracks') The problem I want the RouteOrderingSerializer to return also the activity with the same activity_id. For this I thought I should use nested serializers. What I've tried I've tried adding a nested serializer like so: activity = ActivitySerializer( read_only=True) But this resulted no output in the endpoint. I know this is not the use case presented in the documentation, and this is probably why its noy working. Ill be glad to see what code will work to get this done :) -
Djangosum two fields from different tables
I use the code below to sum fields in different tables. However, when there's no record that matches table1_id in table2, django returns None Table 1 id val 1 2 2 3 Table 2 id val table1_id 1 5 1 The query below would return: 7 None How would I return: 7 3 Django query: SomeModel.objects.filter( some_filters ).annotate( var=ExpressionWrapper( F('val') + F('table2__val'), output_field=FloatField() ) ) -
How to embed python code in HTML5 (Django)
I am using Python 3.4 /Django and i want to embed my python code in HTML5 Like: <h1>print("this is py code")</h1> //this thing has 2 be put in the middle of the document means if d page is of 100 lines ,"this is py code" has 2 be sumwhere at 51'st line similar 2 PHP like:] <h1><?php echo "hi there php" ?></h1> How is it possible? 2) Secondly how do i import a python script from other folder in the same project in html5 ? -
django migrate failing after switching from sqlite3 to postgres
I have been developing a Django project using sqlite3 as the backend and it has been working well. I am now attempting to switch the project over to use postgres as the backend but running into some issues. After modifying my settings file, setting up postgres, creating the database and user I get the error below when running manage.py migrate django.db.utils.ProgrammingError: relation "financemgr_rate" does not exist financemgr is an app within the project. rate is a table within the app. If I run this same command but specify sqlite3 as my backend it works fine. For clarity I will repeat: Environment Config1 Ubuntu 14.04, Django 1.10 Settings file has 'ENGINE': 'django.db.backends.sqlite3' Run manage.py migrate Migration runs and processes all the migrations successfully Environment Config2 Ubuntu 14.04, Django 1.10 Settings file has 'ENGINE': 'django.db.backends.postgresql_psycopg2' Run manage.py migrate Migration runs and gives the error django.db.utils.ProgrammingError: relation "financemgr_rate" does not exist Everything else is identical. I am not trying to migrate data, just populate the schema etc. Any ideas? -
Django materialize
So I have in my forms.py: auto_current_type = forms.ModelMultipleChoiceField(label="Авто:", queryset=Auto_current_type.objects.all(), widget=forms.CheckboxSelectMultiple()) My template: <div class="row"> <form class="col s6 offset-s3 l6 offset-l3 m6 offset-m3" method="post"> {% form %} {% endform %} <button class="btn waves-effect waves-light" type="submit" name="action">Поиск </button> </form> </div> But there how it looks like: As you can see there is name of the car types, and below you can see checkboxes with the same names of the car types. But checkboxes are not working. Any help?