Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is WSGR library? How it is useful for importing the Shapefiles in GeoDjango?
My Shape files has california_zone2 EPSG=2226 projection Coordinates. I need to Import my Shape files as WSGR. I am new to GeoDjango. can anyone suggest me How to use WSGR library to import the Data? -
Displaying the total price of the Items of my Offer in a template
I've got two Models: Offer and Items. My Offer always has an variable amount of Items, which have a price. Now I'd like to display the total sum of the price of the items for each Offer. How can I do that? This is my Item Model: class Item(models.Model): number = models.CharField('Nr.', blank=False, default="", max_length=10) description = models.TextField(default="", blank=False, verbose_name='Beschreibung') costs = models.DecimalField('Price', blank=False, default=0, decimal_places=2, max_digits=10) offer = models.ForeignKey('Offer', null=True, verbose_name="Angebot", related_name="items", on_delete=models.CASCADE) Where do I have to put my code to get the total sum of the items? Inside the views file or my model? And how can I then display this total price in my template? -
Django, How to get template tag rendered data on views.py?
models.py: class TestPhoto(models.Model): file = models.ImageField() views.py: def print_test(request): if request.method == "POST": if request.is_ajax(): testphoto = TestPhoto.objects.all().last() # Here is what I'm asking print({{ testphoto.file.url }}) return JsonResponse({'success': 'printed'}) How can I get template tag rendered data: {{ testphoto.file.url }} on views.py ?? I want to get template tag rendered data in views.py. -
how to delete multiple delete in django
Doubt: Here i have mentioned Html and output Image . if i click select all option (checkbox) it will select all image but my doubt was how to delete all images once i click delete button Html {% for j in img %} <h4>Select All <input type="checkbox" onclick="$('input[name*=\'selected\']').prop('checked', this.checked);" /></h4> <button class="btn btn-danger" action=" ">Delete</button> <div class="col"> {% if i.placename == j.gallery_place %} <div class="show-image"> <img src="{{j.gallery_image.url}}" style="height:130px; width:130px;" /> <tag class="one" style="margin:8%"> <input type="checkbox" name="selected[]" value="{{j.id}}" /> </tag> </div> {% endif %} </div> {% endfor %} image enter image description here -
django URL Reverse : argument to reversed() must be a sequence
This is my urls.py conf from django.conf.urls import include, url from django.contrib import admin from home import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.index), url(r'^home/', include('home.urls')), url(r'^setting/', include('setting.urls')), url(r'^customer/', include('customers.urls')), url(r'^material/', include('materials.urls')), url(r'^order/', include('orders.urls')), url(r'^partner/', include('partner.urls')), ] and my customers.urls conf from django.conf.urls import url from customers import views app_name = 'customers' urlpatterns = [ url(r'^list', views.customerList, name='customerList'), url(r'^create', views.createCustomer, name='createCustomer'), url(r'^remmove', views.lockCustomer, name='removeCustomer'), url(r'^update', views.updateCustomer, name='updateCustomer'), url(r'^detail/(?P<id>\S+)/$', views.customerDetail, name='customerDetail'), url(r'^member/(?P<customer_id>\S+)/$', views.customerMember, name='customerMember'), ] and my template.html to use url reverse {% for company in customers %} <tr> <td> <a href="{% url 'customers:customerMember' company.id %}"> <span style="color:#08c; font-weight: bold;">{{ company.name }}</span> </a> </td> <td> {{ company.region_id }} </td> <td> {{ company.register_time }} </td> <td> {% if current_time > company.due_time %} <span class="text-center text-danger">Expired</span> {% else %} <span class="text-center text-danger">{{ company.due_time }}</span> {% endif %} </td> <td> {{ company.account_limit }} </td> <td> {{ company.isdelete }} </td> </tr> {% endfor %} when i visit http://localhost:8000/customer/list page, It gives me a TypeError: TypeError at /customer/list/ argument to reversed() must be a sequence Request Method: GET Request URL: http://127.0.0.1:8000/customer/list/ Django Version: 1.10.3 Exception Type: TypeError Exception Value: argument to reversed() must be a sequence Exception Location: C:\Python\lib\site-packages\django\urls\resolvers.py in _populate, line 196 Python Executable: … -
Django Haystack + Elasticsearch strange intermittent bug
I'm facing a strange issue with django-haystack with Elasticsearch. Everything works great (indexing, querying…), but sometimes (and I don't manage to identify the root cause), querying the index crashes with this error: File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.5/dist-packages/django/contrib/auth/decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "/home/django/prod/posepartage/forum/api.py" in get_topics 66. topics_list = SearchQuerySet().filter(**filter).models(Topic) File "/usr/local/lib/python3.5/dist-packages/haystack/query.py" in __init__ 29. self._determine_backend() File "/usr/local/lib/python3.5/dist-packages/haystack/query.py" in _determine_backend 55. backend_alias = connection_router.for_read(**hints) File "/usr/local/lib/python3.5/dist-packages/haystack/utils/loading.py" in for_read 167. return self._for_action('for_read', False, **hints)[0] Exception Type: IndexError at /forum/api/get-topics/ Exception Value: list index out of range The issue seems to be with the _determine_backend function. My backend is configured this way in Django settings file: HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch2_backend.Elasticsearch2SearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'myindex', }, } It's the same on my production server (Python 3.5) and my dev (Python 3.6). Haystack version is: django-haystack==2.8.1 - Django [required: >=1.11, installed: 2.0.6] - pytz [required: Any, installed: 2018.4] elasticsearch==2.4.1 - urllib3 [required: <2.0,>=1.8, installed: 1.23] Have you ever experienced such a thing? Thank you in advance! -
if statements around blocks in template inheritence in django
enter image description herei have 2 type of users in my website customers and bankers and i don't want bankers to visit customer's dashboard and vice versa.so i used a library django-role-permissions and have given roles to each user at the time of registration which works fine . but now i wanted to give authorization to each page and specify which user can access which page. so i wants that if a banker logs in and tries to open customer dashboard it should how an error.so i changed the customer_dashboard and applied if user is banker shows error but since i am using template inheritance the error page shows header and footer but i don't want that . i want a clear error message and nothing else so i tried this - my customer_dashboard.html file <!DOCTYPE html> {% extends "base.html" %} {% load permission_tags %} {% if user|has_role:'banker' %} {% block main_block %} <h1>error!!</h1> {% endblock main_block%} {% else %} {% block body_block %} <div class="container"> <div class="jumbotron"> <h1>Hello! Wellcome to Your Personal DashBoard</h1> <h3>now you can check your credit score!</h3> </div> </div> {% endblock body_block %} {% endif %} And my base.Html file <!DOCTYPE html> {% load staticfiles %} … -
How does sqs message deletion flow works in celery-sqs
I was looking for how celery and sqs deletion works? When does celery delete message from sqs? Does it delete when message is picked from sqs or after completion of tasks? What happens if there is some error in task or it raises error? Will the message (task) will be there if the tasks is taking too long like and 20 mins. -
Aggregate over foreign key attributes
I want to know the number of questions that has been asked to a specific user. Here are my models class TrueOrFalseQuestion(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) content = models.TextField(default='', blank=True) explanation = models.TextField(default='', blank=True) class TrueOrFalseUserQuestion(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) creator = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(TrueOrFalseQuestion, related_name='user_questions', on_delete=models.CASCADE) Someone creates a question, then when I want to display it for a specific user, I create a TrueOrFalseUserQuestion (and assign the user as creator). I want to know how many times a question has been displayed to each user. Let's say user with id 1 has 5 TrueOrFalseUserQuestion and user 2 has 3, then I would like to have this result {"1": 5, "2": 3} It's easy to do with Python but I think it will give poor performance, is there a way to do that using Django ORM? -
Error running WSGI application
Hi I'm trying to deploy a blog site using Python anywhere but I have had a problem... The following error occurs when I try to enter a site I created 2018-06-21 07:34:36,467: Error running WSGI application 2018-06-21 07:34:36,470: ModuleNotFoundError: No module named 'djnago' 2018-06-21 07:34:36,470: File "/var/www/choco1992_pythonanywhere_com_wsgi.py", line 10, in <module> 2018-06-21 07:34:36,470: from djnago.core.wsgi import get_wsgi_application -
Django admin - customized model page
Currently I'm working on an admin panel for my application. The database is in MongoDB so I use Djongo connector as my db backend. Right now I managed to succesfully pull all the data from my database and display it in my admin panel. However, I have models in my database which contains array of other models. For example, I have a Team model which contains an array of Colleagues. The Colleague model contains details like firstName, role, email, etc. Now, the way it is displayed is quite confusing. Here is a screenshot of the problem: https://i.gyazo.com/2ea2f73c6b7868fcb9b864e67c4708d4.png As you can see, each colleague item is displayed fully with input fields. I want the fields to be displayed as a list or something like that so the user can easily go through the data without getting confused. Here is the my code for the models: class Colleague(models.Model): _id = models.ObjectIdField() name = models.CharField(max_length=100) job = models.CharField(max_length=150) img = models.CharField(max_length=350) phone = models.CharField(max_length=50) branch = models.IntegerField() mail = models.CharField(max_length=100) class Meta: abstract = True class OurTeam(models.Model): _id = models.ObjectIdField() colleague = models.ArrayModelField( model_container=Colleague ) class Meta: abstract = True class OurTeamCollection(models.Model): _id = models.ObjectIdField() he = models.EmbeddedModelField( model_container=OurTeam ) en = models.EmbeddedModelField( … -
how to create a todo app for multiple users in django
are these models are correct for the above question? does foreign key is one to many relationship? from django.db import models import datetime from datetime import date class Data(models.Model): title=models.CharField(max_length=128) text=models.TextField() data=models.DateTimeField(default=datetime.now,blank=True) def __str__(self): return self.title class Client(models.Model): user=models.ForeignKey(Data,on_delete=models.CASCADE) -
Set custom UI languages in Django
How can I set own custom coded UI languages (Example: English, Myanmar, Chinese) in my django website without using django localization. Is there any method to write each translation data in .py file and load to html page. -
Django keep HTML formatting with passed string
I am very new to Django and I've encountered the following problem. I have a small script to give me a random quote from my list @register.simple_tag(name='quote') def random_quote(): quote, author = random.choice(quotes_list) return """%s <br> %s""" %(quote, author) And I call the selected quote in my template as: {% load quotes %}{% quote %} which is working just fine, however I'm not able to pass the HTML formatting together with my quote. How can I escape HTML in my quote to get e.g. a single line break between quote and author? Thank you! -
custom Django admin static files not loading
I want to make my own admin panel for Django from scratch. So I made a folder named admin in the template folder and put my HTML files there. Then I've added the code below to admin.py in order to go to my HTML page when the user goes to 127.0.0.1:8000/admin/ : # admin.py #-------------------------------------------------------- from django.conf import settings from django.conf.urls.static import static from django.shortcuts import render def my_view(request): return render(request, 'admin/pg_1.html', {}) def get_admin_urls(urls): def get_urls(): urlpatterns = [ url(r'^$', admin.site.admin_view(my_view)) ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) return urlpatterns + urls return get_urls admin_urls = get_admin_urls(admin.site.get_urls()) admin.site.get_urls = admin_urls Then I add my static files in the directory below: myProject/static/static-only/admin/ But when I go to admin link, my HTML page loads but the styles won't load. Here is my settings.py: And 'django.contrib.staticfiles' exists in the INSTALLED_APPS. I've also tried python manage.py collectstatic but it loads the original Admin styles in the myProject/static/static-only/admin/ directory that I don't need them. So why my styles won't load? How can I fix that? Thanks. -
Break up django monolith into microservices
We currently have a big Django web application: all data is centrally managed by the webapp, via models backed by Postgres. We want to offer access to the data in a more decentralized way, and the solution that we are aiming for is to provide small uServies dealing with the different application domains. That is, from this architecture: Django + single DB We want to move to the following architecture: Django (without data) uService 1 + DB1 uService 2 + DB2 ... Thus we will have a smooth transition path: the webapp will keep working as before, but we will now have the option of offering access to the data in a fine-grained manner, with different requirements (for scalability, ...) for each of our application domains. The refactoring must be done in the following way: The Django webapp must remain unchaged (except for the models). In particular, views and templates must remain unchanged. Each uService will deal with a problem subdomain, and will be completely autonomous, offering access to the data via REST. The technology for each uService is not defined: it could be DRF, or Flask, or Scala, or Java, it does not really matter; this is actually one … -
Django Admin: "Save as New" with GenericForeignKey
We have a model A that can be edited in Django Admin. Model B is linked to A via a GenericForeignKey and the linked B instances are displayed together with A in an inline formset. Now when "save as new" is enabled and used, the copy of the A instance does not have any linked B instances, which is what I would have expected. With regular foreign keys at least it works like this. Is it bug in Django or expected behavior? Is there a way achieve the desired result? -
How to fetch custom column which does not exist in database table?
How can I implement followig SQL QUERY in django rest framework `SELECT `id` , `name_hi` as hi , `name_en` as en , false as `checked` FROM `tab_name` where checked does not exist in the database. id | hi | en | checked 1 | xx | xx | 0 2 | hi2| en2| 0 3 | hi3| en3| 0 I am using Django Rest framework. How can I rename these fields also include checked So far I have tried in serializer class TabFaultOptionSerializer(serializers.ModelSerializer): hi = serializers.CharField(source='name_en') en = serializers.CharField(source='name_en') class Meta: model = TabFaultOption fields =('id','name_en','name_hi') -
Implementing Attribute Level Access Control in Django
In my django application, I have a model, Client, which holds information about the clients of my business. I have two groups of employees that uses my application - Technician and Finance. Members of Technician can view/update attributes such as 'password_hash', 'login_ip_address'. Members of Finance can view/update attributes such as 'total_revenue' or 'bank_account_number'. My goal is to implement access control on the attributes of my Client model based on the group that current user belongs to. Requirements: I use mostly Class-Based Views in my application. For Client's UpdateView (which uses a ModelForm), I want to control which fields the current user can update based on their group. For Client's DetailView, I want to control which fields are displayed in the template easily. Ideally, I want to maintain only one details view template which renders the correct fields based on the current user's group. Questions: Is there an existing plugin that can achieve what I want? (If the answer to the above question is no) How should I go about implementing this myself? -
Cannot start django app
I am a newbie at Django and everytime I try to run (myvenv) C:\Users\lenovo> python manage.py startapp blogit gives me the error: CommandError: 'blog' conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name. Am I doing something wrong? -
How to delete multiple image in Django using check box
How to Delete multiple Image by using checkbox. here i have mentioned Html, screen (output). 1) In this code i have kept Checkbox once i click select all, it select all the images but i dono how to pass id to delete all images. HTML <div class="panel panel-default"> <div class="pull-right"></div> <div class="Heading panel-heading"> <h3 class="panel-title">Gallery Images List</h3> </div> <h4>Select All <input type="checkbox" onclick="$('input[name*=\'selected\']').prop('checked', this.checked);" /></h4> <button class="btn btn-danger">Delete</button> <div class="panel-body" style="padding-left: 50px; padding-right: 50px; padding-top:10px;"> <div class="table-responsive"> {% for i in details %} <b style="font-size:16px;">{{i.placename}}</b> <div class="row"> {% for j in img %} <div class="col"> {% if i.placename == j.gallery_place %} <div class="show-image"> <img src="{{j.gallery_image.url}}" style="height:130px; width:130px;" /> <a href="/GalleryImagesDelete/{{j.id}}"> <span class="delete glyphicon glyphicon-remove"></span> </a> <br/> <tag class="one" style="margin:8%"> <input type="checkbox" name="selected[]" value="33" /> </tag> </div> {% endif %} </div> {% endfor %} </div> {% endfor %} </div> </div> </div> Image Screen -
UpdateView FileField not deleting previous files Django python
I have: class UserUpdateView(UpdateView): fields = ("file_one", "file_two") model = User And it works... but not always, I put in another file, and the paths change, but when I go a process the file in another def, it keeps the previous file values, I came to know because I checked my media folder to see if it was there and It was in the corresponding folder but also all the other files I had tested and read. I had to manually delete them and only the it took my new file. How do I delete the previus file? or do I need to do: def Inputfiles(request): form = UploadFilesForm(request.POST, request.FILES, instance=request.user) if request.method == "POST": if form.is_valid(): form.save() return redirect('index') else: form = UploadFilesForm() return render(request, 'registration/File_Upload.html', {'form': form}) else: return render(request, 'registration/File_Upload.html', {'form': form}) The only thing I cant think of doing is add a request.user.file_one.delete() from [documentation delete()][1] but I don't know where to put suck line if it would even work. models.py class User(AbstractUser): email = models.EmailField(unique=True) file_one = models.FileField(upload_to='csvfiles', validators=[FileExtensionValidator(allowed_extensions=['csv'])]) file_two = models.FileField(upload_to='csvfiles', validators=[FileExtensionValidator(allowed_extensions=['csv'])]) -
OSError: exception: access violation writing 0x00001CE8
I just loaded a shapefile manholes in geodjango but I'm getting an error when trying to open one layer, anyone had experience with this kind of error? OSError: exception: access violation writing 0x00001CE8 [21/Jun/2018 08:36:55] "GET /admin/ww_manholes/ww_manholes/4640/change/ HTTP/1.1" 500 429383 -
Ajax Post URL with buttton id, Django Server
Im trying to delete an element in a list by clicking a button, each button got the pk of the element as id $('.delete').on('click', function (event) { var evaluacion_id = this.id; $.confirm({ title: 'Desea Eliminar Evaluacion?', content: 'De ser asi no podra Recuperar estos datos', buttons: { confirm: function (evaluacion_id) { var url = "{% url 'delete-evaluacion' evaluacion_id %}" $.ajax({ type:"POST", url: url, success: function(){ location.href="{% url 'evaluaciones-psicologo' informe.proceso.pk %}" } }); }, cancel: function () { $.alert('Continue Evaluando'); }, } }) }); if i do $.alert("Delete "+evaluacion_id); instead of the ajax function everything its ok and it shows me the correct id But if I call it with ajax function, throws me this Reverse for 'delete-evaluacion' with arguments '('',)' not found. 1 pattern(s) tried: ['INTRANET\\/delete-evaluacion/(?P<pk>\\d+)$'] And my urls.py url(r'^procesos/EvaluacionesPsicologo/(?P<pk>\d+)$',views.evaluaciones_psicologo,name='evaluaciones-psicologo'), url(r'^procesos/EvaluacionePsicologo/(?P<pk>\d+)$',views.evaluacion_psicologo,name='evaluacion-psicologo'), url(r'^delete-evaluacion/(?P<pk>\d+)$', views.EliminarEvaluacion, name='delete-evaluacion'), -
How to convert “with open” into Django download button?
Hello I would like some help in converting this code into a Django download button. I looked at this Django page https://docs.djangoproject.com/en/2.0/howto/outputting-csv/ but it did not help me. I also looked for videos and other resources. What I need is when I collect all my data from api, it gets turned into a csv file for excel. This file will pop up a button when it’s ready for download. This code works for me when sending it to my computer. Also I apologize for the formatting on the code. Thank you for your time for item in Headers:#for header names in array "Headers" if item not in Keyz:#If not duplicate Keyz.append(item)#ADD Header diction=dict(zip(Headers,TabData))#Combine data to make dictionary dict2.append(diction)# put that dictionary in an array ''' Use "Key" instead of Keyz for better readability but less usability ''' if M ==(Size-1):#if done with document data with open(PdfLocation+'TabData_.csv', 'w',newline='') as f: w = csv.DictWriter(f, Keyz ,extrasaction='ignore')#What headers you want = Keyz array w.writeheader() for M in range(Size): w.writerow(dict2[M]) #write data