Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Model Override Only Works if I Save Twice
I have implemented a save override in my model so as to calculate a field using inputs from other models. In Admin, I have a TabularInline form. The problem is the code only works if I save my form twice. Here's my models.py class School(models.Model): name = models.CharField('school name',max_length=200) county = models.ForeignKey(County, null=True, on_delete=models.SET_NULL) location = models.DecimalField(blank=True, null=True, max_digits=9, decimal_places=6) score = models.DecimalField(blank=True, null=True, max_digits=5, decimal_places=2) def __str__(self): return'{}'.format(self.name) def calc_score(self): calculated_score = 0 for item in Marks.objects.filter(school=self.pk): for weight in Weights.objects.filter(year=item.year): new_score = item.marks*weight.weight calculated_score = calculated_score + new_score return calculated_score def save(self, *args, **kwargs): self.score=self.calc_score() super(School, self).save(*args, **kwargs) And my admin.py class MarksInline (admin.TabularInline): model = Marks @admin.register(School) class SchoolAdmin(admin.ModelAdmin): inlines = [ MarksInline, ] -
save default user in django admin save_model
class Post(models.Model): Tile= models.CharField(max_length=300, null=True,) description = models.CharField(max_length=300, null=True,blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) created_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) I am having this model in models.py file. I want to make created_by field automatically added to the database using request.user in the Django admin site I tried this code but nothing it sends def save_model(self, request, instance, form, change): user = request.user instance = formset.save(commit=False) if not change or not instance.created_by: instance.created_by = user instance.modified_by = user instance.save() print('yes') formset.save_m2m() return instance I think save_model is not working well as it doest this statement in it. I want to create this admin.py -
Python generate unique transaction reference number
I'm looking for a way to generate a unique payment reference number that is shorter than a 32-bit UUID. Ideally under 20 characters, all numbers. Needs to hide the total number of transactions and and be as human friendly as possible in case user has to enter it manually. Currently undecided between two options: shortuuid 22 characters, supposedly as unique as uuid4 Does not index well hashids over auto-increment id Apparently a 21 character long int doesn't exceed a 16 character long hashed string Uniqueness unknown Unable to reverse decode id so runs into same indexing issues as shortuuid If there are alternatives, I would love to hear. Thanks! -
Can't get attribute 'sanitization' on <module '__main__' from 'manage.py'>
This might look like a duplicate question as there are tons of similar questions on StackOverflow but all of them are totally different and none provide the perfect solution. I have a machine learning model that checks for malicious URLs. I am trying to implement this in Django where a user can input the URL and the Django HTML page can show the output. The standalone model is working absolutely file and displaying accurate results. I have saved the model using pickle as well so that it does not require to be trained again. the only problem I am getting is when I enter the input in the input field in Django. I receive the following error. Following are the files and code : malicious_url.py which is building 2 models in a pickle file. I have added both the models in my app directory including the dataset file. import pandas as pd import numpy as np import random import pickle from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import LogisticRegression def sanitization(web): web = web.lower() token = [] dot_token_slash = [] raw_slash = str(web).split('/') for i in raw_slash: raw1 = str(i).split('-') slash_token = [] for j in range(0,len(raw1)): … -
Why people don't answer questions [closed]
I have never got my question answered properly I don't know why. Someone please tell. Why people don't answer questions on stackoverflow. And would downvote questions a lot of time, just because they have few reputations. It sucks for beginners. Hate this. -
my Django form is not validating and storing informating in database
i have created a custom user model and using that model i have created sign up form. but whenever i click submit button ,form does not validate and don't store data in database. it just redirects me to home without storing data in database. but i can store data manually in database. models.py from django.db import models from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class SignUpManager(BaseUserManager): def create_user(self, email,age,name, username, password=None): if not email: raise ValueError("insert user") if not username: raise ValueError("insert username") if not name: raise ValueError("insert name") if not age: raise ValueError("insert age") user = self.model( email=self.normalize_email(email), username=username, age=age, name=name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email,name,age,username, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, age=age, name=name, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class UserSignupModel(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) age = models.CharField(max_length=15) name = models.CharField(max_length=15) username = models.CharField(max_length=15, unique=True) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = "username" REQUIRED_FIELDS = ['email','name','age'] objects = SignUpManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True #migrate --run-syncdb in … -
Error deploying Django, unable to configure static files
I tried deploying Django project to www.pythonanywhere.com, My website ran but could not load static files. I did collectstatic command in hosting server console but got error. my project file configuration as follows myproject # parent directory -DjangoApp1 # an app inside project -Myproject main file(includes manage.py etc) -DjangoApp2 # an app inside project -DjangoApp3 (in this app my static files located `DjangoApp3/static/DjangoApp3` ) in settings.py file STATIC_ROOT = os.path.join(BASE_DIR, "/static/") STATICFILES_DIRS = ('/DjangoApp3/static/DjangoApp3/',) STATIC_URL = '/static/' when I run collectstatic method in local machine ,below error occured FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\DjangoApp3\\static' -
How to add a value to an integer field via a form in Django?
I'm currently trying to make a form that adds the value to the"point" model that I created but it seems to not go through. I made a form that should allow the user to put any integer value and it should add (or subtract) to the model. Can anyone point me to the right direction on what to do? Any help is appreciated. Here is my forms.py: class addpointForm(forms.ModelForm): add_point_field = forms.IntegerField(widget=forms.NumberInput) class Meta: model = Points fields = ['user'] Model.py: class Points(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) points = models.IntegerField(default=0, null=False) def __str__(self): return self.user.username views.py: @login_required def pointform(request): if request.method=='POST': form = addpointForm(request.POST) if form.is_valid(): instance = form.save(commit=False) messages.success(request, 'Success! Points has been added!') instance.user.points += addpointForm.add_point_field form.save() else: messages.error(request, 'Oh no! There was an error when you were adding points!') form = addpointForm() return render (request,'users/addpoints.html',{'form':form}) -
How to view some objects from a django model into another model's CreateView and template
Hello every one I am trying to view two objects from a Model into another Model's CreateView and I need help to accomplish that (I am using Django v2.2.1). note: the two models are not related to each other Some samples of the code are bellow they may help. the first model is like: ... class First(models.Model): field(i) = models.SomeField(...) def get_absolute_url(self): return reverse("first_template", kwargs={"pk": self.pk}) The second model is like: ... class Second(models.Model): field(j) = models.SomeField(...) def get_absolute_url(self): return reverse("second_template", kwargs=None) It's form is like: ... class SecondForm(forms.ModelForm): class Meta: model = Second fields = ("field(1)", "field(2)",...) The view is like: ... class SecondView(CreateView): template_name = "second_template.html" form_class = forms.SecondForm model = models.Second -
Save model only to elasticsearch and not django db
I want to use django to make API calls to an external service and save the returned data to elasticsearch. For this I followed this https://django-elasticsearch-dsl.readthedocs.io/en/latest/quickstart.html tutorial. While my data is saved to elasticsearch, it is also saved to the sqlite db I'm using for other models (which I don't want to store in ES). How can I save the model only to ES and forgo the sqlite db? -
django null value in column "id" violates not-null constraint for new row
I am facing a problem where Django is trying to save new records with Null value in 'id' field. I was taking backup from server and it was incomplete due to connection issues. Since then whenever I try to save new data it shows 'django null value in column "id" violates not-null constraint' and the query shows it is trying to save Null value in 'id' field. It was working just fine before that and still works in local database. I restored the local database to server and it still shows the same error. None of my models include 'id' field, Django has created them automatically. Any idea why Django is trying to save with Null 'id' for every model? -
How to have a Django app running on Heroku doing a scheduled job using Heroku Scheduler
I am developing a Django app running on Heroku. In order to update my database with some data coming from a certain service, I need to periodically run a certain script (let's say myscript). How can I use Heroku Scheduler to do it? -
How do I make the user edit/update the .py file in Django?
I am working on a Django Project, and I want the User to be able to add the code in the .py file. Well, I have .py file that contains some code, and in the mid of code I have some lines of code that specify some rules for Fuzzy Logic Algorithm, such as below: #some code #again some code # # rule1 = scikit-fuzzy.control.Rule(input1["bad"] & input2["bad"] & input3["bad"] & input4["bad"] & input5["average"], output["poor"]) #some code #again some code # # So, I have total 243 lines of codes (in other words rules) like the above centered between some code (that is above it and below it there some other code). Now, I want Admin to be able to edit and update these lines of codes in a way that, using Forms I will take the inputs from the Admin (such as: 'good', 'bad', 'average', 'bad', 'good', 'poor', and I want the system to create a new line of code taking these strings as inputs. If admin enters: 'good', 'bad', 'average', 'bad', 'good', 'poor', I want the .py to have a new line after the 243rd line which should be like this: rule243 = # rule244 = rule1 = scikit-fuzzy.control.Rule(input1["good"] … -
Django: is it possible to have model's FK linked to through model's PK to have one-to-many relationship?
I will have 2 models (Project and User) linked with a many-to-many relationship. Django will create implicit through model with id, and the 2 FK (Project and User). Is it possible to have a third models Application linked to the through model? Can I declare a FK in Application that is linked to the through model id? -
No matching distribution found for torch==1.5.0+cpu on Heroku
I am trying to deploy my Django app which uses a machine learning model. And the machine learning model requires pytorch to execute. When i am trying to deploy it is giving me this error ERROR: Could not find a version that satisfies the requirement torch==1.5.0+cpu (from -r /tmp/build_4518392d43f43bc52f067241a9661c92/requirements.txt (line 23)) (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2, 0.4.1, 0.4.1.post2, 1.0.0, 1.0.1, 1.0.1.post2, 1.1.0, 1.2.0, 1.3.0, 1.3.1, 1.4.0, 1.5.0) ERROR: No matching distribution found for torch==1.5.0+cpu (from -r /tmp/build_4518392d43f43bc52f067241a9661c92/requirements.txt (line 23)) ! Push rejected, failed to compile Python app. ! Push failed My requirements.txt is asgiref==3.2.7 certifi==2020.4.5.1 chardet==3.0.4 cycler==0.10.0 dj-database-url==0.5.0 Django==3.0.6 django-heroku==0.3.1 future==0.18.2 gunicorn==20.0.4 idna==2.9 imageio==2.8.0 kiwisolver==1.2.0 matplotlib==3.2.1 numpy==1.18.4 Pillow==7.1.2 psycopg2==2.8.5 pyparsing==2.4.7 python-dateutil==2.8.1 pytz==2020.1 requests==2.23.0 six==1.14.0 sqlparse==0.3.1 torch==1.5.0+cpu torchvision==0.6.0+cpu urllib3==1.25.9 whitenoise==5.0.1 And runtime.txt is python-3.7.5 However installing it on my computer is not giving any type of error when i use command pip install torch==1.5.0+cpu I am using python 3.7.5 and pip 20.0.2. Complete code is here. How to solve this issue i really need to deploy my app. Thanks -
The view diabetes.views.signupuser didn't return an HttpResponse object. It returned None instead
i am trying to submit the signup form using custom user model. whenever I try to submit the form it suppose to redirect to home page. but it gives error. my forms is good. problems occur both for render or redirect. my views.py from django.shortcuts import render,redirect from django.contrib.auth import login,authenticate from diabetes.forms import UserSignupForm # Create your views here. def home(request): return render(request,'diabetes/home.html') def signupuser(request): if request.method=='POST': form=UserSignupForm(request.POST) if form.is_valid(): form.save() email=form.cleaned_data.get('email') raw_password=form.cleaned_data.get('password1') account=authenticate(email=email,password=raw_password) login(request,account) return redirect('home') else: pass else: form = UserSignupForm() return render(request,'diabetes/signupuser.html',{'form':form}) my urls.py """diabetes_project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from diabetes import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.home,name="home"), path('signupuser/',views.signupuser,name="signupuser"), ] -
edit uploaded file (while in POST method) and save it (django)
i want to make a site for uploading and processing of xray images. usually most xray files are dicom which at the end of the day is an image. i can already save normal images. i wanted to convert dicom to png then replace the uploaded dicom with that before actually saving it to media dir (mostly to avoid IO interaction and only keep dicom in memory till converted) . so i thought i have to run the convert function in POST, and edit request.FILES. but i fail, and don't know what to do anymore. any way that could get the job done with speed should be adequate. The model: class ImagePatient(models.Model): image_imag = models.ImageField(upload_to='') ... The View: class ImageAddView(LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, CreateView): model = ImagePatient fields = ['image_imag'] success_message = "image added" template_name = 'patient/image_add.html' def post(self, request, *args, **kwargs): if request.FILES['image_imag'].name.endswith('.dcm'): png_bytes=overrideTempDicom(request.FILES['image_imag']) # what to do, what not to do return super().post(request, *args, **kwargs) ... The dicom to png converter (returns an io.BytesIO): def overrideTempDicom(image_data): import numpy as np import png import pydicom import io # ************* ds = pydicom.dcmread(image_data.file) shape = ds.pixel_array.shape # Convert to float to avoid overflow or underflow losses. image_2d = ds.pixel_array.astype(float) # Rescaling … -
What is the best way to write to a log file when an exception is raised in Django?
What is the best way to write to a log file when any exception occurs within the Django app without hardcoding to each function in the view? E.g. when DatabaseError,ValueError,Integrity error are raised in the views. import logging logger = logging.getLogger(__name__) def my_view(request, arg1, arg): ... if bad_mojo: # Log an error message logger.error('Something went wrong!') -
What is a good way to show one-time announcements to users on a webpage?
I have made a Django app and it was a basic to-do list app. I didn't work on that for like 3 weeks and later noticed that the app had some security vulnerabilities and I also had some major new feature ideas in my mind. Since then I have been working on the 2.0 version of this app with much more features and new design. Now, my app supports multiple users. So, what I want to do is when those users will login for the FIRST TIME to the 2.0 version of this app, I want to show them an announcement box (think of Bootstrap Modals for a better idea) which would inform them all of the new features and changes. This box could take up about 70% of the screen and the background would be dimmed. So, my question was what could I use to achieve this? Will Bootstrap be a good solution? But how do I make it one-time? Also, I wish to show images on the content and there should be arrow buttons to switch between different content boxes, like what a typical website would do. Thanks for any suggestions. Update: My main focus is what library … -
Celery Best Practice For one Task Kicking off Many Small tasks
I have a novice level of experience with celery. I have written many tasks both scheduled and one off delayed jobs, but that is it. I am running into an issue where I want to create one task that kicks off 1000s of smaller jobs to mitigate any issues that could arise with queue length and a job the could take hours to complete. The current application relies on information from external APIs. So to speak a user links their account with another service I have integrated, and I want to update the user's information daily with changes on their external account. I have a scheduled job like this @app.task() def refresh_accounts(): for account in Account.objects.all(): response = retrieve_account_info(account_id=account.id) account.data = response.data account.save() -- What I desire is something like this @app.task() def kickoff_refresh(): for account in Account.objects.all() refresh_account.delay(account_id=account.id) @app.task() def refresh_account(account_id=None): account = Account.objects.get(id=account_id) response = retrieve_account_info(account_id=account.id) account.data = response.data account.save() one approach I was thinking of was having kickoff_refresh and refresh_account in different queues. @app.task(queue=q1), @app.task(queue=q2)... I, however, do not know if there is a better way of doing this. Calling a task inside a task on the same queue seems to be bad practice in celery - … -
How can I do division of these fields and aggregate
class Worker(models.Model): name = models.CharField(max_length=180, blank=True, null=True) def __str__(self): return str(self.name) class WorkDone(models.Model): worker = models.ManyToManyField(Worker, related_name='workers') work_title = models.CharField(max_length=180, blank=True, null=True) units = models.IntegerField(blank=True, null=True) def __str__(self): return str(self.work_title) views context['workers'] = Worker.objects.all() \ .values('name', 'workers__work_title')\ .order_by('name') \ .annotate(total_work=( Sum('workers__units')/Count('name')) ) print(context['workers']) print output <QuerySet [{'name': 'dinesh', 'workers__work_title': 'first', 'total_work': 4}, {'name': 'ramesh', 'workers__work_title': 'first', 'total_work': 4}]> instead of 4 it should be 2 as the total unit is 4 and no. of worker is 2 -
E-Mail report sending with Django
I'm working with a Django project using Python 3.8.2 and I need to send emails every day (they contain a simple csv file with some data). I wanted to use Celery, but it doesn't support my python version and downgrading isn't really possible at the moment. Is there any other practical way to do this? Let me know if I'm not being specific enough or the question is badly formulated. Thanks in advance! -
Django 3: how do I save a semi-unique value during creation of an object?
I'm working on a small project for my running club. We want to be able to have our own events where a user can sign up, choose an event and distance and have a bib number created. In my participant model I have a unique_together binding between an event_id (foreign key), and the bib number. The bib number is only unique to a specific event. So the bib number 1001 could be used for several events, but only once per event How do I during creation of a model instance find the next unused bib number for a given event? Override the save() method in participant, use signals (and how?) or use default=callable_method or something completely different? My models are: class Event(models.Model): event_name = models.CharField(max_length=256, unique=True) event_max_participants = models.PositiveSmallIntegerField(validators=[MaxValueValidator(1000)]) def __str__(self): return self.event_name class EventDistance(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) event_distance = models.FloatField() class Meta: unique_together = ['event', 'event_distance'] def __str__(self): return str(self.event_distance) class Participant(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) event_distance = models.ForeignKey(EventDistance, on_delete=models.CASCADE) # CustomUser participant_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) participant_bibnumber = models.SmallIntegerField(blank=True, editable=False) class Meta: unique_together = [['event', 'participant_user'], ['event', 'participant_bibnumber']] def __str__(self): return f'{self.deltager_user.name}' -
passing a variable into url to query DB
in my url I want to pass a key and query the DB on that View, based on that key : #url.py path('view/<slug:secret_key>/',DetailMessage.as_view(),name='message'), view.py class DetailMessage(generic.DetailView): model = Message template_name = 'msg/view.html' def get_queryset(self): queryset = super().get_queryset() key =self.request.get('secret_key',None) return queryset.get(secret_key=key) But I receive this error : WSGIRequest' object has no attribute 'get' -
Is there to set default fields in Django?
I would like to add an 'is_active' boolean, created_datetime and created_by fields to every model that I create. Is there a way for me to let migrations handle that? Basically adding to the existing addition of the Id field.