Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to use a block tag ({% block %}) from base html template two or more times in derived html file in Django
I want to be able to reuse the same block tag multiple times in derived html. something like: base.html <body> {% block panel %} # some basic panel structure inside this block {% endblock %} </body> derived.html {% extends base.html %} --first panel <div class="col"> {% block panel %} # override things like panel header {% endblock %} </div> --second panel <div class="col"> {% block panel %} # again override some panel stuff from base template {% endblock %} </div> Is there anyway i can achieve this in Django? -
Dajngo: access the string value in a forms.CharField WITHIN the ModelForm class
Within the Form class below, I let the user enter a street name, a number and a zipcode. class MeldingForm(forms.ModelForm): street = forms.CharField(max_length=256, help_text="Street: ") number = forms.CharField(max_length=10, help_text="Number: ") zip = forms.ChoiceField(choices=((34000, 'TownA'), (34001, 'TownB'), (34010, 'TownC'), (34012, 'TownD'))) I want to automatically extract the coordinates by using the values (strings) of these three fields. I defined a method get_closest_coords() which takes these 3 strings as arguments (and works very well in other occasions) and tried this WITHIN the class definition so I can assign the value to the coordinate variables. lat, lng = get_closest_coords(street.__str__(), number.__str__()) coord_lat = forms.FloatField(widget=forms.HiddenInput(), initial=lat) I have tried various ways to acces the string value of these fields, but none has worked for now... -
Integrating C++ video streaming application with django webframework
We are developing a simple video streaming application that will stream a single channel video over a private WiFi network. The c++ application(using OpenCV) that does the video processing will reside on a Linux server. The users will be able to view the videos live by logging on to the same Linux server using a web interface. The number of users logging onto will be less than 10 at a time. We would like to have the video streaming over the network to be encrypted. The Linux server running the application(both c++ part and django webserver are on one machine) is a standard PC grade machine. Here is a small block diagram {(C++ Image/video processing)--->(webserver)}=====PrivateWifi========> Users(less than 10) My questions are How do i send the video stream from C++ application to the Web server,Here i am planing to use Django webframework? Is it a good way to use Django in this situation?What would be the correct way to do it? Pointers on encrypting the video will be welcome? -
Adding a conditional class to a Django field's label
I'm trying to refactor a Django template which renders fields manually (cf. https://docs.djangoproject.com/en/2.0/topics/forms/#rendering-fields-manually). The labels are generated as follows: <label for="{{ field.id_for_label }}" class="{% if field.value %}active{% endif %} {% if field.errors %}invalid{% endif %}"> </label> where the field is looped over using {% for field in form %} ... {% endfor %}. I'm trying to refactor this by writing a custom filter (cf. https://docs.djangoproject.com/en/2.0/howto/custom-template-tags/#writing-custom-template-filters). So far I've come up with the following. In the templatetags directory, I've added a label_with_classes.py which reads from django import template register = template.Library() @register.filter(is_safe=True) def label_with_classes(value, arg): return value.label_tag(attrs={'class': arg}) which I use to replace the HTML above with {{ field|label_with_classes:"active"}} The problem is that this doesn't actually do what the original template does; it always labels it with the class "active" and doesn't implement the conditional logic. My question: is implementing this logic possible using a filter? What does the value input argument to the filter function actually represent, is it the field.value (as its name suggests) or the field itself? -
How do I write regEx to recognize when a string has anything but a-z 0-9?
I need to write a regex pattern for recognizing when a string has regex in it. I am parsing Django urls.py file to look at what the user has specified as routes. Then in my middleware I'm looking at request.path, and I want to check if the url passed was a url that uses regex or just normal characters. My thoughts are to intercept the regex url and then parse urls.py lines to determine where the incoming request url is tied to. That way if I have a url like: /users/{userid}/delete or /users/{userid} or /{userid} I would normalize the url so that /users/1139/delete would be /users/user/delete I want to use a regex expression to recognize when the django url is specified with regex or if its a normal path. This would be an example of a url with regex in it: articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<slug>[\w-_]+)/ This is a normal path /test/helloworld I just need to determine when it has regex in it and normalize it so metrics searches can be ran easier. Not sure how to write the regex to determine if the string line has regex in it because im parsing the urls file line by line, and im super bad at … -
django custom template tag - import model blog error
I am trying to import a model class called BlogDetails to use in my customised template tags page. Here is the structure of my app: appname (directory) -->core (directory) -->models.py (file) -->templatetags (directory) -->customised_template_tags.py (file) Here is the import message in the customised_template_tags.py file. This is the same structure of other import statements I have used in my view files: from appname.core.models import BlogDetails Here is the error message: from myapp.core.templatetags.customised_template_tags import absolute_static, alternative_file, \ File "C:\Users\me\desktop\appname\appname\core\templatetags\customised_template_tags.py", line 11, in <module> from appname.core.models import BlogDetails ImportError: cannot import name 'BlogDetails' I have re-started my development server and I have read this thread and followed the suggestions in the answer and I have also read the django docs. Can anyone suggest the solution to my issue? -
How to resolve Django migrate stuck?
After I tried to makemigrations/migrate a change (adding a default value to a DateTimeField for testing) on my MySQL database with Django 2.0.2 it run into an error as I formatted the date wrong. Now after removing the default value changing the default value removing the table and recreating the model python manage.py migrate still shows the following error (last line): django.core.exceptions.ValidationError: ["'02.02.2012' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."] Like I said: I allready changed my code to (excerpt): class Task(models.Model): uploaddate = models.DateTimeField(auto_now_add=True) and run makemigrations several times. Why does migrate keep on showing my former mistake and wont import the new attribute correctly? Is this possibly a bug? Can I sort of "reset" migrate? -
Saving data in the database with Django
I've been trying to save my POST data to the database using the ModelForm but I couldn't make it go there for some reason.When I try to send the forms the page is redirecting me to the right place however the DB is still empty.I am not sure what am I doing wrong. forms.py class AddProblem(forms.ModelForm): class Meta: model = problem fields = ('lat','lng','email','importance','description','images') models.py class problem(models.Model): lat = models.BigIntegerField() lng = models.BigIntegerField() email = models.EmailField(max_length=70,blank=True) importance = models.IntegerField(default=1) description = models.TextField() images = models.FileField(upload_to='images/') published = models.BooleanField() def __str__(self): return self.email views.py def addproblem(request): temp_name = 'google_api/addproblem.html' form = AddProblem(request.POST,request.FILES) if request.method == 'POST': if(form.is_valid()): form.save() form = AddProblem() return redirect('/') else: messages.error(request, "Error") context = { } return render(request, temp_name, context) urls.py urlpatterns = [ path('', views.index, name='index'), path('add/', views.addproblem, name='addproblem'), ] template <form action="/add/" method="POST"> {% csrf_token %} <div class="form-group"> <label for="">Lat:</label> <input class="form-control" id="lat" name="lat" disabled> </div> <div class="form-group"> <label for="">Lng:</label> <input class="form-control" id="lng" name="lng" disabled> </div> <div class="form-group"> <label for="">Емайл</label> <input type="email" class="form-control" id="email" placeholder="name@example.com" name="email"> </div> <div class="form-group"> <label for="">Важност</label> <select class="form-control" id="importance" name="importance"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> <option>6</option> <option>7</option> <option>8</option> <option>9</option> <option>10</option> </select> </div> <div class="form-group"> <label for="">Описание на проблема.</label> <textarea class="form-control" … -
Displaying imagefield in Django without HTML
Hi everyone :) I am making a simple web server using Django where one of the fields in my model is an imagefield. I ask the user to upload an image and everything works: The user can select and image, and it gets saved into the location that I want it to. However, I do not know how to make it display. When I am on the web server, I can see the image link like this: image And I want to be able to click on the url and come to a page where I can see just the picture. However, when I click on the url right now, I am taken to the page I am currently on. It pretty much just reloads, but the url above has changed to the one I clicked on. # views.py class CreateView(generics.ListCreateAPIView): """This class defines the create behaviour of our REST Api""" queryset = BucketList.objects.all() serializer_class = BucketListSerializerPostOnly def perform_create(self, serializer): """Save the post data when creating a new bucketlist""" serializer.save() def image_upload(request): if request.method == 'POST': form = BucketListSerializer(request.POST, request.FILES) if form.is_valid(): m = BucketList.objects.get(pk='ID') m.model_pic = form.cleaned_data['image'] form.save() return #urls.py (not the main one, just the on in this … -
One-To-Many and Individual in Django
I've customized the django user object as follows, class User(AbstractBaseUser): mobile = models.CharField(max_length=100, unique=True) email = models.EmailField(max_length=255) username = models.CharField(max_length=255) full_name = models.CharField(max_length=255, blank=True, null=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) root = models.BooleanField(default=False) I also have a feed and a Source object, which has a one-to-many relationship. class Source(Base): name = models.CharField(max_length=255) class Feed(Base): headline = models.CharField(max_length=255) link = models.CharField(max_length=255) summary = models.TextField() published_date = models.DateTimeField() views = models.IntegerField(default=0) shares = models.IntegerField(default=0) source = models.ForeignKey(Source, on_delete=models.CASCADE,) Now I want to simulate a bookmarking action and thus associate many feeds with one user. How do I do that in Django. -
Avoid automatic ordering when concatenating two Django querysets
I am trying to return a queryset in Django to create a list for a view with it. Having the entries for a model indexed with id's from 1 to n (the id's correlate with creation datetimes, but let's not rely on this too much), my goal is to display the first entry as first in the resultant list, but order the rest of the list reversely -- from the most recent, i.e. with the highest id number to the lowest (so id=2 should be the last one). For now I have something like this: class ModelLC(generics.ListCreateAPIView): queryset = Model.objects.filter(id=1) aux_queryset = Model.objects.exclude(id=1).order_by('-created') queryset = queryset | aux_queryset serializer_class = ModelSerializer def perform_create(self, serializer): serializer.save(owner=self.request.user) (id is the index column and created is the datetime field with creation timestamp.) Upon joining the queries together the result inherits the sorting order and no matter how I rewrite it, the query, when it is actually executed, looks the same and the result is sorted by creation time in reverse order, which makes the id's also go from highest to lowest. Is it at all possible to force the query result to be "glued together" in such a weird way, but at the … -
Django - queryset output formatting
I am fairly new to Django, ran into the following problem: I have a model FundPrice storing daily prices of particular funds. I would like to retrieve this from a database and pass to a js based chart. views.py from django.shortcuts import render from fundmgmt.models import FundPrice def fund_details_cards(request): fp = list(FundPrice.objects.values('fund_id','value_date','price')) return render(request,"fundmgmt/fund_detail_cards.html", {'fund_prices': fp}) In my template, by using {{ fund_prices }} reference, the result I get is the following: [{'fund_id': 1, 'value_date': datetime.date(2016, 11, 9), 'price': Decimal('2.574557')}, {'fund_id': 1, 'value_date': datetime.date(2016, 11, 8), 'price': Decimal('2.572507')}, {'fund_id': 1, 'value_date': datetime.date(2016, 11, 7), 'price': Decimal('2.571724')}] Can I somehow format this output? E.g. get rid of these datetime.date(, Decimal( field type indicators? What I would like to print is the following: [{'fund_id': 1, 'value_date': '2016-11-09', 'price': '2.574557'}, {'fund_id': 1, 'value_date': '2016-11-08', 'price': '2.572507'}, {'fund_id': 1, 'value_date': '2016-11-07', 'price': '2.571724'}] -
LookupError: 'base64' is not a text encoding; use codecs.decode() to handle arbitrary codecs
Its showing error LookupError: 'base64' is not a text encoding; use codecs.decode() to handle arbitrary codecs. Last few lines when the execution stops are - thumbnail = resize(photo_data, 200, 200) File "/home/anurag/photoshare/app.py", line 406, in resize image_string = StringIO(img.decode('base64')) LookupError: 'base64' is not a text encoding; use codecs.decode() to handle arbitrary codecs begin photo uploading code photos uploaded using base64 encoding so they can be directly embeded in HTML ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif']) def allowed_file(filename):`` return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS @app.route('/upload', methods=['GET', 'POST']) @flask_login.login_required def upload_file(): if request.method == 'POST': uid = getUserIdFromEmail(flask_login.current_user.id) imgfile = request.files['photo'] caption = request.form.get('caption') album_id = request.form.get('album') tags = request.form.get('tags') photo_data = base64.standard_b64encode(imgfile.read()) thumbnail = resize(photo_data, 200, 200) cursor = conn.cursor() cursor.execute("INSERT INTO Photos (imgdata, thumbnail, user_id, caption, album_id) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}')".format(photo_data, thumbnail, uid, caption, album_id)) conn.commit() picture_id = cursor.lastrowid print (picture_id) print (tags) insert_tags(picture_id, tags) return redirect( url_for('get_album', id=album_id)) #The method is GET so we return a HTML form to upload the a photo. else: return render_template('upload.html', loggedin=True, albums=get_all_album_data()) end photo uploading code resizes if greater than (x,y) else returns original def resize(img, x,y): image_string = StringIO(img.decode('base64')) with Image.open(image_string) as image: if image.size[0] > 200 … -
Django AttributeError: 'DatabaseOperations' object has no attribute 'select'
I've got a GeoDjango instance connected to a PostGIS database backend. When I query a table in this database, I get the error in the title: AttributeError: 'DatabaseOperations' object has no attribute 'select' As suggested elsewhere, I checked to make sure that my local_settings.py file specified the correct database engine: 'ENGINE': 'django.contrib.gis.db.backends.postgis'. This is already correct in my settings file. How do you fix this problem? -
Refactoring a Django form which renders fields manually
I'm working on a code base which contains forms which are written along the lines of https://docs.djangoproject.com/en/2.0/topics/forms/#rendering-fields-manually. Here is a snippet of the form's template, which uses Django Widget Tweaks: {% load widget_tweaks %} {% csrf_token %} <div class="row"> <div class="input-field col s12"> {{ form.session_number|add_error_class:"invalid" }} {% if form.session_number.errors %} <span id="{{ form.session_number.id_for_label }}-error" class="error">{{ form.session_number.errors|join:", " }}</span> {% endif %} <label for="{{ form.session_number.id_for_label }}" class="{% if form.session_number.value %}active{% endif %} {% if form.name.errors %}invalid{% endif %}"> Session Number </label> </div> </div> <div class="row"> <div class="col s12"> <label for="email">Scheduled For</label> </div> {{ form.scheduled_for }} </div> {% if form.family.value %} <input name="family" required="" id="id_family" type="hidden" value="{{ form.family.value }}" /> {% else %} <div class="row"> <div class="input-field col s12"> {{ form.family|add_error_class:"invalid" }} {% if form.family.errors %} <span id="{{ form.family.id_for_label }}-error" class="error"> {{ form.family.errors|join:", " }} </span> {% endif %} <label for="{{ form.family.id_for_label }}" class="{% if form.family.errors %}invalid{% endif %}"> Family </label> </div> </div> {% endif %} <div class="row"> <div class="input-field col s12"> {{ form.expert|add_error_class:"invalid" }} {% if form.expert.errors %} <span id="{{ form.expert.id_for_label }}-error" class="error"> {{ form.expert.errors|join:", " }} </span> {% endif %} <label for="{{ form.expert.id_for_label }}" class="{% if form.expert.errors %}invalid{% endif %}"> Expert </label> </div> </div> <div class="row"> <div class="input-field col s12"> … -
Error template when using {%djng_all_rmi %} - django + AngularJs
I'm using django 1.1.10 with Angularjs to developping my first app . according to this document : http://django-angular.readthedocs.io/en/latest/remote-method-invocation.html when using this code : {% load djng_tags %} … <script type="text/javascript"> var tags = {% djng_all_rmi %}; my_app.config(function(djangoRMIProvider) { djangoRMIProvider.configure(tags); }); </script> i get this error : enter image description here Thanks for your help ! -
AttributeError: object has no attribute 'ordered' when iterating a dictionary of lists of formsets
I have A dictionary called FormDic. The Values of the dictionary are lists and the lists contain formsets. I have double checked that this is the case 100 different ways. In my template i have the following: {% for key, ItemList in FormDic.items %} {% for Formset in Itemlist %} xxxxx {% endfor %} {% endfor %} the x's are just placeholder. Now if I refer to the formset in any way, {{Formset}} {{Itemlist.0}}, whatever.... it throws a AttributeError: 'Item' object has no attribute 'ordered' Any help would be appreciated. I'm losing my mind on this. Thx -
Django - Session expiration renewal
I'm just getting interested in making web apps with Django and I'm struggling with a question about sessions. I wonder how to make a session expire if the user has not tried to connect to the website in a certain period of time (15 days for exemple). In other words, I would like to renew the expiration date of a user session each time he/she is connecting to the site. I scrapped a lot of websites but I couldn't find any valuable example. -
Iterate Over Object GET Request Python
We are working with Django to GET sales data from a server for a number of brands. The endpoint is below and requires an API key and password. API keys and password for each brand are stored in settings.py. How we pass through the brand name to the endpoint so that the data is pulled iteratively? brand = models.CharField(max_length=140) orders_endpoint = 'https://{api_key}:{password}@site.com/admin/orders/count.json?status=any' orders_url = orders_endpoint.format(api_key=settings.brand_API_KEY, password=settings.brand_PASSWORD) orders_response = requests.get(orders_url) orders_json = orders_response.json() orders = mark_safe(json.dumps(orders_json)) -
`docker up --build` yields ImportError: No module named django.core.management
I'm converting a working django application to run in Docker containers. #Dockerfile FROM python:3 RUN mkdir /code ADD . /code/ WORKDIR /code RUN pip3 -q install -r requirements.txt RUN ls $(python -c "from distutils.sysconfig import get_python_lib;print(get_python_lib())") CMD python manage.py runserver the penultimate line prints out my site-packages and shows django as one of the installed modules. adding RUN pip3 freeze shows Django==1.11.4 which is what I'd expect. Given this, I can't explain why i'm getting the ImportError -
How to create a prepopulated form based on an existing object in Django's admin
I'm setting up links within a Django admin list view, where I want the links to redirect users to a prepopulated form based on the existing object that the link appears next to within the list form. So essentially these added links will act almost like a "create new" button with a form that is prepopulated with some of the data from the existing object. Is it possible to do this within the framework? Or will I need to add in JavaScript for this functionality? Currently I have these links for the list view added via the admin class in my admin.py file (without any functionality tied to them just yet): def get_link(self, obj): return u'<a href="/%s/copy">Copy</a>' % obj.id get_link.allow_tags = True get_link.short_description = "" And the URL pattern is set up for these copy pages like this: def get_urls(self): urls = super(MyAdmin, self).get_urls() custom_urls = patterns( '', ( r'^(?P<id>\d+)/copy/$', self.admin_site.admin_view(CopyView.as_view()) ), ) return custom_urls + urls -
Extracting a path variable from an included URL pattern in Django
Been scratching my head quite a bit with this one, can't seem to figure out what I am doing wrong. So, the problem is that I cannot seem to extract the path variable that I want from a urls.py inside an app to pass it to the function that should be called when the path is visited. This URL configuration where I am trying to get it is a nested one that is included when one visits events/, here is how it looks: Root URL configuration: urlpatterns = [ url(r'^api/', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^admin/', admin.site.urls), url(r'^events/', include(event_urls)) ] And then the included URL conf from event_urls: urlpatterns = [ url(r'alarm/<alarm>', alarm) ] Should be pretty straight forward I imagine, but the above does not work, like at all! If I construct the URLs in this way, requesting to the path events/alarm/on will state that path does not exist. After this, I figured it could not match the URL, but I don't understand why or how to fix it. I thought (from the docs) that the part would match anything! Now, I did some more investigating that proved to me that using a pattern for the might be the right … -
Is it a bad practice to use sleep() in a web server in production?
I'm working with Django1.8 and Python2.7. In a certain part of the project, I open a socket and send some data through it. Due to the way the other end works, I need to leave some time (let's say 10 miliseconds) between each data that I send: while True: send(data) sleep(10) So my question is: is it considered a bad practive to simply use sleep() to create that pause? Is there maybe any other more efficient approach? -
Django Memcache not setting value
I am using AWS Elastic Cache as a backend which uses memcache. What I am basically trying to do is apply throttling to DRF. Now it uses cache to keep track of requests. The throttling works fine if I use default Django Cache, but if I switch to memcache it doesnt. What I tracked to it that memcache stores cache_keys differently. So, I changed the make_keys method, but that didnt work either. Any Idea on how to fix this? -
How to protect concurrent write of same number in Django Tastypie
A REST API implemented with Tastypie, which is to write a number into a table. To prevent 2 users to write same number into the table, and is_valid() is implemented in HelloValidation. transaction.atomic() is used to prevent concurrent write. Models.py class HelloModel ... RestApi.py from django.db import transaction from tastypie import resources from tastypie import validation class HelloValidation(Validation): def is_valid(self, bundle, request=None): """Length validation.""" return status class HelloResource(ModelResource): class Meta(object): queryset = models.HelloModel.objects.all() validation = HelloValidation() def dispatch(self, request_type, request, **kwargs): with transaction.atomic(): response = super(HelloResource, self).dispatch(request_type, request, **kwargs) return response This is my understanding: 1) Without transaction.atomic(). If 2 user write same number at same time, is_valid() will be True. For example, table has 1 row with number 10, 2 users write same number 20. Each 'thread' read table with 10, and 20 is valid, as it is not same number as 10. There is no protection of writing same number. Is that correct? 2) I added transaction.atomic(), but I am not sure what it does in this case, because is_valid = True. Does transaction.atomic() lock the table? If it locks the table, is_valid() can't be performed currently for 2 users, then, I know following code work. But, I …