Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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') -
Django custom exception to return 503 and ignore sending admin mail
I want to raise a custom exception that will: return 503 status don't send django admin email I can do one of them, but not both together return 503: using drf ApiException, or custom exception handler to handle response, but I won't get the exception type in the email record to filter don't send email: checking exception type in a custom email handler class, but this returns 500 -
How to create alert from view model
I want to validate file. While file is invalid, i want to refresh my page and inform user that he did not upload proper file. So i have this in my views/campaign.py try: wb = load_workbook(mp_file) except BadZipfile: return redirect('campaign_add', client_id) The only way i know how to do it is add another attribute to client class which will be is_error(models.BooleanField()) And then change views/campaign to try: client.is_error = False wb = load_workbook(mp_file) client.save() except BadZipfile: client.is_error = True client.save() return redirect('campaign_add', client) And with another attribute i can add in my campaign.html file some kind of if is.error is true i'm adding some kind of windows with information about bad file after reloading page. But is there any way to do it without adding another attribute? -
How do I prevent the Django admin delete confirmation view to display all the objects to be deleted?
I have a object that has several thousand related objects. How can I make the confirmation view in the Django administration only display the Yes/No buttons without the list of all the objects to be deleted. The problem is that displaying the whole list of objects takes way too much time. I am using Django 3.0.3. -
Error during execution: docker-compose run --rm api python3 manage.py migrate
I install saleor on Linux Mint according to the instructions https://docs.saleor.io/docs/3.0/developer/installation When executing the command "docker-compose run --rm api python3 manage.py migrate", an error appears, tell me how to fix it? $docker-compose run --rm api python3 manage.py migrate Starting saleor-platform_db_1 ... Starting saleor-platform_jaeger_1 ... done Starting saleor-platform_redis_1 ... done ERROR: for saleor-platform_db_1 a bytes-like object is required, not 'str' ERROR: for db a bytes-like object is required, not 'str' Traceback (most recent call last): File "/usr/lib/python3/dist-packages/docker/api/client.py", line 261, in _raise_for_status response.raise_for_status() File "/usr/lib/python3/dist-packages/requests/models.py", line 940, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 500 Server Error: Internal Server Error for url: http+docker://localhost/v1.22/containers/c015b9d2a6e0ba06c8cc393147db2a4eb1a0fc72d1ae2805e177b409bb8212db/start During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/compose/service.py", line 625, in start_container container.start() File "/usr/lib/python3/dist-packages/compose/container.py", line 241, in start return self.client.start(self.id, **options) File "/usr/lib/python3/dist-packages/docker/utils/decorators.py", line 19, in wrapped return f(self, resource_id, *args, **kwargs) File "/usr/lib/python3/dist-packages/docker/api/container.py", line 1095, in start self._raise_for_status(res) File "/usr/lib/python3/dist-packages/docker/api/client.py", line 263, in _raise_for_status raise create_api_error_from_http_exception(e) File "/usr/lib/python3/dist-packages/docker/errors.py", line 31, in create_api_error_from_http_exception raise cls(e, response=response, explanation=explanation) docker.errors.APIError: 500 Server Error: Internal Server Error ("b'driver failed programming external connectivity on endpoint saleor-platform_db_1 (1b57cb27e18e4e18fad1fde3f6bebb573260974514be140c7e4e0d74d663b7b0): Error starting userland proxy: listen tcp4 0.0.0.0:5432: bind: address already in use'") During handling of the above exception, … -
Use django hitcount module without a class
In the model below, I want to count the number of times an object is retrieved with hitcount module. class Stats(models.Model, HitCountMixin): user = models.ForeignKey("User", null=True, blank=True, on_delete=models.CASCADE) count = models.PositiveIntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) hit_count_generic =GenericRelation(HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') I don't have any view function (class-based or function-based) that retrieves the objects. I only use get_or_create method to update or create the model object. So how can I use hit_count.hits_in_last to return the number of hits for today -
Which is the most commonly used way to implement user signup and login?
I'm starting out with Django development and I feel very confused and lost about all the ways you can implement the same thing. (or I may be just stupid) It all is very jumbled in my head right now (Class-based forms? Class-based views? Function-based views with Class-based forms? Custom HTML forms which are bound to Forms class and then etc etc etc...) So far these are all the intertwined options that I see and they confuse me a lot: Plain HTML forms which are then bound to the Form instance in views for validation (?). Every view is custom. (I like this one the best because I don't find any joy in using {{ form }} in templates, plus this one seem to be straightforward for me) Is forms.py not used when you implement forms that way? include('django.contrib.auth.urls') for login with custom templates (in which you when use {{ form }} and then something else for signup because there is no same built-in thing for signing up UserCreationForm but you have to extend it somehow if you want to add more fields (why are there built-in views for authentication but not for user creation btw?) Custom class-based forms if you … -
scanning qr code and display information in browser using django
I have a django web app where i have some qr code generator and now i want to create a view that can scan and open qr code in the browser.I have tried instacan but i didn't like it because i am not so good in javascript and i found this tutorial https://towardsdatascience.com/building-a-barcode-qr-code-reader-using-python-360e22dfb6e5 so my question is how can i use this tutorial to allow user to scan qr code from his device 2)open it in the browser (i mean the link) I will also appreciate any recommendation of other third app that can scan qr code.Thanks -
Django REST framework benchmarking [closed]
I want to know, how many requests can Django REST framework handle per second? And how much RAM does it use per session?