Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run or include gdal python scipt in Django
I am new (noobee) on Django. I have a python script that prints the times, X, Y of the dataset in a specific NetCDF file. import gdal netfile = gdal.Open('NETCDF:"E:/Jobs/statr.nc":tm25') print 'Band shape (T, Y, X): ', (netfile.RasterCount, netfile.RasterYSize, netfile.RasterXSize) How can I use this script in a Django project? For instance, if I have a button and an input box and on user click, show the script's output to the input box. Is there any way to include the script inside Django (view, template, etc)? Thanks in advance John -
?: (admin.E403) A 'django.template.backends.django.DjangoTemplates' instance must be configured in TEMPLATES in order to use the admin application
When i run my service using python manage.py runserver Then this error is occured. SystemCheckError: System check identified some issues: ERRORS: ?: (admin.E403) A 'django.template.backends.django.DjangoTemplates' instance must be configured in TEMPLATES in order to use the admin application. My settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
html tags in djnago email template
I am using django signals to send emails when a new record is assed to model : @receiver(post_save, sender=MeetingMember) def send_invited_emails(sender, instance, **kwargs): host = instance.meeting.host subject = "Mizban invition" # htmly = get_template('sendingemail.html') domain = Site.objects.get_current().domain context={'host':host,'meeting': instance,'domain':domain} html_content = render_to_string('sendingemail.html',context) send_mail(subject, html_content, settings.EMAIL_HOST_USER,[instance.email]) this code works but it sends html tags in email as well how can i sove this issue? -
Django ModelForm not valid (not saving to database)
I currently have a list of settings on my app, and if a user wants to update those settings I want them to be able to do that without going into the database. However, when the user clicks update , the page reloads but no changes are saved to the database. My code currently looks like this: Views.py: def viewSettings(request, settings_pk): setting = get_object_or_404(SettingsClass, pk=settings_pk) if request.method == 'GET': form = SettingUpdateForm(instance=setting) return render(request, 'main/viewSettings.html', {'setting': setting, 'form':form}) else: form = SettingUpdateForm(request.POST, instance=setting) if form.is_valid(): form.save() return redirect('settingsHome') return render(request, 'main/viewSettings.html', {'setting': setting, 'form':form}) Models.py: class SettingsClass(models.Model): Complex = models.CharField(choices=complex_list , max_length = 22 ,default='1' , unique=True) #Trial Balance Year To Date Trial_balance_Year_to_date= models.BooleanField(default = False) tbytd_Include_opening_balances=models.BooleanField(default = False) tbytd_Only_use_main_accounts=models.BooleanField(default = False) tbytd_Print_null_values=models.BooleanField(default = False) tbytd_Print_description=models.BooleanField(default = True) tbytd_Print_account=models.BooleanField(default = True) tbytd_Sort_by_account_name=models.BooleanField(default = True) #Trial Balance Monthly Trial_balance_Monthly=models.BooleanField(default = False) tbm_Only_use_main_accounts=models.BooleanField(default = False) tbm_Print_null_values=models.BooleanField(default = False) tbm_Print_description=models.BooleanField(default = True) tbm_Print_account=models.BooleanField(default = True) tbm_Sort_by_account_name=models.BooleanField(default = True) #Income Statement Year To Date Income_Statement_Year_to_date=models.BooleanField(default = False) isytd_Only_use_main_accounts=models.BooleanField(default = False) isytd_Sort_by_account_name=models.BooleanField(default = True) isytd_Print_null_values=models.BooleanField(default = False) isytd_Print_description=models.BooleanField(default = True) isytd_Print_account=models.BooleanField(default = True) #Income Statement Monthly Income_Statement_Monthly=models.BooleanField(default = False) ism_Only_use_main_accounts=models.BooleanField(default = False) ism_Sort_by_account_name=models.BooleanField(default = True) ism_Print_null_values=models.BooleanField(default = False) ism_Print_description=models.BooleanField(default = True) ism_Print_account=models.BooleanField(default = True) #Age … -
Generating automatic user registration number using django
What i wanted to achieve? I wanted to achieve {Company Letter}- {Country Code}-{1st Letter of 1st Name}{1st Letter of Last Name}-{000001-999999} For example: Company Name: Stack Overflow Username: Stack Overflow County is USA SO - 001 - SO - 000001 For that i have created a country, state and city model. I have created a custom user model. In the custom user model, i am using country, state, city drop down. So there is one field called registration numbers.. How can i generate registration number after registering one user.. Please guide me.. -
creating a database table for week schedule
i want to create a table for storing a weekly schedule for a doctor, my approach was like this: class ScheduleDay(models.Model): doctor = models.ForeignKey(Doctor, on_delete= models.CASCADE) #the name of the week day day = models.CharField(max_length=15) clinic = models.ForeignKey(Clinic, on_delete=models.SET_NULL, null = True) start_time = models.TimeField() end_time = models.TimeField() is it a good design to do this? -
How to update a particular field of a django model in class based views?
models.py class Grocery(models.Model): name = models.CharField(max_length=40) price = models.IntegerField(default=0) quantity = models.IntegerField(default=0) time = models.DateTimeField(default=datetime.now()) class Meta: verbose_name = 'grocerie' class Person(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) groceries = models.ManyToManyField(Grocery) my views.py class PersonSavedUpdateView(LoginRequiredMixin, UserPassesTestMixin,UpdateView): model = Person fields = ['groceries'] def test_func(self): person = self.get_object() if self.request.user == person.user: return True return False Here I want to update groceries field in the Person model through this updateView but i want to only delete a particular grocery from the logined User, How to do it -
React Django Application different ip adresses CORS issues
I try to deploy an APP1 application on an EC2 (whose IP address is app1_ip): the frontend is created with React and the backend is created with Django, django-rest-framework, gunicorn and nginx. The backend is the same as another APP2 application that is already deployed on a second EC2 (whose IP address is app2_ip). I have no trouble getting the second application to work and request its React frontend (located at port 3000 of app2_ip) on its backend (located at port 8000 of app2_ip). On the other hand, I have a lot of trouble requesting the backend of APP2 from the frontend of APP1. I'm missing something but I can't see what. I am looking to develop the cleanest production configuration possible. I have a login page that prompts the user to enter a password and a username. A request is then sent to the backend to verify these credentials. Fetch request from the login page used in the APP1 backend deployment : fetch(`https://{app2_ip}/token-auth/`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) nginx.conf file used in the APP2 backend deployment upstream django { server backend:8000; } server { listen 80; server_name my_server_name return 301 https://{my_server_name}$request_uri; } server … -
DJANGO - [Errno 30] Read-only file system: '/media'
I need your help because of an error regarding Media directory on Django forms.py from django.forms import ModelForm from .models import Mots from django import forms class CreeMot(ModelForm): mot = forms.CharField(max_length=50) level = forms.IntegerField(max_value=10) image = forms.FileField() class Meta: model = Mots fields = ["mot", "level", "image"] views.py def cree_mot(request): if request.method == "POST": form = CreeMot(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect('/success/url/') else: form = CreeMot() return render(request, "cp/cree_mot.html", {'form': form}) settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' # Add these new lines STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'staticfiles', 'media_root') And the error I have hen i submit my form [Errno 30] Read-only file system: '/media' Actually my /media/ directory is at the same place like /static/ cp /views.py /forms.py main_app /settings.py /... media static manage.py If you have a solution ... I put my /media/ in 777 chmod just in case ;) ... Thanks for your help ... Django is very usefull but regarding static and media it's not so easy to use ;) -
How can I use django-clever-selects for filters instead of forms?
I'm using ChainedChoiceField of django-clever-selets to automatically update a field if another field changes, in a form like this: class SomeForm(forms.Form): some_field = ChainedChoiceField( label=_("Field depending on parent field"), parent_field="some_parent_field", ajax_url=reverse_lazy('ajax:AjaxSomeView') ) Now I need the same functionality in a django rest framework FilterSet instead. Something like this: from django_filters.rest_framework import filters from django_filters.rest_framework import filterset class ChainedChoiceFilter(filters.ChoiceFilter): # This does not work, it's just a concept field_class = ChainedChoiceField class SomeFilterSet(filterset.Filterset): some_field = ChainedChoiceFilter( label=_("Field depending on parent field"), parent_field="some_parent_field", ajax_url=reverse_lazy('ajax:AjaxSomeView') ) Is there a way to do this? -
dj rest auth reset password sends raw html in email
I use dj rest auth package and i have overrided the reset password email like this in settings.py : REST_AUTH_SERIALIZERS = { 'JWT_TOKEN_CLAIMS_SERIALIZER': 'account.token.TokenObtainPairSerializer', 'USER_DETAILS_SERIALIZER': 'account_profile.api.userupdate.UserSerializer', 'PASSWORD_RESET_SERIALIZER': 'account_profile.api.customemail.CustomPasswordResetSerializer'} and in customemail.py : class CustomPasswordResetSerializer(PasswordResetSerializer): def save(self): request = self.context.get('request') # Set some values to trigger the send_email method. opts = { 'use_https': request.is_secure(), #'from_email': 'noreply@mizbans.com', 'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'), 'request': request, # here I have set my desired template to be used # don't forget to add your templates directory in settings to be found 'email_template_name': 'password_reset_email.html' } opts.update(self.get_email_options()) self.reset_form.save(**opts) and in email.py : class MyPasswordResetSerializer(PasswordResetSerializer): context={'domain':settings.WEBSITE_DOMAIN,'site_name':'mizban'} def get_email_options(self) : return { 'email_template_name': 'password_reset_email.html', 'context':'context' } I put a sample html code in password_reset_email : <html> <body> <p>welcome to{{domain}}</p> <p>site {{site_name}}</p> </body> </html> It works but it sends html tages codes as well in email template! -
getting the count of a query set in Django
i am making a doctor appointment system, and i want to get the count of how many appointment i have in a specific day, so instead of doing it this way: appointments_count = Appointment.objects.filter(user = user, date = specific_date).count() will it be more efficient if i make another table for keeping track of the count of the appointments for each date, to avoid more i/o disk operations class Date_Counter(models.Model): doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) date = models.DateField() count = models.PositiveIntegerField(default=1) and thanks everyone -
Django : Set is_active flag for User created by social-auth-app-django and google_oauth2
I am using social-auth-app-django for signup-signin of new users using google oauth2 authentication. after signup a new user is created in my db but the is_active is set as false, I want to set is_active as true only for users created by this social_auth google authentication (for other users who sign up using email-password I activate them by sending an account activation email) I have tried setting is_active = True for all users with no password , but I feel this way is insecure and hackish . How do I modify the social_auth_login flow to activate users as well ? I am using a custom User model : class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) if password: user.set_password(password) # else: # user.is_active = True <-------- tried this , worked too user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_active', True) extra_fields.setdefault('user_type', user_constants.SUPERUSER) if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(email, password, **extra_fields) .. class User(AbstractUser): username = None # remove username field, we will use email as unique identifier email = models.EmailField(unique=True, null=True, db_index=True) client_id = … -
Don't return forms in context if they are not altered?
In my HTML-file I have a submit button (click_button) to do stuff and a submit button for a Django form (form_submit). All submits are redirected to one View-function (get_post_from_submit). If using the return render() function, I always have to return the context including the form, but I have no information of the form when I pressed the click_button. Is there any way to not return the form again? def get_post_from_submit(request): if request.method == 'POST': if "form_submit" in request.POST: # Do Stuff form = form_book(request.POST) if "click_button" in request.POST: # Do Stuff # Here the form always gets a reset, because I have no Info about the form in POST but it is needed as context... form = form_book() return render(request, 'home.html',{"form": form}) -
Vehicle rental system Database Structure [closed]
Vehicle Allotment The vehicle Allotment should be done automatically.A particular vehicle may have multiple quantities, hence if one vehicle is alloted for a duration of 2 hours the other vehicle must accept booking for that duration, if no vehicles are available then show "out of stock". The price of vehicles can change on weekends or on special occations. This is a project that I am currently working on and I am stuck at this. I am building this project with python Django. and Database MySql. Please Help. -
How to filter results and manytomany childs?
I am making a web page that display a "Kanban". I have columns as well as cards. I want to filter the results according to a field (priority) in the cards (Sale). My models: class PipelineColumn(models.Model): name = models.CharField(_("Name"), max_length=80) order = models.PositiveIntegerField(_("Order of column"), unique=True) default_probability = models.PositiveSmallIntegerField(_("probability")) class Meta: verbose_name = _("PipelineColumn") verbose_name_plural = _("PipelineColumns") ordering = ["order"] def __str__(self): return self.name class Sale(models.Model): name = models.CharField(_("name"), max_length=255) expected_income = models.FloatField(_("expected income")) probability = models.PositiveSmallIntegerField(_("probability")) contact = models.ForeignKey( "crm.Person", verbose_name=_("person"), related_name="sale_person", on_delete=models.PROTECT, ) date = models.DateField(_("date"), auto_now_add=True) scheduled_closing_date = models.DateField(_("scheduled closing date")) priority = models.PositiveSmallIntegerField(_("priority"), default=0) column = models.ForeignKey( "crm.PipelineColumn", verbose_name=_("column"), related_name="sale_column", on_delete=models.CASCADE, ) class Meta: verbose_name = _("Sale") verbose_name_plural = _("Sales") ordering = ["scheduled_closing_date", "-priority"] def __str__(self): return self.name For example, I would like to display only the columns and cards that have a priority of 2. If I try with PipelineColumn.objects.filter(sale_column__priority=2) it filters the columns well, only the columns with a sale with a priority equal to 2 are displayed. On the other hand, in the displayed columns all the sales are displayed even those whose priority is not equal to 2. I would also like to be able to filter the sales returned by my … -
django queryset filter many2many
In django i have two model classes that both of them have a many2many field. I want filter objects from this models that have subscription in their two many2many fields. How can I do that with queryset? -
ERROR while iterating through csv files in python [duplicate]
"csv.Error: iterator should return strings, not int (did you open the file in text mode?)" thrown while iterating through csv files in the folder I want to iterate through the files and need name of the file, row count and column data. below is my code root_dir=os.fsencode("D:/Django/bmat/files") for file in os.listdir(root_dir): reader = csv.reader(file, delimiter=",") data = list(reader) row_count = len(data) print(row_count) Error message File "D:\Django\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "D:\Django\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Django\venv\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "D:\Django\venv\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "D:\Django\bmat\app\repertoire\management\commands\csv_ingest.py", line 9, in handle data = list(reader) _csv.Error: iterator should return strings, not int (did you open the file in text mode?) -
How to split html content in 2 pages with xhtml2pdf Django
I'm using xhtml2pdf in my django app and I would like to split my html content in 2 pages but keet all of it on the same html file someone have a idea how to do that ? I've read in xhtml2pdf documentation that we could use -pdf-next-page but I don't understang where should i use this tag. I give you the link of the documentation : https://xhtml2pdf.readthedocs.io/en/latest/reference.html Here my HTML <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Fiche Medicale {{ fiche_medicale.nom_patient }}</title> <style type="text/css"> @page first { -pdf-next-page:1; size: letter portrait; @frame header_frame { /* Static Frame */ -pdf-frame-content: frame_header_left; left: 40pt; width: 270pt; top: 10pt; height: 150pt; } @frame header_frame { /* Static Frame */ -pdf-frame-content: frame_header_right; left: 300pt; width: 270pt; top: 50pt; height: 150pt; } /* ====================== COL 1 COORDONNEES ====================== */ @frame col1 { -pdf-frame-content: frame_col1; left: 30pt; width: 540pt; top: 135pt; height: 130pt; } @frame col1_1 { -pdf-frame-content: frame_col1_1; left: 40pt; width: 270pt; top: 165pt; height: 130pt; } @frame col1_2 { -pdf-frame-content: frame_col1_2; left: 340pt; width: 270pt; top: 165pt; height: 130pt; } /* ====================== COL 2 HOSPITALISATION ====================== */ @frame col2 { -pdf-frame-content: frame_col2; left: 30pt; width: 540pt; top: 245pt; height: 130pt; } @frame col2_1 { … -
Deploy static file of djago on IIS
I read some similar issue on stackflow but sill stuck with this problem. the web django can deploy on ISS well except CCS style for admin and all CSS. what I tried: use whitenoise -> I got error when I wrote whitnoise tag in middleware. then i stopped use this way use add virtual directory more information -> i created virtual enviroment venv_>my django>app folder honestly, I really dont know where virtual directory (named static) should be, then I tried at default web site venv_ my project folder (my static folder after use collectstatic django) I tried to use path physical to (my static folder after use collectstatic django) it still not working more information I used findstatic but got another path not (collectstatic path in my project app) it is in my venv_ package? -
How to allow superuser to all users passes test?
Here I have many UserPassesTest and in those test I want to allow superusers automatically. Here I have to do self.request.user.is_superuser in every class. I don't want to write this in every class. How can I do it ? class Permission1(UsersPassesTestMixin): def test_func(self): some_condition = True return self.request.user.is_superuser or some_condition class Permission2(UsersPassesTestMixin): def test_func(self): some_condition = True return self.request.user.is_superuser or some_condition class Permission3(UsersPassesTestMixin): def test_func(self): some_condition = True return self.request.user.is_superuser or some_condition -
Error: 404 Page Not Found. After trying to update a form
I currently have a settings model for my Django app which saves a set of settings for the rest of the program to read from. I have tried to create a way to update these settings on the app, as per the below code. When the update button is clicked, however, the app returns a page not found error instead of updating the database. Does anyone know what could be causing it because I cannot seem to find any errors in the code? Views.py: def viewSettings(request, settings_pk): setting = get_object_or_404(SettingsClass, pk=settings_pk) if request.method == 'GET': form = SettingUpdateForm(instance=setting) return render(request, 'main/viewSettings.html', {'setting': setting, 'form':form}) else: try: form = SettingUpdateForm(request.POST, instance=setting) form.save() return redirect('settingsHome') except ValueError: return render(request, 'main/viewSettings.html', {'setting': setting, 'form':form, 'error':'Bad info'}) Models.py: class SettingsClass(models.Model): Complex = models.CharField(choices=complex_list , max_length = 22 ,default='1' , unique=True) #Trial Balance Year To Date Trial_balance_Year_to_date= models.BooleanField(default = False) tbytd_Include_opening_balances=models.BooleanField(default = False) tbytd_Only_use_main_accounts=models.BooleanField(default = False) tbytd_Print_null_values=models.BooleanField(default = False) tbytd_Print_description=models.BooleanField(default = True) tbytd_Print_account=models.BooleanField(default = True) tbytd_Sort_by_account_name=models.BooleanField(default = True) #Trial Balance Monthly Trial_balance_Monthly=models.BooleanField(default = False) tbm_Only_use_main_accounts=models.BooleanField(default = False) tbm_Print_null_values=models.BooleanField(default = False) tbm_Print_description=models.BooleanField(default = True) tbm_Print_account=models.BooleanField(default = True) tbm_Sort_by_account_name=models.BooleanField(default = True) #Income Statement Year To Date Income_Statement_Year_to_date=models.BooleanField(default = False) isytd_Only_use_main_accounts=models.BooleanField(default = False) isytd_Sort_by_account_name=models.BooleanField(default = True) isytd_Print_null_values=models.BooleanField(default = … -
Django rest framework, how to redirect to other viewset as post request
I have two viewsets: UserViewSet and GoogleViewSet. In the GoogleViewSet I want to validate token and then redirect to UserViewSet. class GoogleViewSet(APIView): def post(self, request): # some logic password = User.objects.make_random_password() return redirect(reverse('v1_users:user_create'), kwargs={'email': 'test@test.com', 'username': 'test', 'password': password}) But on redirect I got 405 Error { "detail": "Method \"GET\" not allowed." } How can I redirect as post request? -
Get PDF from HTML form view template with xhtml2pdf Django
I get a problem with my function letting to get a PDF file from my HTML form view. It generate all choices to pdf from the form, and I would like to generate only chosen options from the forms.ChoiceField in forms.py. My view.py: from django.shortcuts import render from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from django.views import View from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1", 'ignore')), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None form = Formularz context = { 'form': form, } class ViewPDF(View): def get(self, request, *args, **kwargs): pdf = render_to_pdf('PLK/pdf_template.html', context) return HttpResponse(pdf, content_type='application/pdf') class DownloadPDF(View): def get(self, request, *args, **kwargs): pdf = render_to_pdf('PLK/pdf_template.html', context) response = HttpResponse(pdf, content_type='application/pdf') filename = "Invoice_%s.pdf" % ("12341231") content = "attachment; filename='%s'" % (filename) response['Content-Disposition'] = content return response def FormularzView(request): template_name = 'PLK/PLK.html' form = Formularz context = { 'form': form, } return render(request, template_name, context) on template I have got 2 buutons, first to view PDF, second to donwload. -
Pytest: how to mock django management command class method variable
There is a django manager command that handles the csv file. app/my_app/my_command.py class Command(BaseCommand): def handle(self, *args, **options): path = (os.path.join(os.path.abspath(os.path.dirname(__name__)), 'data.csv')) # other logic with file I am writing a test for it in pytest, the problem is that I can not understand how to mock the variable path to test accessed not the real data.csv but a temporary test.csv file @pytest.fixture def create_test_csv_file(tmpdir_factory): path = tmpdir_factory.mktemp('data').join('test.csv') # other logic return str(path) @pytest.mark.django_db def test_function(mocker, create_test_csv_file): # smth like mock_path = create_test_csv_file <- NEW CODE HERE call_command('my_command')