Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : CX_Oracle : Not setting Purity to self in DRCP connections
I wanted to use DRCP with Django Rest application I created. Settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': ('(DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP) (HOST = ' HOST_VALUE' ) (PORT = 'POST_VALUE'))) (CONNECT_DATA = (SERVICE_NAME = ' DATABASE_SERVICE_NAME ')(SERVER=POOLED)))'), 'USER': 'sys', 'PASSWORD': 'SYS_PASSWORD', 'OPTIONS': { 'purity': cx_Oracle.ATTR_PURITY_SELF, 'cclass': 'test', 'threaded': True, 'mode': cx_Oracle.SYSDBA }, } } However, querying the db(select * from v$cpool_cc_stats;) for the DRCP stats showed that NUM_HITS=0, NUM_MISSES=NUM_REQUESTS. Another query (select * from V$CPOOL_CONN_INFO;) showed that the PURITY of the queued requests is NEW. Why is the purity NEW and not SELF Because of this the NUM_HITS=0 as the sessions are not being re-used. -
How get name of prev months short from or full form numbers in python/Django
Forgive me If i'm asking a very stupid questions. I'm trying to get name of the past months instead of numbers my django framework: Example: For instance, if I have 12, I want to return december or dec Right now, I had this external python scripts that sort the day, weeks, month and years. Here the codes for external scripts Name;basicfun: (only on the months) #basicfun codes (external python scripts) def selectDates(query): if query == 'Previous-Months': dataset = datetime.now().month - 1 dataset.strftime("%b") return dataset It will return to my django view to use as a filter for Queryset Here the Frame works codes on view: #Django view def ph(request): query = request.GET.get('dateRange') fill = selectDates(query) data = tank_system.objects.all().filter(datetime__contains=fill) return render(request, 'FrounterWeb/extends/ph.html', {'tank': data}) Solution I had try This link: Get month name from number 1. dataset = datetime.now().month - 1 dataset.strftime("%b") error: Exception Type:AttributeError Exception Value:'int' object has no attribute 'strftime' -
django model field check instance
I have a models like class MyModel(models.Model): name = models.CharField() updated_on = models.DateTimeField() Now I am querying this like m = MyModel.objets.get(id=2) Here I want to check if the field is of certain type I want to do some stuff like from django.db.models import DateTimeField if isinstance(m.updated_on, DateTimeField): // do something But here I am getting false. Is there any workaround by which I can achieve this ?? -
Django - grouping a manytomany field sum
Django 2.1, python 3.6 I have two models class B(models.Model): id = models.CharField(max_length=36, blank=False, primary_key=True) c = models.CharField(max_length=15, blank=False) d = models.IntegerField(default=1) class A(models.Model): id = models.CharField(max_length=50, primary_key=True) b = models.ManyToManyField(B, through='AB') @property def grouped_c_value(self): self._grouped_c_value= self.b.aggregate(total=models.Sum('d'))['total'] return _grouped_c_value The property field grouped_c_value successfully returns the correct count. However, I want to now group the sum by c? C shows a char field, but there are only up to 7 options in there so it won't blow up on me. Does anyone know how to do this? -
Can't see apps from existing Django project on Wagtail CMS
I'm trying to integrate my Django project with Wagtail CMS. As it is done with existing Django project, I'm trying to follow this documentation. After having done that, I can see my users on Wagtail, but not my apps. Should I need additional steps to bring my existing Django apps to Wagtail? What I'm guessing is if the below two code snippets don't matter with it's added position. The documentation says to add them without specifying where exactly before or after. For INSTALLED_APPS 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'modelcluster', 'taggit', For MIDDLEWAR 'wagtail.core.middleware.SiteMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware', -
raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'file'
I am working on a django web application. The application holds two forms in the same page. The first form is for uploading an image and the second form is a description for the image. After the user uploads an image and clicks on the upload image button, an image classifier classifies the image and autofill some parts of the second form. once the second form is filled the save button can be clicked to save the form as an entry. The problem is when the upload button is clicked and the classifier runs the page is reloaded when parts of the second form is filled. Hence the first form no longer holds any image. So when I try to save the form I get a MultiValueDictKeyError on the first form. Here is the complete error message File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\datastructures.py", line 79, in getitem raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'file' This is my code so far models.py class Item(models.Model): title = models.CharField(max_length=100) pattern = models.CharField(max_length=100) color = models.CharField(max_length=100) user = models.CharField(max_length=100) img = models.ImageField(upload_to='item/img/', null=False, blank=False) def __str__(self): return self.title def delete(self, *args, **kwargs): self.img.delete() super().delete(*args, **kwargs) forms.py from .models import Item class ItemForm(forms.ModelForm): class Meta: model = Item fields = ('title', 'pattern', … -
Page still refreshing while using ajax with django
I'm using my own custom form. Which looks like: {%extends 'base_template.html'%} {%block title%} <title> Simple Ajax Demo </title> {%endblock%} {%block javascript%} <script> $(document).ready(function(){ $("#formi").submit(function(event){ $.ajax({ type:"POST", url:"{% url 'haha:ajax' %}", data: { username : $('#username').val(), password : $('#password').val(), csrfmiddlewaretoken: {% csrf_token %}, }, success: function(data){ alert('asdas'); }, }); }); }); </script> {%endblock%} {%block content%} <div> <form method="post" id="formi"> {%csrf_token%} Username:<input type="text" name="username"><br> Password:<input type="text" name="password"><br> <button type="submit">CLick Me</button> </form> </div> {%endblock%} I've got two input fields with name password and username, to be saved to the table User. View.py def ajax(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] Users.objects.create(username=username, password=password) return render(request,'core/ajax.html') I've tried with the GET method too. But still the page gets refreshed. Also tried firing the Ajax call while clicking the button, but it says something like multiple-dict value error. Also tried with username = request.POST.get('username') password = request.POST.get('password') -
Django's F() does not seem to work with Potgresql
Im trying to get my Django powered website deployed on Heroku. While in development I used Sqlite as a database, and when I deployed on Heroku, I chose a Postgres database, what led to one problem that I have not experienced while developing with Sqlite. In my views.py I have a following code: products = Product.objects.order_by(F('stockQty') - F('minQty')) I tried to relay some of the sorting from the server (python) to the database with the above code. It worked as expected in Sqlite, but in Postgres I get the following error: django.db.utils.ProgrammingError: operator does not exist: character varying - character varying LINE 1: ...g_product" ORDER BY ("catalog_product"."stockQty" - "catalog... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. It seems the error refers to the fact that Postgres sees my two fields that I am trying to subtract as two characters and due to some built in strong casting it refuses to do so, while Sqlite has some softer rules. I could go with that and debug, but here is the code in my models.py: #Quantity in Stock stockQty = models.IntegerField(help_text='Enter current quantity in stock') #Min Quantity minQty = models.IntegerField(help_text='Enter … -
Port forwarding between docker containers
I run a nginx container sudo docker run --name some-nginx -d -p 8030:8030 --rm -v /home/username/nginx_test/nginx.conf:/etc/nginx/nginx.conf:ro nginx:1.15.8alpine /home/username/nginx_test/nginx.conf: user nginx; worker_processes auto; error_log /dev/null; pid /var/run/nginx.pid; events { worker_connections 1024; multi_accept on; use epoll; } http { include /etc/nginx/mime.types; default_type application/octet-stream; ## # Gzip Settings and client, log settings ## server { listen 8030; set $port_endpoint http://127.0.0.1:8080; location / { proxy_pass $port_endpoint; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-NginX-Proxy true; proxy_redirect off; } } } On http://127.0.0.1:8080, there is django project docker container. It run by type: sudo docker run --name some-nginx -d -p 8080:8080 --rm some/django:0.1, and It has uwsgi file: [uwsgi] chdir = /smaple_django wsgi-file = /smaple_django/smaple_django/wsgi.py master = true processes = 10 http = :8080 vacuum = true max-requests = 1000 harakiri = 10 enable-threads = true lazy-apps = true single-interpreter = true It works well individually so that my browser at http://127.0.0.1:8080(django container), it shows django front page. But When I go to http://127.0.0.1:8030 in my browser, it shows 502 bad gateway on nginx. I think it has to be connected to http://127.0.0.1:8080 by these nginx.conf lines: server { listen 8030; set $port_endpoint http://127.0.0.1:8080; location / { proxy_pass $port_endpoint; proxy_set_header Host $host; … -
Django Copying Form Data to another Form
I have two simple Django forms PDEM & GUARANTOR. I am trying to figure out how to copy data from PDEM form to the GUARANTOR form if Patient_Relationship = Self. class PDEMForm(forms.Form): first_name = forms.CharField(required=True, max_length=255, widget=forms.TextInput(attrs={'placeholder': 'Mike','class':'form-control' , 'autocomplete': 'off','pattern':'[A-Za-z ]+', 'title':'Enter Characters Only '})) Middle_Name = forms.CharField(required=False, max_length=10) last_name = forms.CharField(required=True, max_length=255, widget=forms.TextInput(attrs={'placeholder': 'Smith','class':'form-control' , 'autocomplete': 'off','pattern':'[A-Za-z ]+', 'title':'Enter Characters Only '})) sex = forms.ChoiceField(required=True, choices=SEX) class GUARANTORForm(forms.Form): Patient_Relationship = forms.ChoiceField(required=True, choices=PTREL) guarantor_first_name = forms.CharField(required=True, max_length=255, widget=forms.TextInput(attrs={'placeholder': 'Guarantor First Name','class':'form-control' , 'autocomplete': 'off','pattern':'[A-Za-z ]+', 'title':'Enter Characters Only '})) guarantor_last_name = forms.CharField(required=True, max_length=255, widget=forms.TextInput(attrs={'placeholder': 'Guarantor Last Name','class':'form-control' , 'autocomplete': 'off','pattern':'[A-Za-z ]+', 'title':'Enter Characters Only '})) guarantor_sex = forms.ChoiceField(required=True,choices=SEX) if Patient_Relationship = Self copy data from PDEM form fields to GUARANTOR form fields -
Django Signal not adding user to a group
I am trying to add a user to a group when the user is created. I have seen a few different ways to accomplish similar things with signals but nothing I am trying has seemed to work. In the shell, I ran Group.objects.get(name='User') to make sure that the group was being recognized. signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User, Group from django.dispatch import receiver @receiver(post_save, sender=User) def add_user_to_user_group(sender, instance, created, **kwargs): try: if created: instance.groups.add(Group.objects.get(name='User')) except Group.DoesNotExist: pass This part I am very unsure of, I have seen a few different ways people have done this part. One tutorial did it this way but I am not sure what just importing the signals would do app.py from django.apps import AppConfig class UserConfig(AppConfig): name = 'User' def ready(self): import User.signals -
SESSION_EXPIRE_AT_BROWSER_CLOSE does not work
I am trying to set up the parameter above to make the user stay log in, somehow it only works on my local development environment (Mac os), after I deploy it to the server, it does not work at all, my server runs with the latest version of ubuntu, anyone have ideas? Django version: 1.7.5 Python version: 2.7 Ubuntu version: 18.04 -
Showing thumbnails for docx pdf for uploaded files using JQuery and Django
I am using dropzone.js to upload files to Django backend and it displays the default thumbnail for files except images. How can I add a snapshot of a file, doc/pdf/ppt/excel types? Is there any package out there? Googled it but not showing that much. Thanks in advance. -
Django - model that has a count per CHOICES Field
django 2.1, python 3.6 Let's say I have a set of things ['house_1','house_2',...] and I want to have a model that keeps a count of each item. I'd imagine that it'd look like the following. class Card(models.Model): house_1_count = models.IntegerField(... house_2_count = models.IntegerField(... house_3_count = models.IntegerField(... Is there a way to convert this model so that the items are not hard coded. Like by using a CHOICES field. The items in my list may change (slowly), but I don't want to have to create a field in the model every time it happens. -
Can someone help me about attendance employee with clock in & clock out in Python 3, and django
I'm built a new project with python & django in simple feature could someone help me about create model, view, template just to show how the logic is? Thank you very much if some of you could help me.. i really appreciate -
Issue Django V 1.11.16 Admin Search Not Working with all Data
I developed an application form in Django I added 500 +- records using the Django admin, then I imported 9000 records using MySql. In the Django admin I can see all records perfectly. However, when I search for xxx record does not find it but I can see the record on the admin right there. It is weird because when I search the records I added using the Django admin the search works and display them correctly. If I want to search for a record or records that was imported using MySql import (9000 records) does not find them. If I filter them, yes I see the records, if I type the same search for the filter does not show them. I really appreciate your help. Thanks a MILLON. This is for a Linux server running on AWS, running MySQL, Python, Django 1.11.16 I changed the filters, add filters, checked the search_fields, restart the server. from django.contrib import admin from .models import ApplicationForm, Supervisor from .forms import AdminForm from advanced_filters.admin import AdminAdvancedFiltersMixin from apps.users import views # Register your models here. class ReadOnly(AdminAdvancedFiltersMixin, admin.ModelAdmin): readonly_fields = [] advanced_filter_fields = ('first_name', 'last_name', 'email', 'phoneNumber', 'city', 'state', 'socialSecurityNumber', 'other city', 'project', 'agreement_signed_date', … -
Django Formset image.url Not Populated
I have an image field on a model that i'd like to render inside an img tag. It's inside of a formset and I can see the link to the image, but if I try to reference form.image.url nothing comes back. form.image returns "Current :" "" which breaks because of the leading string. How can get the images to display? Stack Django 2.1, django-storages using S3 Storages Settings MEDIA_ROOT = os.path.join(BASE_DIR, 'media') DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_DEFAULT_ACL = 'None' AWS_S3_REGION_NAME = "us-east-1" AWS_LOCATION = "images" AWS_STORAGE_BUCKET_NAME = 'fakebucketname' MEDIA_URL = 'http://%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME AWS_S3_HOST = 's3.us-east-1.amazonaws.com' AWS_DEFAULT_ACL = None Models class Note(models.Model): user = models.CharField(null=True, max_length=25) image = models.ImageField(upload_to="%Y/%m/%d/") text = models.TextField(verbose_name='Text', null=True) pub_date = models.DateTimeField(auto_now_add=True) report = models.ForeignKey(Report, on_delete=models.CASCADE, null=True) def __str__(self): return self.user class Report(models.Model): name = models.DateField(auto_now_add=True, unique=True, verbose_name='Report Name') slug = models.SlugField(blank=True) def __str__(self): return str(self.name) def __unicode__(self): return u"%s" % self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) return super(Report, self).save(*args, **kwargs) def get_absolute_url(self): from django.urls import reverse return reverse('report_detail', args=[str(self.id)]) Forms from TheDaily.models import Report, Note from django.forms import ModelForm, inlineformset_factory class NoteForm(ModelForm): def __init__(self, *args, **kwargs): super(NoteForm, self).__init__(*args, **kwargs) self.fields['image'].required = False class Meta: model = Note exclude = () class ReportForm(ModelForm): class Meta: … -
How to make django accessible on on intranet
I have a django project on a linux server with the hostname sgzls1 which i have been developing in debug mode. Now I want to make the django project available from other users win machines in the intranet, so I set DEBUG = False ALLOWED_HOSTS = ['*'] However, I can't reach the project. While this here lets me connect http://localhost:8000/gui/?sort=id even trying this from sgzls1 http://sgzls1:8000/gui/?sort=id shows 'unable to connect'. What do I need to do to make that project available from within the intranet? -
Djangorestframework - All api paths under a common url base
django 2.1, python 3.6, djangorestframework Is it possible to create one api path that includes multiple models? urlpatterns = [ ... path('api/', include('cards.api.urls')), path('api2/', include('decks.api.urls')), ] urlpatterns = [ ... path('api/', include('cards.api.urls', 'decks.api.urls')), ] I am getting the following error messaage Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. I want to be able to have all of my api calls under one url -
Django 1.9 how to query model using prefetch_related() and get the results which prefetched data existing
I'm making a query to retrieve a model using prefetch_related. products = products.prefetch_related('payments').all() However, I got all the products but some of them have no payments. Is there a way to retrieve products which have payments? -
Django - set OSMWidget.js as static file
I had a similar problem as the one asked in this question ,I managed to make it work and display the map widget, but the map that is displayed is set to an area in Europe, I need to set the mapcenter to my area of work, and as it is mentioned at the bottom in the link a workaround is to set the customized OLMapWidget.js I've been looking for info about how to set this file as static and how to bind it with the specific html template, but i cant make it work: settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'a_imac/static') ] STATIC_URL = '/static/' forms.py class Pav_ima_form(forms.ModelForm): class Meta(): model = Pavim_ima fields = '__all__' widgets = { 'observaciones': Textarea(attrs={'cols': 80, 'rows': 5}), 'geom_linea': forms.OSMWidget(attrs={'map_width': 800, 'map_height': 500}), } class Media: js = ('OLMapWidget.js') def limpiar(self): cd = self.cleaned_data template {% extends 'base-seco.html' %} {% load crispy_forms_tags %} {% load bootstrap %} {% load leaflet_tags %} {% load staticfiles %} {% block content %} {% leaflet_js plugins="forms" %} {% leaflet_css plugins="forms" %} <head> {{ form.media }} <script src="{% static 'OLMapWidget.js' %}"></script> </head> <div class="col-md-10"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class='form-group '> {{ form|bootstrap }} </fieldset> <input type="submit" … -
Display comment content on delete page
I'm not able to display content of comment in Django template. do i have to pass something to the view or do i just call the object simply the wrong way. views.py def comment_delete(request, pk): comment = get_object_or_404(Comment, pk=pk) try: if request.method == 'POST': comment.delete() messages.success(request, 'You have successfully deleted the Comment') return redirect('post_detail', pk=comment.post.pk) else: template = 'eCHO/comment_delete.html' form = CommentForm(instance=comment) context = { 'form': form, } return render(request, template, context) except Exception as e: messages.warning(request, 'The comment could not be deleted. Error {}'.format(e)) models.py class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField() published_date = models.DateField(auto_now_add=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.content template.html <div class="class-one-box"> <p>{{ comment.post.content }}</p> <p>Are you sure that you want to delete this Comment? If so, please confirm.</p> <form method="POST"> {% csrf_token %} <button class="btn btn-danger" type="submit">Delete Comment</button> </form> </div> -
How can I make a choice field with steps in Django admin
I'm trying to make something like the image below. Let's say that I have 3 multiple choice fields like the following. If I choose bags from choices_first, I want choices_for_bags to show up as the next choice step. The below image is one of the fields for Django default user model. It's for another purpose. I'm looking for something like that. As I choose something on the left, I want something to show up on the right based on the choice on the left. Does Django admin provide anything like that as default or is there any library for that? choices_first = ( ('clothing', 'Clothing'), ('bags', 'Bags'), ) choices_for_clothing = ( ('tops', 'Tops'), ('bottoms', 'Bottoms'), ) choices_for_bags = ( ('handbags', 'Handbags'), ('backpacks', 'Backpacks'), ) -
Wagtail, CORS and Django-Cors-Headers. How to enable CORS so that AXIOS can get to the endpoints
I'm trying to enable the Wagtail API so I can do some exciting stuff in Vue. However, I've followed all the instructions for enabling the API in Wagtail and there is no mention of CORS. Well, it's less than a paragraph. I use Django-Cors-Headers on all my projects and set it up as I normally would, but for some reason, the API still won't allow access. Does anyone have any suggestions on how to allow a CORS connection to the Wagtail API endpoints using DJANGO-CORS-HEADERS? -
Django - manytomany card/deck model with selecting the same option multiple times possible?
Django 2.1, djangorestframework, Python3.6 Suppose you have a Deck model and a Card model. For simplicity's sake there are possible cards. A deck is made of 6 cards that are in any combination. Thus there are 6 choose 4 (15) combinations. What is the best way to make these models. The number of cards and cards in a deck is going to be much more (300+ and 36). This is what I was thinking. Use a ManytoMany field like so- class Card(models.Model): id = models.CharField(max_length=36, blank=False, primary_key=True) card_title = models.CharField(max_length=100, blank=False) and class Deck(models.Model): id = models.CharField(max_length=50, primary_key=True) name = models.CharField(max_length=100) card = models.ManyToManyField(Card) However, this only let's me select each card once per house. I'd want to be able to select as many multiples of a card as possible. I imagine there is a parameter that will let me select multiple, but I don't know what it is. Is this the right way to build this relationship or is there a better way?