Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How i can define the environment variable in DJANGO_SETTINGS_MODULE?
settings.py That's my setting.py the site is not published so that's why is not published so the secret key don't matter here. At the beginning i'm trying to receive some request in Ajax from Django import django django.setup() import os from django.conf import settings # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "f6-6p&w%mxjh6dnk7n$i9ik$w-5@x*_2-!omr8)qhr)&rqbn&2" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mysite' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' 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', '' ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = … -
Django: how to perform and display calculations on inputs obtained from a form post?
I have successfuly created a complex form with a lot of fields using ModelForm and FormView. I managed to save those data and display it in the admin. Thus it is only the beginning of what I want to do. My next goal is to use the inputs posted by the user via the form to perform calculations on it and then display the results of those calculations in another view. What would be the best approach to do so? So far here are my files (I do not display all the fields since it is not relevant) Here is the view I use to display the form class SimulInputView(FormView): form_class = SimulInputForm template_name = 'apps/simulateur/formulaire/form.html' success_url = reverse_lazy('simulateur_results') def get_initial(self): initial_data = super(SimulInputView, self).get_initial() for key, value in dict_simul_form_default_data.items(): initial_data[key] = value return initial_data def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context['data'] = SimulateurData return context def form_valid(self, form): form.instance.user = self.request.user form.save() return super().form_valid(form) How should I modify my form_valid function to use another module which would perform calculations on the form data received before displaying them in another view? -
Django Serving XLSX file for download via HttpResponse
I'm having an issue serving a xlsx file via django api. I am able to download the file, but trying to open it leads to an error saying it is corrupted. I can open the file locally just cannot download it an open. response = HttpResponse(open(path, 'rb').read()) response['Content-Type'] = 'vnd.openxmlformats-officedocument.spreadsheetml.sheet' response['Content-Disposition'] = 'attachment; filename=DownloadedEval.xlsx' return response -
What is ready() function in UsersConfig() function?
I have trouble understanding this code from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals Some signals are imported in ready function but what is ready(self) function doing here? and name variable stated within is a built-in keyword? I have studied the documentation I didn't grasp anything. Please explain what is the meaning of this Subclasses can override this method to perform initialization tasks such as registering signals. It is called as soon as the registry is fully populated. Although you can’t import models at the module-level where AppConfig classes are defined, you can import them in ready(), using either an import statement or get_model(). and please explain it in simple words. Thank you -
Editing a django login form
I want to add 2FA to my django app. I found this library but there is some thing i am not understanding. On their example django app they are using the module's login view, it means that the example app does not have its own view, so how do i integrate the 2fa module into my own app? I already have my own login view, but i don't know how to integrate the 2fa with my own view. Or do i need to just use the 2fa module's view? If this is the correct way, can someone please explain me how to edit the login form? If i am calling the module's view, that means i cannot edit it, since it's in the site-packages. Any advice is welcome this is what my login views looks like: def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}") return redirect("example:home") else: messages.error(request, "Invalid username or password") else: messages.error(request, "Invalid username or password") -
How to load a csv file from static in django into javascript function
I Have a javascript function in static/js and i want to get the data from a csv file available in static/csv. My javascript code: function graph1(){ d3.csv('{% static 'csv/data2.csv' %}', function(error, data) { } } -
Validate that dates are the same and the end time is greater than the start time
I am trying to perform validations on my form inputs which only allow a start datetime and end datetime if both the dates equal each other, and if the time of end datetime is greater than the s tartdatetime. This is to prevent something like 2019-05-04 10:00 am as the start datetime, and 2019-05-05 10:00 am as the end datetime being created. The issue is the validation is not working and every input is passing, I am not sure what is causing this and would appreciate any help. def clean(self): cleaned_data = super().clean() lesson_datetime_start = self.cleaned_data.get("lesson_datetime_start") lesson_datetime_end = self.cleaned_data.get("lesson_datetime_end") if lesson_datetime_start >= lesson_datetime_end and lesson_datetime_start.date() != lesson_datetime_end.date(): raise ValidationError('Dates have to be the same and end time must be later than start time') return cleaned_data -
Autofill column value by update model in Django 2.1
I have this easy model: class Ranking(model.Model): athlete = model.ForeignKey(Athlete, on_delete=models.CASCADE) vote_judge_1 = models.FloatField(default=0) vote_judge_2 = models.FloatField(default=0) vote_judge_3 = models.FloatField(default=0) final_rank = ??? Now, what the best way to auto fill final_rank, with an easy arithmetic average every time the judges update or save their vote? -
Using Django's pre_delete signal for new object creation
When a Tasks instance is deleted i want to create a new Instance of Completed Tasks, which stores the deleted task. Here is my code - from django.db import models from django.db.models.signals import post_delete, pre_delete from django.urls import reverse, reverse_lazy from django.contrib.auth.models import User class Tasks(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) TaskName = models.CharField(max_length=100) Description = models.CharField(max_length=400) DueDate = models.DateField(help_text="YYYY-MM-DD") priority = models.IntegerField() def __str__(self): return self.TaskName def get_absolute_url(self): return reverse('tasks:detail', kwargs={'pk': self.pk}) pre_delete.connect(lambda instance,**kwargs:CompletedTasks.obbjects.create(task = instance)) class CompletedTasks(models.Model): task = models.ForeignKey(Tasks, on_delete=None) But , it is not working , instances of CompletedTasks are not being created. -
How do I delete one specific M2M relation between 2 Models?
I have the following models: class Contact(models.Model): name = models.CharField(max_length=100) class Item(models.Model): name = models.CharField(max_length=100) contacts = models.ManyToManyField(Tag, blank=True) How do I delete one specific M2M relation between them(not clear all of them), having access to both instances of Contact and Item involved ? -
django rest framework update user
I'm working on django application with django rest framework. I create a User API with model extending AbstractUser and it's serializers and ModelViewSet to create a CRUD. Everything works fine except for update. If I try to update directly I lose the password encrypt, but If I try to surround update with my own, it says password is required and username already exists. How can I update User with those components? models.py class User(AbstractUser): institution = models.ForeignKey(Institution, on_delete=None, null=True, blank=True) class Meta: db_table = 'User' managed = True verbose_name = 'Users' verbose_name_plural = 'Users' ordering = ['id'] def __str__(self): return self.email serializers.py class UserSerializer(serializers.ModelSerializer): institution_name = serializers.ReadOnlyField(source='institution.name') def create(self, validated_data): return User.objects.create_user(**validated_data) def update(self, instance, validated_data): return User.objects.update(**validated_data) class Meta: model = User fields = ( 'id', 'username', 'first_name', 'last_name', 'email', 'password', 'is_active', 'institution', 'institution_name' ) datatables_always_serialize = ( 'id', 'username', 'first_name', 'last_name', 'email', 'is_active', 'institution', 'institution_name' views.py class UserViewSet(ModelViewSet): serializer_class = UserSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): identification = self.request.query_params.get('pk', None) if identification is not None: self.pagination_class = None return User.objects.filter(pk=identification) return User.objects.select_related().order_by('id') def get_permissions(self): if self.action in ('create',): self.permission_classes = [AllowAny, ] return super(self.__class__, self).get_permissions() def create(self, request, *args, **kwargs): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.create(serializer.validated_data) return Response(serializer.data) … -
why instance.profile.save() Django Python
I have some trouble understanding this code. from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() The question is why do we need to execute instance.profile.save() here however, post_save signal is a proof that the user is already saved and a profile associated that user is already created. Please help me understand it! thanks edit: in instance.profile.save() is profile a built-in keyword -
Django: filtering queryset by date doesn´t apply any filter at all
I´m trying to filter a queryset by the dates. First I group the data by dates and have no problem. inventario_original = Inventario.objects.all() inventario = inventario_original.values("fecha").annotate( valor_coste=Sum(F('existencias') * F('valor_coste')), valor_venta=Sum(F('existencias') * F('valor_venta')), existencias=Sum('existencias')) Then i find the last date in the queryset. ultima_fecha_cargada = inventario_original.order_by('-fecha') ultima_fecha_cargada = ultima_fecha_cargada.first().values('fecha') If I print ultima_fecha_cargada.fecha I get ['15-03-2019'] Finaly I want to filter the queryset with items with that last date. inventario_producto = inventario_original.filter(fecha__date=ultima_fecha_cargada.fecha).values("codigo_kinemed").annotate(existencias=Sum('existencias')) I get the full queryset with no filter applied. If I print the resulting dates I get ['15-03-2019']so the date format matches. Also tried filter(fecha=ultima_fecha_cargada.fecha) filter(fecha=ultima_fecha_cargada) filter(fecha=date(day=15, month=3, year=2019)) filter(fecha__contains=ultima_fecha_cargada.fecha) filter(fecha__contains=date(day=15, month=3, year=2019) -
Assert big JSON responses in DRF uni testing
What is the best strategy when trying to validate big JSON responses inside DRF unit tests? For example: class MyUnitTest(APITestCase): def some_unit_test(self): response = self.client.get(reverse('url'), data, format='json') This method can return a big response with varying data inside it which I would like to verify. Should I just 'hardcode' the expected response for each method call? Or there is a more 'smart' way of generating the expected response and doing this assertion? Thanks! -
Django AbstractUser authentication
We're trying to create an app for university events, where you have two types of users - Society and Student. Their differences - Society can create/edit events, Students can book or bookmark events. Both Society and Student have the same view of homepage, pages of other events etc. While registering, Society has one extra field - logo. Everything works well apart one thing - authentication. After registering, if you try to login with the same credentials, it doesn't find the user. If I check the admin page, the Users are not under 'Authentication and authorization' section, which, I think, is what is causing the problem. Are there any fixes to this issue? Many thanks in advance. In models.py: class UserProfile(AbstractUser): is_user = models.BooleanField('student status', default=False) is_society = models.BooleanField('society status', default=False) class Society(models.Model): user = models.OneToOneField(UserProfile, on_delete=models.CASCADE, related_name='society_user', default = 'null') logo = models.ImageField(upload_to='logos') def __str__(self): return self.user.username In forms.py: class StudentForm(UserCreationForm): class Meta: model = UserProfile fields = ('username', 'password1', 'password2', 'email') def clean_email(self): email = self.cleaned_data.get('email', None) if UserProfile.objects.filter(email=email): raise forms.ValidationError('That email is already in registered!') return email def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if not self.validate_password_strength(): raise forms.ValidationError('Password must contain at least 1 digit and letter.') … -
Python Django: "Reverse for 'Contact' not found"
Environment: Request Method: GET Request URL: http://127.0.0.1:8000/logout/ Django Version: 2.1.7 Python Version: 3.7.2 Installed Applications: ['blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\Rahul Kochar\Desktop\zoomDjango\blog\templates\blog\base.html, error at line 0 Reverse for 'contact' not found. 'contact' is not a valid view function or pattern name. 1 : {% load static %} 2 : 3 : <!DOCTYPE html> 4 : <html lang="en"> 5 : <head> 6 : <meta charset="UTF-8"> 7 : <meta name="viewport" content="width=device-width, initial-scale=1.0"> 8 : <meta http-equiv="X-UA-Compatible" content="ie=edge"> 9 : <link rel="stylesheet" type="text/css" href="{% static 'blog/style.css' %}"> 10 : {% if title %} Traceback: File "C:\Python37\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response 156. response = self.process_exception_by_middleware(e, request) File "C:\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response 154. response = response.render() File "C:\Python37\lib\site-packages\django\template\response.py" in render 106. self.content = self.rendered_content File "C:\Python37\lib\site-packages\django\template\response.py" in rendered_content 83. content = template.render(context, self._request) File "C:\Python37\lib\site-packages\django\template\backends\django.py" in render 61. return self.template.render(context) File "C:\Python37\lib\site-packages\django\template\base.py" in render 171. return self._render(context) File "C:\Python37\lib\site-packages\django\template\base.py" in _render 163. return self.nodelist.render(context) File "C:\Python37\lib\site-packages\django\template\base.py" in render 937. bit = node.render_annotated(context) File "C:\Python37\lib\site-packages\django\template\base.py" in render_annotated 904. return self.render(context) File "C:\Python37\lib\site-packages\django\template\loader_tags.py" in render 150. return compiled_parent._render(context) File "C:\Python37\lib\site-packages\django\template\base.py" in _render 163. return self.nodelist.render(context) … -
Deleting objects once current date passes their set date
I have lesson objects that have a lesson_datetime_end to them which olds their date and time. I am trying to create a command that checks if the current date is greater than lesson_datetime_end, and if so deletes them. I also want the command to run at consistent intervals (every 5 or 10 mins). My custom management command is for some reason not working, and I would appreciate any help in figuring out what the issue is. from django.core.management.base import NoArgsCommand class Command(NoArgsCommand): help = 'Expires old lesson objects' def handle_noargs(self): if datetime.now() > lesson.lesson_datetime_end: Lesson.objects.filter(date__lt=datetime.datetime.now()).delete() -
How to re-save a dictionary key with multiple values in python?
{ "캡틴마블": ["20018348", "81533"], "이스케이프룸": ["20018925", "81654"], "돈": ["20018920", "81651"], "라스트미션": ["20018934", "81658"], "우상": ["20018907", "81650"], } I have fetched movie data and saved the data as shown above (as a dictionary). I want to save them to my Django project, but the code below is not working for me. if __name__=='__main__': movie_data_dict = data #like above format Json file for t, m in movie_data_dict.items(): MovieData(title=t, movie_cd=m[0], movie_idx=m[1]).save() class MovieData(models.Model): title = models.CharField(max_length=20) movie_cd = models.IntegerField(max_length=20) movie_idx = models.IntegerField(max_length=20) Output -
django-storages generates incorrect urls to assets in S3
I'm experiencing a problem where the URLs to assets stored on a Europe/London S3 bucket are not being generated correctly. For example: https://s3.amazonaws.com/mybucket/static/wagtailadmin/css/normalize.css Resulting in such errors in the browser: Cross-Origin Read Blocking (CORB) blocked cross-origin response with MIME type application/xml. See for more details. and when you try to access the url: <?xml version="1.0" encoding="UTF-8"?> <Error> <Code>PermanentRedirect</Code> <Message>The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.</Message> <Endpoint>mybucket.s3.amazonaws.com</Endpoint> <Bucket>mybucket</Bucket> <RequestId>4ER2572A129386F7</RequestId> <HostId>+l38ZBh/hDscROXzeWdNfldQtcQm1ZPVq4sNZAZKQKwGHLv7MDRW4H0sf0I3pijD1T0j4oSE6E=</HostId> </Error> The correct url to the file would be https://mybucket.s3.amazonaws.com/static/wagtailadmin/css/normalize.css. My project uses vanilla settings generated by django-cookiecutter: # STORAGES # ------------------------------------------------------------------------------ INSTALLED_APPS += ['storages'] # noqa F405 AWS_ACCESS_KEY_ID = env('DJANGO_AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = env('DJANGO_AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = env('DJANGO_AWS_STORAGE_BUCKET_NAME') AWS_QUERYSTRING_AUTH = False _AWS_EXPIRY = 60 * 60 * 24 * 7 AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': f'max-age={_AWS_EXPIRY}, s-maxage={_AWS_EXPIRY}, must-revalidate', } AWS_DEFAULT_ACL = 'public-read' # TODO - not sure if this is ideal # STATIC # ------------------------ STATICFILES_STORAGE = 'config.settings.production.StaticRootS3Boto3Storage' STATIC_URL = f'https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com/static/' # MEDIA # ------------------------------------------------------------------------------ from storages.backends.s3boto3 import S3Boto3Storage # noqa E402 class StaticRootS3Boto3Storage(S3Boto3Storage): location = 'static' class MediaRootS3Boto3Storage(S3Boto3Storage): location = 'media' file_overwrite = False DEFAULT_FILE_STORAGE = 'config.settings.production.MediaRootS3Boto3Storage' MEDIA_URL = f'https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com/media/' -
django handling request and scheduling code
def index(request): this function take request from extension and scrape the link provided in post request def job(): take link from database scrap it and again store in database this function is called by schedluler I want to do the both task at the same time problem :- when i start django server it goes infinite loop and computer scheduler part and not able to handle post request -
Django 2.1 Create automatically models in db
I have 2 models : class Solo(models.Model): id = models.PositiveIntegerField(primary_key=True) atleta = models.ForeignKey(Atleta, on_delete=models.CASCADE) categoria = models.ForeignKey(Categoria, on_delete=models.CASCADE) tipo = models.PositiveIntegerField(null=True, blank=True) valida = models.PositiveIntegerField(null=True, blank=True) societa = models.ForeignKey(Societa, on_delete=models.CASCADE) gara = models.ForeignKey(Evento, on_delete=models.CASCADE) path = models.CharField(max_length=150) and class VotazioniSolo(models.Model): solo = models.OneToOneField(Solo, on_delete=models.CASCADE) voto_1 = models.FloatField(default=0) voto_2 = models.FloatField(default=0) voto_3 = models.FloatField(default=0) voto_4 = models.FloatField(default=0) voto_5 = models.FloatField(default=0) voto_6 = models.FloatField(default=0) voto_7 = models.FloatField(default=0) voto_8 = models.FloatField(default=0) voto_9 = models.FloatField(default=0) voto_10 = models.FloatField(default=0) voto_11 = models.FloatField(default=0) voto_12 = models.FloatField(default=0) voto_13 = models.FloatField(default=0) voto_14 = models.FloatField(default=0) voto_15 = models.FloatField(default=0) Inside the table of db, I have a lot of Solo objects and I need Django create for me every Object VotazioniSolo for every Solo existing. And if I create an other object Solo, automatically Django create the respective VotazioneSolo object with default values. -
WYSIWYG editor for templates
I'm looking for a wysiwyg editor for the front end of my django powered website (i.e. my html templates). Using the wysiwyg editor, users needs to be able to: create bullet points create bold text change font size Given these requirements, what WYSIWYG editor package would you recommend? Also, I was looking at django-summernote. With this package, it looks like there is a requirement to mark content as safe when displaying that content in templates. {{ foobar|safe }} Do all wysiwyg editors require this? Does this represent a security concern? Could an end user insert malicious code into the textbox and then have it executed when the page is rendered? My end users are random people on the internet. Thanks all! -
Djanog getter on model field
I'm using Django 2.x I have a model like class MyModel(models.Model): name = models.CharField() balance = models.IntegerField() I want to change the value of balance on the GET request without changing the value in the database. Like if it could be @Property field, the model will look like class MyModel(models.Model): name = models.CharField() balance = models.IntegerField() @property def balance(self): if balance: return balance return 0.15 * 50 But redeclaration is not allowed. How can I solve this issue? Note: Field should be compatible with ModelAdmin and DRF Serializer -
Web based project on Data Visualization with Python(Django)
I want to create a web based project on Data Visualization with Python(Django), so which python library should I prefer such as dash, bookeh or similar one? I want some opinions from experts thanks in advance... -
Django - aggregation zero
I've got the following in my views.py : called = CashFlow.objects.filter(item__slug=itemslug).filter(type='cashin').aggregate(sum=Sum('amount'))['sum'] distributed = CashFlow.objects.filter(item__slug=itemslug).filter(type='cashout').aggregate(sum=Sum('amount'))['sum'] try: result = round(-distributed/called * 100,2) except ZeroDivisionError : result = 0 Everything works fine as long as one of the queries return something. but, let's say there haven't been any cashouts so far -> the result should be zero. However, I receive the following Typerror : "bad operand type for unary -: 'NoneType'" How can I solve this? many thanks in advance