Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Html Uploaded File to Python and Return Data Analysis Result Back to HTML
My question is that I want to allow my users to upload a tiff file, then I pass this file to views.py and do some data analysis and return an int and display the result in html when a button in html is clicked. How can I achieve this in django? Thanks! -
Problem with request.user.is_authenticated
I am writing a simple django view that takes username and password and authenticates it using authenticate(). However after successful authentication request.user.is_authenticated is still False. Here is the code: def login(request): if request.method == 'POST': form = loginform(request.POST) if form.is_valid(): username = request.POST['USERNAME'] password = request.POST['PASSWORD'] user = authenticate(username=username, password=password) if user is not None : return HttpResponse(request.user.is_authenticated) else : return HttpResponse('Login Failed') else: form = loginform() return(render(request,'signup/login.html')) PS : In my version of django `request.user.is_authenticated` is a attribute not function -
Displaying all of the fields of ManytoMany objects in Django Model Form
I am doing a simple invoice app and i encountered a problem with my django model form. Form is showing all of the ManytoManyfields objects but i would like to display all of their fields not just an objectname. My models.py: from django.db import models import datetime from django.urls import reverse # Create your models here. class Product(models.Model): item_name = models.CharField(max_length=100) chinese_name = models.CharField(max_length=100) erp_number = models.CharField(max_length=20) unit = models.CharField(max_length=8) photo = models.ImageField(blank=True, null=True) price_usd = models.DecimalField(max_digits=8, decimal_places=2) price_eur = models.DecimalField(max_digits=8, decimal_places=2) def __str__(self): return self.item_name class Batch(models.Model): batch_name = models.CharField(max_length=100) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.DecimalField(max_digits=5, decimal_places=0) def __str__(self): return self.batch_name class Invoice(models.Model): invoice_no = models.CharField(max_length=30, default="Proforma Invoice 2018102300001") products = models.ManyToManyField(Product) total = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) date = models.DateField(auto_now_add=False,auto_now=False, default=datetime.datetime.now()) def __str__(self): return self.invoice_no def get_absolute_url(self): return reverse('invoice_detail',kwargs = {'pk':self.pk}) My forms.py: from django import forms from django.forms import modelformset_factory, inlineformset_factory from .models import Invoice, Product from django.forms.widgets import CheckboxSelectMultiple class InvoiceForm(forms.ModelForm): invoice_no =forms.CharField(widget=forms.TextInput(attrs={'size':40}),initial='Proforma Invoice 2018102300001') date = forms.DateField(widget = forms.SelectDateWidget) class Meta: model = Invoice fields = '__all__' def __init__(self, *args, **kwargs): super(InvoiceForm, self).__init__(*args, **kwargs) self.fields["products"].widget = CheckboxSelectMultiple() self.fields["products"].queryset = Product.objects.all() My template: {% extends 'base.html' %} {% block content %} <!DOCTYPE html> <html lang="en"> … -
unhandled exception with django and fastcgi
We have a Django application running on FastCGI on a Apache server hosted by Bluehost. It has been running smoothly for a long time. Suddenly every page is issuing this message: Unhandled Exception An unhandled exception was thrown by the application. Firefox Web Console says this: The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol. No changes were made by us, but it is likely that either a configuration change was made by Bluehost, or possibly a software change. Their tech support is unhelpful and slow. I realize this is a long shot, but if anyone has any idea what might cause such an error on a Django server, I would be grateful. -
How to async iterate over a queue of websocket clients in Django Channels using redis?
Consider the following scenario: 01) PHP Server with PostgreSQL a.k.a PHP 02) Python with Django Channels 2 with Redis a.k.a. PYTHON 03) Mobile Websocket clients a.k.a Client PYTHON has several stored (in memory) connect clients through websockets. PHP opens a websocket connection with PYTHON asking: give me a list of the closest clients. PYTHON store (in memory) this connection with PHP PYTHON organize these clients in a queue and store in REDIS. After the ready queue, PYTHON offer this job (data from PHP) to the first client of the queue. If client answer yes, PYTHON receives answer then notify PHP and the process is done. If client answer 'no', PYTHON will get the next client in queue. Here is my problem: if the client does not answer? or disconnect? I need a timeout and find a way to go to the next item on queue. This is the question? How to pop queue with the unavailable client and offer the job to the next item? I set an external Python to listen to __keyspace@0__ and __keyevents@0__ (expire) with a while True: code ... but it's quite confusing. I also thought with channel_layer and groups... but the control of the loop … -
sending email via rabbitmq async results cannot connect to smtp 10051
I have an email sending function that works from django shell but there are times I call it with delay() to be sent async. When done async with rabbitmq, I get the following error: I am sending normal message and the function that sends the message does work from shell as well as without delay() method so I doubt it is the mail server or the code but who knows. Anyone? -
Django rest with raw
sorry I have a problem with raw, I'm trying to add up the total sales for each month, but I have an error. this is my sight. class TotalSale(ListAPIView): serializer_class = TotalSaleSerealizer def get_queryset(self): queryset = Sale.objects.raw("SELECT 1 id, SUM(totalprice), to_char(datesale,'yyyy-MM') FROM sales_sale group by to_char(datesale,'yyyy-MM')") return queryset the to_char I am using to change the format of my date and so I can calculate the sales of each month, this query works well when I do it directly in Postgresql, but when I do it in django I do not vote for the correct data. 1,'1197','2018-10' 1,'612','2018-09' 1,'1956','2018-08' and it's fine I calculate the sum of the sales of each month But when I do that in Django, this comes to me. { "id": 1, "totalprice": 144, "datesale": "2018-08-06" }, { "id": 1, "totalprice": 144, "datesale": "2018-08-06" }, { "id": 1, "totalprice": 144, "datesale": "2018-08-06" } I think the error is for the 1 id, just filter the data of the data that has id 1, my question is why that happens, how can I solve it try to remove the 1 id but another error comes out, how can I fix that problem. -
Django two forms interconnected in single template
I have another model which is like below class Status(models.Model): name = models.ForeignKey(User, on_delete=models.CASCADE) status = models.BooleanField(default=False) I just want to create a form which will render all users from django User model with upper model connected. When click single Status button it will just save that field. I'm using CreateView. How to do that? <form method="post" action=""> User1 <input type="checkbox" name="status" /> <input type="submit" name="submit" value="Status"/> </form> <form method="post" action=""> User2 <input type="checkbox" name="status" /> <input type="submit" name="submit" value="Status"/> </form> <form method="post" action=""> User3 <input type="checkbox" name="status" /> <input type="submit" name="submit" value="Status"/> </form> -
django send post data to url
I am creating a web service in Django that when called will call a stored procedure that will render data, that will then be changed to json and now I have to send it to a url with a userid and password. Do I have to import another library or will something like HttpResponse work? -
Solving problems in django when no debug message is displayed
I'm using this https://rock-it.pl/multiple-forms-on-one-page-in-django/ to try and include multiple forms in a single Django view. Here's my views.py class survey_detail(MultipleFormsView, DetailView): model = Survey template_name = 'blog/post/survey_detail.html' # here we specify all forms that should be displayed forms_classes = [ Survcomm ] def get_success_url(self): return reverse('blog:survey_detail', kwargs={'slug': self.object.slug}) def get_context_data(self, **kwargs): context = super(survey_detail, self).get_context_data(**kwargs) context['post'] = self.object return context def get_forms_classes(self): # we hide staff_only forms from not-staff users # our goal no. 3 about dynamic amount list of forms self.object = self.get_object() forms_classes = super(survey_detail, self).get_forms_classes() user = self.request.user if not user.is_authenticated or not user.is_staff: return list(filter(lambda form: not getattr(form, 'staff_only', False), forms_classes)) return forms_classes def form_valid(self, form): form.save() return super(survey_detail, self).form_valid(form) All is fine when working with the code above. However, I also need to prepopulate certain fields in one of my forms. For that, i add the following code below my already declared functions: def get_form_kwargs(self, **kwargs): """ Returns the keyword arguments for instantiating the form. """ kwargs = super(survey_detail, self).get_form_kwargs() kwargs.update( {'initial': {'author_s': self.request.user.userprofile, 'post_s':self.object} } ) return kwargs Sadly, after overriding the get_form_kwargs definition, my form no longer works. To make matters worse, no error is displayed by django - as it should be … -
Filtering an object with GenericForeignKey ContentType model
trying to filter and object with a GenericForeignKey get this error E django.core.exceptions.FieldError: Field 'pos' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. inside the get_categories function im trying to filter POSRecord by the property pos, and assigning that to self.credentials. here is where i get the error. class SquareGateway(): def __init__(self, tenant): super().__init__(tenant) self.credentials = SquareCredential.objects.get(tenant=self.tenant) def get_categories(): category_records = POSRecord.objects.filter( pos=self.credentials, object_content_type=ContentType.objects.get_for_model(Category) ) this is the model with GenericForeignKey. class POSRecord(models.Model): name = models.CharField(max_length=200) pos_content_type = models.ForeignKey('contenttypes.ContentType', related_name='pos_record_integration', on_delete=models.CASCADE) pos_id = models.CharField(max_length=100) pos = GenericForeignKey('pos_content_type', 'pos_id') object_content_type = models.ForeignKey('contenttypes.ContentType', related_name='pos_record_object', on_delete=models.CASCADE) object_id = models.CharField(max_length=100) object = GenericForeignKey('object_content_type', 'object_id') class SquareCredential(models.Model): tenant = models.ForeignKey('tenant.Tenant', unique=True, on_delete=models.CASCADE) token = models.CharField(max_length=255) -
How to make the search feature catch all types of keyword format in Django views
I'm trying to improve the search feature in my website. I use filter() multiple times to check if the search text matches with multiple columns. Everything is good so far, but the problem is when I want to search a store named "Under Armour", if I type underarmour, it isn't filtered with anything. I can't come up with any idea about how to let the system consider underarmour "under armour". Does Django support anything like this feature in default or should I do something else? class SearchListView(ListView): def get_queryset(self): search_text = self.request.GET.get('search_text') if search_text: search_stores = Store.objects.filter(Q(businessName__icontains=search_text) | Q( relatedName__icontains=search_text) | Q(mKey__icontains=search_text) | Q(website__icontains=search_text)) return search_stores.filter(status='active') -
Why Django stops execution if reverse relation does not exist?
I have a common situation: a User model and an Employee model which is related to User by one-to-one relation on user_id. My user model is customized and one of customizations is the method "is_employee": class User(AbstractUser): def is_employee(self): print(self.id) print(self.employee is not None) return self.employee is not None is_employee.boolean = True is_employee.short_description = _('Employee status') class Employee(AddressMixin, models.Model): user = OneToOneField(User, primary_key=True, related_name='employee', on_delete=CASCADE) phone_no = models.CharField(max_length=20, blank=True, default='') mobile_no = models.CharField(max_length=20, blank=True, default='') I use User.is_employee in the admin site on list_display. The problem is that the function User.is_employee only returns a result if there is an Employee for that user. If there is not then it stops executing where it first meets the call self.employee ant thereby returns None. And here is what I see on the admin: Employee status for the last user last user is not False but None Sorry if the question was messy. I am quite new to Django and this is my first post on this site as well. Thank you in advance. -
I don't understand the JWT integration in this repository/article
I've been changing this project: https://github.com/viewflow/cookbook/tree/master/_articles/redux_jwt_auth To get a better understanding of react/redux and how it could be implemented into a backend framework like Django but I'm stumped on one part. I'm trying to implement a logout feature but I don't understand how the logout should look like based off of the author's other variables in his actions/auth.js. I know I have to destroy the JWTToken but I don't quite understand how he is implementing the token into the project. I've read his article about it many times and I still don't really understand it. -
Running Pydoc with Django
I'm trying to ruin pydoc in a django module however I keep getting an error message and I'm not too sure on how to fix it. Error Message: problem in models - ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I am using windows 10; if it is relevant. Thanks for the help. -
using a queryset to generate options for select widget on IntegerField in Django
I'm trying to make a site where users can have multiple avatars and pick the one they want to use when entering a room. (It will be a dice-rolling app.) I've been stuck for three days trying to figure out how to pass a queryset into a form to use as the options for a select widget that's on an IntegerField. Right now, I think I have successfully passed the information into the form, but nothing is rendering in the widget. (I've even got a print statement in the form to prove to myself that the information has made its way in.) model.py class EnterSWroom(models.Model): room_number = models.IntegerField(blank=False) passcode = models.CharField(max_length=100, blank=True, null=True) default_avatar = models.IntegerField(default=0) forms.py class Enter_SW_Room(forms.ModelForm): class Meta: model = EnterSWroom widgets = {'default_avatar': forms.Select(choices=[])} fields = ('room_number', 'passcode', 'default_avatar') def __init__(self, *args, **kwargs): imported_list = kwargs.pop('avatar_list') super().__init__(*args, **kwargs) self.fields['default_avatar'].choices = imported_list print(self.fields['default_avatar'].choices) #this is just for debugging; see example below views.py class DockingBay(FormMixin, TemplateView): form_class = Enter_SW_Room def get_form_kwargs(self): kwargs = super().get_form_kwargs() # get tuples for avatar choices # get user first name (if exists), else use username if self.request.user.userprofile.user_first_name: user_name = self.request.user.userprofile.user_first_name else: user_name = self.request.user.username # instantiate avatars list, start with user name my_avatars … -
Guarantee .count() atomicity in Django queryset
I'm working on a REST API developed with Django. One of the views of the API adds a new instane of a model to the database only if there are less than a specific amount of them already stored in the database. I'm worried about the possibility of two simulatenous calls to the API, in such a way that both of them evalueate at the same time the amount check: if modelX.objects.filter(...).count() < n: ... given the situation that is only possible to add one of them. I've thought about wrapping the whole code with a with transaction.atomic() statement, but as long as I'm not selecting any specific object, I don't know if sucha thing would work. -
Changing templates dynamically with xhtml2pdf and django
I want to switch between two named templates acording which kind of page the rendering is in (odd or even). In another words, is it possible to loop through my context variable and change my template so I can print the paper and make a book out of it?. Is there a way to detect a page break and change the template? Here are my templates @page { size: a4 portrait; @frame header_frame { /* Static Frame */ -pdf-frame-content: header_content; left: 80pt; width: 500pt; top: 20pt; height: 100pt; } @frame content_frame { /* Content Frame */ left: 80pt; right: 20pt; width: 500pt; top: 110pt; height: 600pt; /*top: 90pt*/ } @frame footer_frame { /* Another static Frame */ -pdf-frame-content:footer_content; left: 80pt; width: 500pt; top: 720pt; height: 50pt; } } @page even{ size: a4 portrait; @frame header_frame { /* Static Frame */ -pdf-frame-content: header_content; right: 80pt; width: 500pt; top: 20pt; height: 100pt; } @frame content_frame { /* Content Frame */ left: 20pt; right: 80pt; width: 500pt; top: 110pt; height: 600pt; /*top: 90pt*/ } @frame footer_frame { /* Another static Frame */ -pdf-frame-content:footer_content; right: 80pt; width: 500pt; top: 720pt; height: 50pt; } } And my table {% for item in data %} <tr> … -
Celery-Progress-Bar Not Working in Django
I am trying to use celery-progress module to show the user the progress of the task, since it takes lot of time to complete the task. However, after following the instructions on https://github.com/czue/celery-progress,I am seeing the following error on the front-end:- NoReverseMatch at /netadc/arista/views/getFabListArista/TRCW/ Reverse for 'task_status' with arguments '('',)' not found. 1 pattern(s) tried: [u'celery_progress/(?P<task_id>[\\w-]+)/$'] Request Method: GET Request URL: http://x.x.x.x/netadc/arista/views/getFabListArista/TRCW/ Django Version: 1.11 Exception Type: NoReverseMatch Exception Value: Reverse for 'task_status' with arguments '('',)' not found. 1 pattern(s) tried: [u'celery_progress/(?P<task_id>[\\w-]+)/$'] The URL pattern on the front-end var progressUrl = "{% url 'celery_progress:task_status' task_id %}"; does not work. When I change it to var progressUrl = "{% url 'celery_progress:task_status' 'task_id' %}"; i do not get the error, but no tasks are running. Any experts on django/python, please help. -
How to set auto generated meta fields for history table in Django
Sample model : class Sample(models.Model): company = models.CharField(max_length=100,null=True,blank=True) history = HistoricalRecords() In above model,I have used the Historical records so basically it create history table and maintains history of each row for sample model. In history table,How to set history_user_id ? EDIT : In history table some meta fields(history_change_reason,history_user_id) are auto generated.How to set value for these meta fields ? -
Integrate SQLAlchemy based project with Django-rest
I have a existing SQLAlchemy based project with the following structure # __init__.py import yaml from sqlalchemy.orm import sessionmaker from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base try: with open('config.yaml', 'r') as yaml_config_file: config = yaml.safe_load(yaml_config_file) except: raise Exception Base = declarative_base() Session = sessionmaker(bind=create_engine(config['db'])) # models.py: from fmgcore import Base class Image(Base): __tablename_- = 'image' .... ... # service.py from fmgcore import config, Session import sqlalchemy.exc as sql_exc log = logging.getLogger(__name__) class Services(object): def __init__(self, config): self.config = config def create_image(self, name, filename, disk_format, size=None, description=None): session = Session() try: session.add(...) session.commit(...) except sql_exc.IntegrityError as e: logging.info("Image with name {0} already exists".format(name)) session.rollback() except sql_exc.SQLAlchemyError as e: session.rollback() finally: session.close() def get_image(): #### I want to expose these services using REST Api's using Django-Rest. I don't want to use Django models. My question is how should I use Services() in my view.py, so that it will not create multiple instances of engine or new connection for every REST request, instead use the same pool. -
django: field error passing name through url
FieldError: Cannot resolve 'name' into field. Choices are: heading, id, bookname. want to pass book.heading as name through url. no error when pass id but only want to pass heading not id as requirement. how to do it? -
Django sql_server.pyodbc passing incorrect code to MS SQL Server for case when and group by
I am a DBA in the process of migrating a Django application database from Postgres to MS SQL Server. (This is something I must do.) This application is using sql_server.pyodbc and Microsoft SQL Server ODBC driver for Linux/Ubuntu. Everything works except for queries that have a CASE WHEN and GROUP BY added to them. From running traces I see that the sql is actually passed to SQL Server via the sp_prepexec procedure with MANY parameters. The parameters are variables and are different in the select vs group by, causing the error on SQL Server side. (This is just an example, actual query is more complex): select case when col1=@p1 then @p2 end as new_col1, sum(col2) from table group by case when col1=@p3 then @p4 end In reality @p1 and @p3 are the same values. So are @p2 and @p4. But SQL Server doesn't know that. This also fails if I run the same query on postgres - so I assume this has to do with sql_server.pyodbc package. Has anyone come across this? What are my options? Am I doing something wrong with the configuration? -
i need to specify some id in django to later add it in bootstrap
i want to make a portfolio in django, i have a section in html that with {% for ... %} i connect it to my jobs list in dajngo to show my job's pictures,summary and title but in html code there is an id in this div that call another div in the code and when i perform a for loop this id is just repeat it self,how could i change this id in order to changed automatically?` {% for job in jobdic.all %} <div class="col-md-6 col-lg-4"> <a class="portfolio-item d-block mx-auto" **href="#portfolio-modal-1"**> <div class="portfolio-item-caption d-flex position-absolute h-100 w-100"> <div class="portfolio-item-caption-content my-auto w-100 text-center text-white"> <i class="fas fa-search-plus fa-3x"></i> </div> </div> <p>{{ job.summary }}</p> <img class="img-fluid" src="{{ job.image.url }}" alt="{{job.title }}"> </a> </div> {% endfor %} the problem area is in href that call another section in html with portfolio-modal-1 i need to write some code that can be change this portfolio-modal-1 to portfolio-modal-2 and 3 and ... automatically this is the section that its refers to : {% for job in jobdic.all %} <div class="portfolio-modal mfp-hide" id="portfolio-modal-1"> <div class="portfolio-modal-dialog bg-white"> <a class="close-button d-none d-md-block portfolio-modal-dismiss" href="#"> <i class="fa fa-3x fa-times"></i> </a> <div class="container text-center"> <div class="row"> <div class="col-lg-8 mx-auto"> <h2 … -
how can i serve images urls in html template usign django
in my django app i can serve images using path like this src="/media/user/image.png"using {{ apps.upload.url }} but now i want to serve images to html page using urls links likes this http://127.0.0.1:8000/media/image.png settings.py STATIC_URL = '/static/' STATICFILES_DIRS=( os.path.join(BASE_DIR, 'static','static_dirs'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'static','static_root') MEDIA_ROOT = os.path.join(BASE_DIR, 'static','media') MEDIA_URL = ('/media/') models.py class MyModel(models.Model): name = models.TextField() upload = models.ImageField(upload_to=user_directory_path) urls.py urlpatterns = [ .............. ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) in html page : <img src="/media/user_45/safef_wgis84_wetseis_iFodFR9.png" >