Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Take a value from earlier in the page and use it in a form
Say I have a html form: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <button type="submit" name="create" class="buttonsmall"> Create</button> <input type="hidden" name="selected[]" value="" /> </form> This is in a div that is much farther down my page (at the bottom). I have established selected[] further up the page in another div. Due to my css and positioning I'd rather keep the two elements separate, but I'd love to send that data with this button. How do I get my hidden element to reference the selected[] from further up the page? -
Safe way to persist multiple clients dara
I am currently developing a computer based test web app with Django, and I am trying to figure out the best way to persist the choices users make during the course of the test. I want to persist the choices because they might leave the page due to a crash or something else and I want them to be able to resume from exactly where they stopped. To implement this I chose saving to Django sessions with db backend which in turns save to the database and this will resolve to a very bad design because I don't want about 2000 users hitting my db every few seconds. So my question is are there any other ways I can go about implementing this feature that I don't know of. Thanks -
Understanding Backend and Frontend
So I am making an employee scheduling web app like this. The web app will have an algorithm that will be used to create a schedule with a click of a button determining which employee will do what shift. I'm planning to make the backend with Django as I was well versed in Python and not so much in JS. However, my question is that will the algorithm/calender be done on Python or JS, i.e. will it be part of front-end or back-end? If it is frontend then is it possible that I can do it after learning React? And if I am learning JS & React, would you recommend me to go for Node.js over Django? (I'm doing this project for future employment opportunities) Thanks for the help! -
Removing a Django migration after "makemigration" but before "migrate"
Apologies for the very basic nature of the question; I am a beginner here with Django. I don't want to mess up the migration structure of my app. I am using Django 3.0.2. with a Postgresql DB. My app is "myapp" and myapp has had several successful migrations thus far. Then today I made more changes to my existing model. In Mac terminal I then ran: python manage.py makemigrations myapp A migration file was created Migrations for 'myapp': myapp/migrations/0007_auto_20200117_0814.py - Add field myfield to appTable However, before running "migrate" on this migration (i.e., "0007_auto_20200117_0814.py"), I have seen an error in my approach to the model change I wish to make, so I want to remove the above migration -- in other words, I do not want to run "migrate" on it. I just want it to ... go away, for lack of a better phrase. I then would like to make some changes to my model and re-run "makemigrations." I've googled around and almost all answers I found regarding "deleting" a migration appear to assume that the "migrate" command was already run on the migration. My question, how does one safely remove a migration after "makemigrations" command was run but … -
Django Form Not Writing to JSON File in html call error
I am writing a program in django where I need to write the form results into a JSON file and from that JSON file write the variables to an html file. I was able to access the json file variables in the html file, but the views program to write the form variables to json is not working. Here is my code: views.py from django.shortcuts import render from .forms import ListForm from django.http import HttpResponseRedirect import json import os from django.conf import settings pricesFile = os.path.join(settings.BASE_DIR, 'CharlemagneApp/static/prices.json') accountInfoFile = os.path.join(settings.BASE_DIR, 'CharlemagneApp/static/accountInfo.json') def MakeMoney(request): if request.method == 'POST': form = ListForm(request.POST) if form.is_valid(): def getJSON(filePathAndName): with open(filePathAndName, 'r') as fp: return json.load(fp) def StartProgram(request): #print("program started") rawJSON = getJSON(pricesFile) rawJSON['capital'] = int(form.cleaned_data['capitalToInvest']) with open(pricesFile, 'w') as fp: json.dump(rawJSON, fp) rawJSON2 = getJSON(accountInfoFile) rawJSON2['email'] = form.cleaned_data['robinUser'] rawJSON2['pass'] = form.cleaned_data['robinPass'] with open(accountInfoFile, 'w') as fp: json.dump(rawJSON2, fp) return render(request, 'index.html') #StartProgram() return HttpResponseRedirect('/index.html/') else: form = ListForm() return render(request, 'home.html', {'form': form}) def Pass(request): return render(request, 'index.html') urls.py from django.urls import path from . import views urlpatterns = [ path('index.html', views.MakeMoney, name='index'), path('home.html', views.Pass, name='home') ] accountInfo.json { "email": "bobqwerty@gmail.com", "pass": "abc1234" } index.html <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script> <script> $(function() { … -
Send an Array via a POST Message in Django
I have an array of checkboxes. {% for groups in groupList %} <tr> <td id="checkboxes"> <input type="checkbox" name="check" id="check_{{groups.GroupID}}"> </td> <tr> {% endfor %} I'd like to pass this array (preferably by ID so I can get the GroupID in the view) in a POST message. I'm not sure how to send this data though. Is there any way of attaching an array to a form parameter? Or any alternative solution? -
Django model (inheritence, one-to-many, many-to-many)
models.py from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ class Book(models.Model): class TYPE_OF_BOOK(models.TextChoices): COMPUTER = 'COM', _('Computer') NATURAL_SCIENCE = 'NAT', _('Natual_Science') ECONOMY = 'ECO', _('ECONOMY') HISTORY = 'HIS', _('History') type_of_book = models.CharField( max_length=10, choices=TYPE_OF_BOOK.choices, default=True, ) title = models.CharField(max_length=100) author = models.CharField(max_length=50) published_date = models.DateField(blank=True) def __str__(self): return self.title class Review(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='reviews') author = models.CharField(max_length=50) text = models.TextField() grade = models.IntegerField(default=5) created_date = models.DateTimeField(default = timezone.now) def __str__(self): return self.text At this moment, each book can have reviews. How to approach book by average of grade in reviews which the book has. --extra explain-- I tried one-to-many and can access book.reviews. But I can't approach book by grade I tried many-to-many and can't access book.reviews -
Extra row after each row while serving a csv file in Django via s3
I am trying to serve a csv file through a button click in Django. The file is stored on AWS s3 bucket. Below is my function in views.py: def download(request): s3 = boto3.client('s3') obj = s3.get_object(Bucket='my_bucket', Key='Output.csv') file = obj['Body'] content = file response = HttpResponse(content, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="Output.csv"' return response When I click on the button, I can download the file easily. However, when I open the downloaded csv file in Microsoft Excel, there is an extra blank row after each row. Is there a way to not get these extra lines in the downloadable file? -
Django: Is it possible to open a transaction, ask a user for confirmation, then commit transaction if confirmed or roll back
I've read the docs: https://docs.djangoproject.com/en/3.0/topics/db/transactions/ But what's not clear to me, is whether a transaction can span HTTP requests. The idea is simple enough: user submits a form backend then opens a transaction saves the data presents user with a confirmation form user then confirms or cancels backend then commits on confirmation or rolls back on cancel The main issue being that the transaction is opened on on HTTP request, then a user response is waited for (if never received I imagine on a time out we'd roll back) and when it comes on a second HTTP request, the transaction is committed. I see nothing covering such a use case in the docs and have found nothing on-line. Yet it would strike me as a fairly ordinary use case. It arises primarily because the submission is complicated, involving many models and relations, and the easiest (almost only sensible or tenable) way to examine the submissions impact is to save all those and then study the impact. That works brilliantly as it happens, but I've thus far been force to make a commit or roll back decision in the one request, when processing the form. I'd like now to throw my … -
How can I create a separate module for role based permissions in django?
enter image description here enter image description here Feature Description: 3 different roles to be created in the system to manage access. Use Case Description: "Administrator: To have full access Handler: One who can just add and issue inventory. Cant check stock or have access to any report. Manager: One who can access stock and other reports" Detailed Description: "1) Create roll management tab to handle users tab Accessibility. Admin have ability to give access only particular tab to particular user only. Add Search functionality Job List with navigation. Create Job roles Assign access to different modules for that job role" -
Search filter django drf
i want to get image as multiple search keyword at once: views.py: class ImageSearchView(generics.ListAPIView): authentication_classes = [] permission_classes = [] queryset = Image.objects.all() serializer_class = ImageSearchSerializer filter_backends = (filters.SearchFilter,) search_fields = ['image_keyword'] models.py: class Image(models.Model): license_type = ( ('Royalty-Free','Royalty-Free'), ('Rights-Managed','Rights-Managed') ) image_number = models.CharField(default=random_image_number,max_length=12,unique=True) title = models.CharField(default=random_image_number,max_length = 100) image = models.ImageField(upload_to = 'image' , default = 'demo/demo.png') thumbnail = models.ImageField(upload_to='thumbs', blank=True, null=True) category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) shoot = models.ForeignKey(ImageShoot, on_delete=models.CASCADE, related_name='Image', null=True,blank=True) image_keyword = models.TextField(max_length=1000) def __str__(self): return self.title urls.py: path('image_search/',views.ImageSearchView.as_view(), name = 'image_search'), when i make a request from postman: localhost:8000/api/image_search?search=boxing cricket kohli marykom i want to get every image which has keyword like any of the search parameter -
Nested input tags multidimention array form in Python
I try to read multidimentional form input data from HTML. I am not sure how to access the nested input tag data in Django View page.Could someone guide me on this matter? <input type="checkbox" name="create[1][1]"> <input type="checkbox" name="edit[1][2]" > <input type="checkbox" name="delete[1][3]"> <input type="checkbox" name="create[2][1]"> <input type="checkbox" name="edit[2][2]" > <input type="checkbox" name="delete[2][3]"> -
Django modelform NameError: name 'check_in' is not defined
Hi everyone I am a beginner in django, building a lodge reservation system with django3.0 and i can't seem to get my modelform to generate a proper queryset to get data in my Reservations model, i keep getting the NameError error message everytime i try enter a new date through my view and right now im not quite sure how to properly solve this error here is my models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User now = timezone.now end = timezone.now() + timezone.timedelta(days=2) room_choices = [ ('single_room', 'Single Room'), ('double_room', 'Double Room'), ('executive_room', 'Executive Room'), ] class Reservation(models.Model): room_type = models.CharField(max_length=30, choices=room_choices, default=room_choices[1]) check_in = models.DateField(default=timezone.now) check_out = models.DateField(default=end) class Meta: verbose_name = 'Reservation' verbose_name_plural = 'Reservations' I would like to add validation statements later in views.py for price and number of rooms depending on the room_type the user selected so disregard the field for now here is my forms.py: from django import forms from .models import Reservation class AvailabilityForm(forms.ModelForm): class Meta: model = Reservation fields = [ "room_type", "check_in", "check_out", ] widgets = { 'check_in': forms.DateInput(format='%m/%d/%Y'), 'check_out': forms.DateInput(format='%m/%d/%Y'), } If someone knows how to get the widgets to work properly outside of admin, … -
Multiple auth login pages in Django
I have multiple apps in one django project /user /manager /business` that need to have separate view logic and appearance from one another. How do I use django.contrib.auth to satisfy this? I have urlpatterns in main are: urlpatterns = [ path('admin/', admin.site.urls), path('user/', include('user.urls')), path('user/', include('django.contrib.auth.urls')), path('manager/', include('manager.urls')), path('manager/', include('django.contrib.auth.urls')), path('business/', include('business.urls')), path('business/', include('django.contrib.auth.urls')), Urlpatterns in the apps are like those: urlpatterns = [ path('index', views.index, name='index'), path('register', views.register, name='register'), ] and I have different views for login and register, also have different templates in each app: /templates/register/register.html and /templates/register/login.html However, login and register views seem to be shared between apps. Is there a way to separate them with ease? -
Django ManyToMany passing variables
I have started my Django project and I want to share some data between 2 classes. I'm not sure if I am doing it correctly. It works but i don't want to populate in my project bad practices. My code looks like this: class Products(models.Model): name = models.CharField(max_length=50) protein = models.FloatField() carbohydrates = models.FloatField() fat = models.FloatField() food_type = models.CharField(max_length=6, choices=( ("1", "Meat"), ("2", "Fruit") ) ) class Meals(models.Model):#Child name = models.CharField(max_length=50) ingredient = models.ManyToManyField(Products) def protein(self): protein = 0 for ing in self.ingredient.all(): protein += ing.protein return protein @property def carbohydrates(self): carbohydrates = 0 for ing in self.ingredient.all(): carbohydrates += ing.carbohydrates return carbohydrates def diet_category(self): diet_types = "vegan, vegeterian, Keto, Paleo, Gluten-free" food_types = "" for ing in self.ingredient.all(): food_types += ing.food_type if "1" in food_types: diet_types.replace("vegan, ", "").replace(" vegeterian,", "") return (diet_types + " | " + food_types) Additionally I have problem with .replace() function in python, which i want to use here to exclude some words from variable. Summing up my questions are: -Retrieving properties from another class is done by referring to an object of that class. In this case Products.objects.all() -How can I remove words from variable in models. -Should i use @property for functions … -
Django: remove Decimal prefix from queryset annotated field, when requesting values
to be brief, i have this queryset: monthly_revenue = list(Booking.objects.annotate(month=Month('created_at')) .values('month') .annotate(total=Sum('price')) .order_by('month')) this is what it is returning: [{'month': 11, 'total': Decimal('4550.00')}] the result is going to a js script to show a graph, and i need to remove the Decimal() prefix. Any help or hint is appreciated. -
Daphne server unable to handle http requests
I have a django application which I want to deploy using daphne. Django application supports both websockets and http requests. I've converted the django to support ASGI. I'm starting the server using : daphne <project_name>.asgi:application The server is able to accept websocket connections but unable to handle the incoming HTTP requests(throws 404). Where am I going wrong over here? P.S.: I'm not using django channels. -
Django: Adding FK relation to existing model
I have a project where I need to change a normal field to an FK field and that in multiple models. The problem is that the project is productive and the database (Postgres) is full of entries. I started locally by just mindlessly changing the field type to forgein_key() and trying to do a migration. Seems that Django is so smart that he tries to update this field, but he stumbles because of values in the model that don't exist in the related model. How can I skip those errors? Can I tell Django to set the FK == null if the related entry does not exist? Heres some code: from persons.models import Customer, Employee class Insurance(models.Model): id = models.BigAutoField(primary_key=True) customer = models.ForeignKey(Customer, models.SET_NULL, blank=True, null=True) employee_id = ForeignKey(Customer, models.SET_NULL, blank=True, null=True) objects = models.Manager() Before those fields where char fields and the relation was made in the backend code. The reason I'm trying to do this is that I need the functionalities from Django like select / prefech_related for the search functionality in the frontend insurance table. The user should have the option to search also for the name of the insured person rather than just the ID. This … -
how to save muliple json field django /models.py in this code i try to save field but only single json field save
how to save muliple json field in this code i try to save field but only single json field save json like this {"data":[ {"id":1,"name":"name_1"}, {"id":1,"name":"name_2"}, {"id":1,"name":"name_3"}]} model.py class Title(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255) view.py def get_titles(request): r = requests.get('https://api.myjson.com/bins/1d8vhy') titles = r.json() print(titles['data']) for title in titles['data']: try: if not title: a = Title.objects.filter(id=title['id']).update(name=title['name']) print("update2") return render(request, "get_titles.html", {'titles': Title.objects.all()}) else: a = Title.objects.create(id=title['id'], name=title['name']) a.save() print("create") return render(request, "get_titles.html",{'titles':Title.objects.all()}) except : a = Title.objects.filter(id=title['id']).update(name=title['name']) print("update1") return render(request, "get_titles.html", {'titles': Title.objects.all()}) -
Python Web Framework with Database
I am trying to essentially build a dashboard that displays data analytics. I have used dash, however, there should be other components added that make me reconsider the technology stack. The dashboard should be connected to a SQL database, as new data will continuously be added. Additionally, there should be a login feature were people with different rights are supposed to log in and the corresponding part of the dashboard will be shown to them. The user should then be able to export a pdf that contains certain plots or information from the dashboard. I have considered Django, but after playing around with it, it seems as if this is more suited for projects that start from scratch without a continuous new influx of data. Does anyone have a suggestion? I hope I explained it somewhat clearly and thank you in advance. -
Django upgrade 1.8 to 2.2.9 with customized adminsite. Reverse for 'app_list' with keyword arguments not found
For a client I am currently upgrading their Django project. However i ran into a problem. The django project uses a overridden AdminSite (app is called cms) and a normal admin site. When accessing any page on the custom admin site I receive the following exception: Reverse for 'app_list' with keyword arguments '{'app_label': 'analytics'}' not found. 1 pattern(s) tried: ['admin/(?P<app_label>filer|mmt|auth|gitbuilder)/$'] We narrowed it down to the _build_app_dict method in django.contrib.admin.sites line 457. The app_url reverse uses 'admin:app_list'. When overriding the method with the cms:app_list the page renders, but makes the site break in other different ways. It also does not feel like the right solution. Have I missed some changes in the AdminSite that were made between 1.8 and 2.2.9? Does anyone have any experience in dealing with the same issue? -
How to alter the ownership of some tables inside a database from postgres to another user?
I have a database which contains significant number of tables. Some of the tables are owned by postgres user and not the one I created. I want to transfer the ownership of such tables to the one I created,because when doing django-migrations, you can only set one user and password for the psql connection and that user doesnt have access to the tables owned by the postgres user, thus the migrations are not completed. So far, googling didn't help as they suggest either using ALTER or REASSIGN OWNED to change the ownership of the database or the table. But the problem is that these cannot change the ownership of some of the tables as they are required to be owned by postgres. I can manually change the ownership by selecting each table one by one, but when trying to do altogether,I get an error saying "ERROR: cannot reassign ownership of objects owned by role postgres because they are required by the database system". Manually changing more than a hundred tables is not an option. Does anyone have any workaround idea for this issue? -
how to call django function
i created a form which takes user input and then perform a computation function in excel. i have written all the code but having trouble in using that function. below is the view.py function code def dpr(request): def report(): userdate_date = request.POST.get('num1') userpath = request.POST.get('num2') # add = f'your num is {num1} and {num2} path = r'\\10.9.32.2\adm\Ash\FY 2019-20\Sale detail sheet' userpath1 = f'SALE DETAIL SHEET {userpath.upper()} 2020' abc = os.path.join(path, userpath1+'.xlsx') customers1 = [20,31,28,27,17,46,18,13,15,14,37,100125] customers2 = [100051,100062,100072,100087,100071,100070] customers3 = [100057,100056,100066,100068,100086,100091,100103,100126,100131,100145,100150,100152,100140,100165,100180] x = datetime.datetime.now() month = x.strftime("%B") df = pd.read_excel(open(abc, "rb"), sheet_name= month.upper() ,index_col=None, header= None) tarik = userdate_date # program for sumifs and countifs for customers1 and appending data to Dpr sum_list1 = [] count_list1 =[] for i in customers1: ab = df[df[2] == i] a= (ab[ab[6]== tarik][8]).sum() b= (ab[ab[6]== tarik][8]).count() sum_list1.append(round(a,2)) count_list1.append(b) app = xlwings.App(visible=False) wb = app.books.open(r'\\10.9.32.2\adm\Ash\FY 2019-20\DAILY REPORT\DAILY REPORT FORMAT.xlsx') # wb = xlwings.Book(r'\\10.9.32.2\adm\Ash\FY 2019-20\DAILY REPORT\DAILY REPORT FORMAT.xlsx') # xlwings.App().visible=False ws = wb.sheets['DPR'] ws.range('E7').options(transpose=True).value = count_list1 ws.range('F7').options(transpose=True).value = sum_list1 # program for sumifs and countifs for customers2 and appending data to Dpr sum_list2 = [] count_list2 =[] for i in customers2: ab = df[df[2] == i] a= (ab[ab[6]== tarik][8]).sum() b= (ab[ab[6]== tarik][8]).count() sum_list2.append(round(a,2)) count_list2.append(b) ws.range('E20').options(transpose=True).value = count_list2 … -
How to sort a value according a typle inside list
Hello I am getting output like this [OrderedDict([('id', 113), ('unread', True), ('timestamp', '2019-12-19T08:09:35.042804Z')]),OrderedDict([OrderedDict([('id', 115), ('unread', False), ('timestamp', '2019-10-19T08:09:35.042804Z')]),OrderedDict([OrderedDict([('id', 119), ('unread', True), ('timestamp', '2019-10-19T08:09:35.042804Z')])] What I want to do is I need to filter the datas according to unread= True or unread = False If I am printing a[0] I can getting OrderedDict([('id', 113), ('unread', True), ('timestamp', '2019-12-19T08:09:35.042804Z')]) But I don't know how to get the tuple inside the list and check the values How can I sort all unreaded messages and readed messages -
Django (forms) - Erorr: ValueError at /blog/1/share/
I write forms and there is such a problem. I tried the solutions from the Internet but it did not help. Please tell me what could be the problem. views.py def post_share(request, post_id): post = get_object_or_404(Post, id=post_id, status='published') sent = False if request.method == 'POST': form = EmailPostForm(request.POST) if form.is_valid(): cd = form.cleaned_data post_url = request.build_absolute_uri(post.get_absolute_url()) subject = '{} ({}) recommends you reading " {}"'.format(cd['name'], cd['email'], post.title) message = 'Read "{}" at {}\n\n{}\'s comments: {} '.format(post.title, post_url, cd['name'], cd['comments']) send_mail(subject, message, 'admin@myblog.com', [cd['to']]) sent = True else: form = EmailPostForm() return render(request, 'blog/post/share.html', {'post': post, 'form': form, 'sent': sent}) share.html {% extends "blog/base.html" %} {% block title %}Share a post{% endblock %} {% block content %} {% if sent %} <h1>E-mail successfully sent</h1> <p>"{{ post.title }}" was successfully sent to {{ form.cleaned_data.to }}.</p> {% else %} <h1>Share "{{ post.title }}" by e-mail</h1> <form action="." method="post"> {{ form.as_p }} {% csrf_token %} <input type="submit" value="Send e-mail"> </form> {% endif %} {% endblock %}