Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Template rest one day from the date
In my view.py I obtain a date from my MSSQL database in this format 2018-12-06 00:00:00.000 so I pass that value as context like datedb and in my html page I render it like this {{datedb|date:"c"}} but it shows the date with one day less like this: 2018-12-05T18:00:00-06:00 Is the 06 not the 05 day. why is this happening? how can I show the right date? -
Convert datetime object inside Django ORM query
I want to filter queryset by year taken from datetime object, but using methods is not allowed with keywords. Thus, the following will raise an error: a = Activity.objects.filter(start_date.year=2018) Is there any other way to do this? -
Django Form - toggle field existence dynamically
Python 2.7.8 and Django==1.4.2 (Legacy app) I am having a few questions regarding the following form and view: class FormA(Form): field_a = CharField() def __init__(self, *args, **kwargs): if kwargs['initial']['test']: self.base_fields['field_b'] = CharField() super(FormA, self).__init__(*args, **kwargs) class ViewA(FormView): template_name = 'test form_class = FormA def get_initial(self): initial = super(ViewA, self).get_initial() initial['test'] = self.request.GET.get('test') I am trying to add a new field dynamically (based on the query param in this example). If a request with the query param test evaluating to True is made first, field_b will be included on FormA. But for all consecutive requests (even if test evaluates to False), FormA is still having field_b. The fix for this is to pop/del the field_b from self.base_fields and then evaluate the test variable. def __init__(self, *args, **kwargs): self.base_fields.pop('field_b', 0) if kwargs['initial']['test']: self.base_fields['field_b'] = CharField() super(FormA, self).__init__(*args, **kwargs) It seems like, the base_fields dict is being persisted across multiple requests. I have few questions regarding this: 1) Why is the base_fields dict not getting re-initiated on every request? 2) Is there a better solution to solve this issue instead of performing pop/del on base_fields? 3) If there is no other solution, does pop/del lead to a race condition? (If both the requests … -
How to pass json to render_to_response
I am trying to pass a json file through render_to_response to the front end. The front end is not a django template, its coded in JS, HTML etc. I am getting some weird error. Can anybody help me with that. I am attaching the code and the traceback. return render_to_response('ModelView.html', json.dumps(newDict)) Traceback (most recent call last): File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 35, in inner response = get_response(request) File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\PythonWorkspace\ScApp\ScApp2\views.py", line 78, in ScorecardApp20 return render_to_response('ModelView.html', json.dumps(newDict)) File "C:\Users\kxc89\AppData\Local\Programs\Python\Python37\lib\site-packages\django\shortcuts.py", line 27, in render_to_response content = loader.render_to_string(template_name, context, using=using) File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\backends\django.py", line 59, in render context = make_context(context, request, autoescape=self.backend.engine.autoescape) File "C:\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\context.py", line 274, in make_context raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__) TypeError: context must be a dict rather than str. -
How to prevent Django ModelAdmin from stripping whitespaces?
so I've defined readonly_fields in Django ModelAdmin with a callable which looks like this: class TestAdmin(admin.ModelAdmin): readonly_fields = ("test_field_with_whitespace",) def test_field_with_whitespace(self, obj): return ' Hello World' In the corresponding admin view the readonly field is shown as "Hello World" - so without the whitespaces. What can I do to show the whitespaces? -
Where do django templates load tags from?
I have forked some django-oscar apps to introduce my own models as per the documentation on how to do so, and I am currently customizine a website template consisting of static HTML to work with django, and to replace the default django-oscar store. django-oscar has a product model with a field category. I have added a collection model which contains products, and products now has a foreignkey to my collections model. When looking at the django-oscar default templates to see how they work and modify the template I am working on to work in a similar fashion, I see the following: {% load basket_tags %} {% load category_tags %} {% load product_tags %} and {% category_tree as tree_categories %} {% if tree_categories %} My question is, how and where is category_tags and category_tree defined? I would like to define something similar, ideally to get a list of collections shown on the page, and to take the name of a collection to be the title of my page. -
vscode doesn't recognized my django module app. Warning from vscode
I installed some extensions in Visual Studio Code for develop in Django. My only problem is when I'm trying to do this; import views from my_app from my_app_name import views I received a warning from Visual Studio Code. If a typed like this; from . import views I don't received any warning! But a would prefer the other form above. I have python 3.x installed on my laptop. I have Anaconda environment created. I have some extensions installed (Python, Django, Pylint,...) Note: My project run well because is only a warning but I would prefer that warning disappear. -
Django - How to display all items inside a Object
I have a Profile Object which has a many to many reationship with a Hobbies object. A profile is used for creating a User. Each User can also have a load of hobbies that are predefined. What I want to do is let Users pick some hobbies they are interested in. However, I am not sure how to display all these Hobbies and let Users pick them on the actual display. Here is the code: TYPES = ( ("Football", "Football"), ("Cricket", "Cricket"), ("Swimming", "Swimming"), ("Cycling", "Cycling") ) class Hobby(models.Model): myfield = MultiSelectField(choices = TYPES) And the User : class Profile(models.Model): email = models.CharField(max_length=200) hobbies = models.ManyToManyField(Hobby) And the HTML code I use is here: <span class="fieldname">Hobbies</span> {% for hobby in all_hobbies %} <input type="checkbox" name={{hobby}} value={{hobby}}> {{hobby}}<br> {% endfor %} However this only displays What I want it to display is all the hobbies with the choices, instead of the whole Object. I am not sure how to do this and would appreciate any help. -
Pass data from View to APIView
I'm currently trying to load dynamically a graph on my website using graphjs. What I want to do is to update data by choosing a time range or a specific datatype. I want it to be more flexible and only have two views; one for rendering the graph and other to return pertinent data. I think my date widget will pass data through HomeView with a post method. How can I pass date information to GenericDataView ? Or maybe there is an other way to do this kind of thing. For now I got something like : class HomeView(View): def get(self,request,*args,**kwargs): return render(request,'charts/charts.html') class GenericDataView(APIView): def get(self,request,*args,**kwargs): selected_data = getDataFromTimeRange() if selected_data is not None: return Response(selected_data) def getDataFromTimeRange(): // do things return data; In urls.py : urlpatterns = [ path('', views.HomeView.as_view(), name='homeView'), path('chart', views.GenericDataView.as_view(), name='api-data'), ] And in charts.hmtl : <div class="chart-container" url-endpoint='{% url "api-data" %}' style="position: relative"> <canvas id="myChart"></canvas> </div> -
Django Models - How do you add subtype choice when user selects choice?
I'm working on a project where they have various job types that I've tackled with CHOICES, however, I want to add conditionals for WHEN job type 1 is chosen, SUBTYPES x-y become choices. I am having trouble with the syntax of how you would do that. I've included my pseudocode below... I appreciate any help! from django.db import models class User(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Job(models.Model): name = models.CharField(max_length=255) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='jobs') JOB_CHOICES = ( ('carpentry', 'Carpentry'), ('cleaning', 'Cleaning'), ('electrician', 'Electrician'), ('handyman', 'Handyman'), ('hvac', 'HVAC'), ('painting', 'Painting'), ('pest', 'Pest'), ('plumbing', 'Plumbing'), ('roofing', 'Roofing'), ('property', 'Property'), ) jobType = models.CharField(max_length=30, choices=JOB_CHOICES, default='handyman') # If JobType = Carpentry: # CARPENTRY_CHOICES = ( # ('trim', 'trim') # ('sheetrock', 'Sheetrock') # ('windows', 'Windows') # ('doors', 'Doors') # ('cabinets and shelving', 'Cabinets and Shelving') # ('other', 'Other') # ) # jobType = models.CharField(max_length=30, choices=CARPENTRY_CHOICES, default='other') def __str__(self): return self.name Django Models Django Serializer /api editor -
Django : go back to correct paginator page
I have simple blog app that is using paginator for listing articles. I want to be able to add button in article detail page that will direct user to same page that this article is on. I want to take slug from current url and send it to paginator so that it directs user to ?page=X where article is on. I checked paginator docs and didn't find any info on how to retrieve page number of specific object. my views: def blog(request): posts = Article.objects.all() paginator = Paginator(posts, 3) page = request.GET.get('page') posts = paginator.get_page(page) return render(request,'blog.html',{'posts':posts}) def article_id(request,slug): articleid = Article.objects.get(slug=slug) return render(request, 'blogid.html', {'article':articleid}) my urls: urlpatterns = [ url(r'^$', views.blog, name = 'blog'), url(r'^(?P<slug>[\w-]+)/$', views.article_id, name = 'article_id'), ] -
How to add .html suffix in wagtail
The wagtail url only accept slug type, no '.' acceptable. Can I add suffix like ".html" at end of url, like "/faq.html" instead of "/faq/"? -
One table filter is working fine for me but ,here i need to filter two tables filter in django which is not working
models.py: class Department(models.Model): department_id = models.AutoField(primary_key=True) department_n_key = models.CharField(max_length=30,blank=True,unique=True) hospital_short_name = models.CharField(max_length=20) department_name = models.CharField(max_length=50) class EmployeesMaster(models.Model): employee_id = models.AutoField(primary_key=True) employee_n_key = models.CharField(max_length=30,blank=True,unique=True) first_name = models.CharField(max_length=30) middle_name = models.CharField(max_length=30, blank=True, null=True) last_name = models.CharField(max_length=30, blank=True, null=True) gender = models.CharField(max_length=12, blank=True, null=True) class PatientMaster(models.Model): patient_id = models.AutoField(primary_key=True) patient_n_key = models.CharField(max_length=30,blank=True,unique=True) first_name = models.CharField(max_length=30) middle_name = models.CharField(max_length=30, blank=True, null=True) last_name = models.CharField(max_length=30, blank=True, null=True) age = models.IntegerField(blank=True, null=True) views.py i need to apply this in django: SELECT * FROM appointment_master WHERE patient_type='something' andappointment_master.department_n_key IN (SELECT department.department_n_key FROM department WHERE department.department_name='something') help somebody to apply this in django -
Sending GET request for an IP address
I need to send a request to a web server of mine to start a stream. The web server is located at 0.0.0.0 (of course I can change the address). How can I send a "GET" request to that server? I already tried using httplib or urllib2 or 3 and they seem not to work with IP address. Note: I know that a local DNS server will map the address to a url, but that is not the goal to set up the server every time I want to execute the code in a new network. Thank a lot. -
Out of memory issue with celery and redis - need help tuning celery
I have a django 2 app that uploads 1 to many photographs (~3-4 MB per image), and uses face_recognition to find the face locations and encoding. The images and created thumbnails are saved to the file system and the data in a mysql database. The app works, except that uploading and finding 16 faces in 3 photos takes about 2 min and uses about 6.5 GB of RAM and no swap (my Ubuntu 18.04 system has a total of 16 GB of RAM and runs with about 8 GB of free memory and 1 GB of swap.) When I use celery (v 4.2.1) and redis (v 2.10.6) and redis-server (v 4.0.9) to offload the face recognition from my django app, the celery tasks run out of memory and the workers are killed before they finish There is 1 celery task per photo for face recognition and django handles the file uploading, thumbnail creation and db writingfor the three photos. Usually 1 task will finish, but not always. I even added exponential retries for the celery tasks, but that did not help. Looking at top during the celery face recognition, I noticed that the amount of free RAM stayed around 6 … -
json loads taking unusually long time while running inside kubernetes pod
I have a http django server deployed through docker container in a kubernetes cluster. Issue is - json.loads in post request is taking too much time(~400ms) for 50Kb Json only. I tried the json.loads from shell_plus inside the pod, it is taking normal timing(<1ms). Also same django application is taking normal time in my local setup. What could be issue, that with django application same process is taking too much long inside pod ? How to debug such issue ? I am logging json load time like this - t1 = datetime.datetime.now() request_json = json.loads(request.body) print("time taken by json loads is {}".format(datetime.datetime.now() - t1)) Server configuration - django application via gunicorn server inside kubernetes pod Tried - Increasing CPU utilisation, memory utilisation different json parsers like (json and ujson), tried cpickle as well. -
Cannot upload image to MEDIA_ROOT using Mongoengine ImageField
I'm trying to upload images using Mongoengine ImageField. But after uploading a test image,I got page not found by visiting http://127.x.x.x:xxxx/media/testimage.png. "/Users/xxx/Documents/basedir/media/testimage.png" does not exist myproject/settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') myproject/myapp/models.py from mongoengine import Document, ImageField class Image(Document): image = ImageField(upload_to="") filename = fields.StringField() myproject/urls.py from django.conf import settings urlpatterns = [ #bla ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) What did I do wrong? -
Django - Page not found 404 but urls are defined?
Im trying to get from my test site to the results site after getting some inputs by a form but im getting this Error: Using the URLconf defined in UnserProjekt.urls, Django tried these URL patterns, in this order: 1. admin/ 2. test/ [name='ctest'] 3. test/ [name='results'] 4. instruction/ 5. 6. home/ 7. ^static\/(?P<path>.*)$ The current path, test/ctest, didn't match any of these. Why doesnt it work? If you need my views etc. just ask :) -
Error:inconsistent use of tabs and spaces in indentation
i have a model about. class About(models.Model): displayname=models.CharField(max_length=50) email=models.EmailField(max_length=70) website=models.CharField(max_length=200) photo=models.FileField(upload_to='uploaded_image') des=models.TextField() def __str__(self): return self.name it's giving me above error in this line email=models.EmailField(max_length=70) -
Change label on required select date widget in django
So I want to change the label on my select date widget on django, preferably to the current date, but even just saying "Month" "Year" etc would suffice. I dont want it to just say "January 1 1980" as is the default. I know that to use the empty_label in my widget, my field has to be blank, or not required, in my model. However, my field is required, but I want the field to match another non-required widget. Here is my form code: class AnimalForm(forms.ModelForm): class Meta: model = Animal fields = ['animal_id','species_strain','dob', 'dod', 'sex', 'source', 'parents', 'labloc', 'notes'] widgets ={ "dod":forms.SelectDateWidget(years=range(1980,2050), empty_label=("Year", "Month", "Day")), "dob":forms.SelectDateWidget(years=range(1980,2050), empty_label=("Year", "Month", "Day")), } For clarification, dob is required while dod is not. But I want them to at least look the same on the webpage. If possible, I would LOVE to make the default value the current date, but I need to be able to at least edit the fields first. So how can I do this? I've tried googling it to no avail. Thank you! -
Django form submission redirection issue
I have created a customer model and a store model. when I add/edit a store via form its getting redirected to the empty list of page rather than list of stores. I will have to refresh the page to see the content. Here is my code, can someone help me to identify the mistake and correct please? Views: def save_store_formview(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True stores = Store.objects.all() data['html_store_list'] = render_to_string('App_CUS/stores/partial_store_list.html', { 'stores': stores }) else: data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) def store_createview(request): if request.method == 'POST': form = StoreForm(request.POST) else: form = StoreForm() return save_store_formview(request, form, 'App_CUS/stores/partial_store_create.html') def store_updateview(request, pk): store = get_object_or_404(Store, pk=pk) if request.method == 'POST': form = StoreForm(request.POST, instance=store) else: form = StoreForm(instance=store) return save_store_formview(request, form, 'App_CUS/stores/partial_store_update.html') def store_deleteview(request, pk): store = get_object_or_404(Store, pk=pk) data = dict() if request.method == 'POST': store.delete() data['form_is_valid'] = True stores = Store.objects.all() data['html_store_list'] = render_to_string('App_CUS/stores/partial_store_list.html', { 'stores': stores }) else: context = {'store': store} data['html_form'] = render_to_string('App_CUS/stores/partial_store_delete.html', context, request=request) return JsonResponse(data) Forms: class StoreForm(forms.ModelForm): class Meta: model = Store fields = '__all__' html: {% for store in customerdetail_view.stores.all %} <tr class="item"> … -
Django preventing a book from being submitted twice
I have the following a form and model: class Book(models.Model): name = models.CharField(max_length=128, null=True, blank=True) author = models.CharField(max_length=128, null=True, blank=True) borrower = models.ForeignKey('core.User') class BookForm(forms.ModelForm) class Meta: model = Book fields = ("name", "author", "borrower") @login_required def private(request): if request.method == 'POST': form = BookForm(request.POST) if form.is_valid(): book = form.save(commit=False) book.save() else: form = BookForm() return render(request, 'borrow.html', {'form': form, }) The website allows the user to submit a new book to their own private page. The problem happens when a User tries to submit a book that has been submitted before by the same user. Where should the verification be implemented and how? - If I choose to verify it in the form clean method, then I have no option of getting the request to see which user it was. - If I choose to verify it in the view, then how can I make the form invalid after it has already been validated? -
OSError: dlopen() failed to load a library: cairo / cairo-2 / cairo-gobject-2
my view @api_view(['GET']) @renderer_classes((JSONRenderer,TemplateHTMLRenderer,BrowsableAPIRenderer)) def admin_order_pdf(request, order_id): # def admin_order_pdf(request, order_id): order = get_object_or_404(Direct, id=order_id) price=order.price discount=order.discount total=price-discount html = render_to_string('bill/bill.html', {'order': order,'total':total}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename=\ "order_{}.pdf"'.format(order.id) weasyprint.HTML(string=html).write_pdf(response, stylesheets=[weasyprint.CSS( settings.STATIC_ROOT + 'css/pdf.css')]) return response and when i tried to run the server or try to run the weasyprint code i'm fired up with an error as raise OSError("dlopen() failed to load a library: %s" % ' / '.join(names)) OSError: dlopen() failed to load a library: cairo / cairo-2 / cairo-gobject-2 i have updated my environment variables as well C:\Program Files\GTK3-Runtime Win64\bin to this location -
Trying to sanitize very basic MySQL SELECT in Python/Django
This is driving my nuts. I have this very basic query that works without the sanitization statement but breaks with it. Everything I've read says to do it this way. query = "SELECT COL1 FROM A_TABLE %s" queryUserInput = "WHERE COL1 = 'user input value'" cursor.execute(query, (queryUserInput,)) I receive the error: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' WHERE ... Top of the stack: C:..\env\lib\site-packages\mysql\connector\connection_cext.py in cmd_query raw_as_string=raw_as_string) Python 3.7 Django 2.1.3 Any advice is very appreciated. -
How to check if a channel is empty
In Channels 1 I could get the number of pending messages in a channel with: RedisChannelLayer().channel_statistics(channel_name).get("messages_pending") I used this during automatic tests to ensure that the channel is empty before starting the next test to avoid an undesired influence of old channel messages. How can I check if a channel is empty or get the number of pending messages in a channel in Channels 2?