Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Complex Django search engine
I want my Django search engine to be able to handle typos on the title of the item I display. For example if the user does the search 'stacoverflow' I would search for 'stackoverflow'. I would then apply other filters I already have and could display the results. What would be the best way to do this and how could I do it? Consider some specific strings and then change their values, how? -
Refactor Business Logic From View To Model
I've got a django view with a small amount of business logic in it. However it would be useful to use this information elsewhere so it feels like something that I could put into a model however I'm not entirely sure how to go about doing this. Mainly because I need specific user data. This is what I have so far: views.py def create_budget(self, context): starting_point = BudgetStartingPoint.objects.filter(owner=self.request.user) running_tally = starting_point[0].starting_amount budget_dict = {} for transaction in self.get_queryset(): if transaction.income_type == "IN": running_tally += transaction.transaction_amount else: running_tally -= transaction.transaction_amount budget_dict[transaction] = [running_tally, transaction.income_type] context['budget'] = budget_dict models.py class BudgetTransaction(models.Model): """ Individual transaction for Budget """ transaction_types = [ ('fixed', 'Fixed'), ('extra', 'Extra'), ] income_types = [ ("IN", "Income"), ("OUT", "Expense"), ] frequencies = [ ('weeks', 'Weekly'), ('fort', 'Fortnightly'), ('4week', 'Four Weeks'), ('months', 'Monthly'), ('years', 'Yearly'), ] today = datetime.today().date() id = HashidAutoField( primary_key=True, salt=f"transaction{settings.HASHID_FIELD_SALT}" ) owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, help_text="Owner of the item" ) category = models.ForeignKey(BudgetCategory, on_delete=models.CASCADE, default=1, null=True) transaction_type = models.CharField(max_length=40, choices=transaction_types, default=1) transaction_name = models.CharField(max_length=100, null=False) transaction_amount = models.FloatField(null=False, default=100) income_type = models.CharField(max_length=20, choices=income_types, default="IN") next_date = models.DateField(null=False, default=today) frequency = models.CharField(max_length=20, choices=frequencies, default=1) complete = models.BooleanField(default=False) def __str__(self): return self.transaction_name class Meta: ordering = ['next_date'] … -
JsonField in DRF
I have a model like below that include JsonField: class Animal(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_field=15) data = models.JSONField() the data field structure is like below: [ { "age":"15", "color":white, ... }, { ... ... } ] And my goal is to show this model in DRF like below: [ { "id": 1, "name": "Bell", "data": [ { "age":"15", "color":"white", ... }, { ..., ... } ] } ] But when i use JsonFeild in my model my data generated liKe: [ { "id": 1, "name": "Bell", "data": "[{\"age\":\"15\",\"color\":\"white\",...},{\...,|... }]" } ] It's converted to string and have \ in characters. My serializer: class AnimalSerializer(serializers.ModelSerializer): class Meta: model = Animal fields = "__all__" -
Django/ AUTH_USER_MODEL refers to model 'home.******' that has not been installed
I checked all the answers but could not achieve a result after trying everything. I wanted to create model with AbstractUser in the home app which I was already using not created for only this purpose .After creating the class (mentioned as *****) I created AUTH_USER_MODEL = 'home.*******' in settings file and also created the 'home.apps.HomeConfig', in Installed Apps part. But still getting the error. What should I do? I would also like to ask which might be connected to my problem. I may not created the home app while in virtual env is it causes a problem in anyway? Thank you for your answer. Im new at django please dont judge and if the question is not appopriate please guide me. -
Django Assign Different ForeignKeys to Different Forms in a Formset
Summary I need to figure out how can I process a formset in a view in a way where instances of the formset can be assigned different foreign keys. Design Requirement #1 I am working with a design requirement where the user should click a button to add a PollQuestion form to the site. The button can be clicked multiple times to add multiple PollQuestion forms, and on submit, the view will handle creating PollQuestion instances that are related to the same Poll object via foreign key. Implementation I am currently using a modelfactory_formset and DOM manipulation with JavaScript to dynamically append PollQuestion forms to the DOM, and on submit are processed in the view as a formset. This is working fine. Design Requirement 2 Design also wants the ability to dynamically add PollOption forms to the PollQuestion form with an HTML button. One submit button will send the data from both PollQuestion and PollOption forms to the view for processing. Implementation Again I am using a dynamic formset modelfactory_formset for the PollOption forms. An "Add Option" button appends a PollOption form to the DOM. This works fine if I have just one PollQuestion. Problem But if I have more … -
How to insert data and update data in One to One Relation in DRF and React Js
I have two models User and Profile which is related by One to One relation. I have registered users who can login and if profile is not created for user, then user can create one profile (using POST) and if profile is created then user can update their profile (using PATCH). Models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='profile') locality = models.CharField(max_length=70, null=True, blank=True) city = models.CharField(max_length=70, null=True, blank=True) address = models.TextField(max_length=300, null=True, blank=True) pin = models.IntegerField(null=True, blank=True) state = models.CharField(max_length=70, null=True, blank=True) profile_image = models.ImageField(upload_to='user_profile_image', blank=True, null=True) Serializer.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model= Profile fields = ['user', 'locality','city','address','pin','state','profile_image'] Views.py class UserProfileDataView(APIView): renderer_classes = [UserRenderer] permission_classes = [IsAuthenticated] def get(self, request, format=None): serializer = ProfileSerializer(request.user.profile, context={'request': request}) return Response(serializer.data, status=status.HTTP_200_OK) def post(self, request, format=None): serializer = ProfileSerializer(data= request.data, context={'user': request.user}) serializer.is_valid(raise_exception=True) serializer.save() return Response ({ 'msg':'Data Updated Successfully'},status=status.HTTP_201_CREATED ) def patch(self, request, format=None): item = Profile.objects.get(user = request.user) serializer = ProfileSerializer(item ,data = request.data, partial=True, context={'user': request.user.profile}) serializer.is_valid(raise_exception=True) serializer.save() return Response({'msg':'Profile Updated Successfull'}, status = status.HTTP_200_OK) API using Redux Toolkit editProfile: builder.mutation({ query: (access_token, actualData ) => { return { url:'editprofile/', method:'PATCH', body:actualData, headers:{'authorization' : `Bearer ${access_token}`, 'Content-type':'application/json'} } } }), createProfile: builder.mutation({ query: (access_token, actualData ) => { … -
Session Authentication for Delete Request with Django Rest Framework
I am trying to modify a Django application to use the Django Rest Framework (DRF). I can get everything to work fine with the exception of the authentication mechanism. To illustrate, consider the following function in views.py which deletes one entry from the database: @api_view(['DELETE']) def api_delete_cert(request, cert_name): .... # delete certificate cert_name from database The entry in url.py for this function is: path('<str:cert_name>/api_delete_cert', views.api_delete_cert, name='api_delete_cert'), During testing, I access this function from the client side using curl with a command like: curl -i -X "DELETE" http://localhost:8000/editor/abcd/api_delete_cert This works fine but, of course, there is no authentication mechanism. I would like to use Session Authentication whereby the client logs in and then saves the session ID locally (in a cookie) and then sends it to the server with each subsequent request. For this purpose, I have extended my views.py to have a login function: @api_view(['POST']) def api_login(request): if ('username' in request.POST) and ('password' in request.POST): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Save user's ID in the session return Response(status=status.HTTP_202_ACCEPTED) return Response(status=status.HTTP_403_FORBIDDEN) I have then modified the delete in views.py function to become: @api_view(['DELETE']) @authentication_classes([SessionAuthentication]) def api_delete_cert(request, cert_name): … -
How can i after registration get jwt tokens (djangorestframework)
from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView from InternetShop import settings from InternetShopApp.views import * urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/products/', ProductsAPIList.as_view()), path('api/v1/products/<int:pk>/', ProductsAPIUpdate.as_view()), path('api/v1/productsremove/<int:pk>/', ProductsAPIRemove.as_view()), path('api/v1/auth/', include('djoser.urls')), path('api/v1/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/v1/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/v1/token/verify/', TokenVerifyView.as_view(), name='token_verify'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I need when user successfully register on api/v1/auth/ get jwt tokens in json answer -
django how to tell if send mail fails - and sending mail via AWS SES
I'm trying to link up to AWS SES, but the message (the login email confirmation message) isn't going out. That is the AWS SES monitor says there were no rejects (or sends). How do I figure out what is going wrong? I've tried two ways to send email: django-ses with the config as: EMAIL_BACKEND = 'django_ses.SESBackend' AWS_ACCESS_KEY_ID = 'wouldnt_you_like_to_know' AWS_SECRET_ACCESS_KEY = 'not_telling' and I've tried it as a simple client: EMAIL_HOST = 'email-smtp.us-east-1.amazonaws.com' EMAIL_HOST_USER = 'yada_yada' EMAIL_HOST_PASSWORD = 'shh_it_is_secret' EMAIL_PORT = 587 EMAIL_USE_TLS = True The console just shows: [12/Aug/2022 16:15:46,877] - Broken pipe from ('127.0.0.1', 57644) Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: [LVM System] Please Confirm Your E-mail Address From: Literacy Volunteers of MA <noreply@lvm.org> To: michael@hotmail.com Date: Fri, 12 Aug 2022 20:15:49 -0000 Message-ID: <166033534901.17800.6503664761440235634@Nibbitz> Hello from LVM System! You're receiving this e-mail because user noone has given your e-mail address to register an account on example.com. To confirm this is correct, go to http://127.0.0.1:8000/accounts/confirm-email/MQ:1oMb4O:sZoI4Z5UUvYXcXLiEGdZUfH5nnt2QO7jJ6iZ1L6zG48/ Thank you for using LVM System! example.com ------------------------------------------------------------------------------- [12/Aug/2022 16:15:49] "POST /accounts/login/ HTTP/1.1" 302 0 [12/Aug/2022 16:15:49] "GET /accounts/confirm-email/ HTTP/1.1" 200 1817 [12/Aug/2022 16:15:49] "GET /static/css/project.css HTTP/1.1" 304 0 [12/Aug/2022 16:15:49] "GET /static/js/project.js HTTP/1.1" 304 0 Thanks for the help. -
How to get a src image link instead of Django tag when fetching through jQuery?
I am trying to get value from django template to my external js file. It works well when in html template the data would be text like <h3 class="username">{{ user.first_name }} {{ user.last_name }}</h3> and js file code, var username = $(this).children().text(); But incase of image, it gives me the Django tags. Following is the html code, <img id="my_img" src="{{user.picture_url}}"> and js file code, profile_pic = $('#my_img').attr('src'); WHAT OUTPUT I EXPECT ? http://127.0.0.1:8000/media/profile_image/blog-img1_Pw8NJQm_trt743z.jpg WHAT OUTPUT I OBSERVED ? {{user.picture_url}} Please let me know how can I achieve the expected output. Thanks. -
djnago drf update field if all user read it
so i have this djnago rest framework views that filter latestbooks=True and return latest books and if user view book i have other funtion to remove book from latestbook by making latestbooks=False , it's works fine with one user now i have more users if the first one read the book it will remove from latestbook and other users won't be able to see it how i can remove book from latestbook only after all usres read it views.py class LatestBokks(ListAPIView): queryset = Book.objects.filter(latestbooks=True,blacklist=False).order_by('-date') serializer_class = BookSerial pagination_class = None models.py class Book(models.Model): title = models.CharField(max_length=255,unique=True) description = models.TextField(max_length=4000) alternative_name = models.CharField(max_length=200) author = models.CharField(max_length=500) type = models.CharField(max_length=20) book_slug = models.SlugField(max_length=200) image_file = models.ImageField(blank=True) image_url = models.URLField(blank=True) blacklist = models.BooleanField(default=False) latestbooks= models.BooleanField(default=False) date = models.DateTimeField(auto_now_add=True) duplicated = models.IntegerField(null=True,blank=True) -
Django Web App with Selenium download location heroku
I have the following problem, i have a selenium bot which download a file from a website and save it on local, he save on "C:\Users\name\Downloads", but on heroku i dont know where to put. chrome_options.add_experimental_option("prefs", { "download.default_directory": "C:\\Users\\name\\Downloads", "download.prompt_for_download": False, "download.directory_upgrade": True, "safebrowsing_for_trusted_sources_enabled": False, "safebrowsing.enabled": False } ) What can i add on heroku on 'download.default_directory', and how i can access the document (what path)? Thank you -
How to pass a list to the value of an input
I have the following input: <input type="hidden" id="accesspoint_node_attribute" name="accesspoint_node_attribute" value="name,military_organization,commander"> As can be seen, I'm passing three elements in value (name,military_organization,commander) However, the last element (commander) is a select multiple, so it can have more than one value. However, I can only pass one value. <select name="accesspoint_military_organization" id="accesspoint_military_organization" multiple> {% for om in oms %} <option value="{{om.Id}}">{{om.name}}</option> {% endfor %} </select> Any suggestions on how to pass all select values? -
Cors errors on Django apps
I'm trying to build a Django app with a react frontend and was trying to work out why I keep getting cors errors on my browser when I host it on the server. After reading up a bunch on this I figured out that I need to configure the following in the settings.py after installing django cors headers: ALLOWED_HOSTS = "127.0.0.1", "localhost:8000", "localhost" CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW = True CORS_ORIGIN_WHITELIST = [ "http://127.0.0.1:5501", "http://127.0.0.1:5500", "http://localhost:8000", "http://127.0.0.1:8000", ] CSRF_TRUSTED_ORIGINS = [ "http://127.0.0.1:5501", "http://127.0.0.1:5500", "http://localhost:8000", "http://127.0.0.1:8000", ] CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with", ] INSTALLED_APPS = [ "corsheaders", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rawWikiData.apps.RawwikidataConfig", ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "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", ] But I still get this error when I try to access the webpage from one of the frontend pages that I'm hosting using the static paths of django. Here is the error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/getSentenceData/. (Reason: CORS request did not succeed). Status code: (null). Uncaught (in promise) Object { message: "Network Error", name: "AxiosError", code: "ERR_NETWORK", config: {…}, request: XMLHttpRequest, response: … -
Django override CreateView with form_valid
I'm building a blog with Django that has a 'Create Post' page using CreateView. That requires three fields, an image, description, and author. I want the page to automatically assign the author to the logged-in user. the documentation says I should be using a form_valid method in the class I use to create a new post. I'm doing that, but... it's just not working. The actual error I'm getting is "IntegrityError at /new/ NOT NULL constraint failed: posts_post.author_id" ##models.py class Post(models.Model): image = models.ImageField() description = models.TextField(null=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) And the views.py: ##views.py class PostCreate(LoginRequiredMixin, CreateView): model = Post fields = ['image', 'description', 'author'] success_url = '/' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) I've changed the PostCreate around a lot, by taking out the 'author' in the fields of the PostCreate class... but yeah. I don't get it, this is pretty much directly copying out of the docs and it's not working. -
Python3: Correct way of doing ORM using metaclass
The following source file created ORM Car to represent a database table. But Car.brand became None afterward. Due to TableMetaCls is setting to all the db fields to None. How do I persevered Car.brand to StringField()? What's the properly way of doing? This is similar to django ORM, please see https://github.com/django/django/blob/main/django/db/models/base.py#L477 for reference. class Field: pass class StringField(Field): pass class TableMetaCls(type): def __new__(cls, name, bases, attr): # backup field definition field_definitions = {} for x, y in attr.items(): if isinstance(y, Field): field_definitions[x] = y attr['field_definitions'] = field_definitions # set field val to null for x, y in attr.items(): if isinstance(y, Field): attr[x] = None return super(TableMetaCls, cls).__new__(cls, name, bases, attr) class Table(metaclass=TableMetaCls): def save(self): pass class Car(Table): brand = StringField() model = StringField() c = Car() c.brand = "BMW" print(Car.brand) -
Moving a Django app into production using Nginx and Gunicorn, there are no errors but the page doesn't show
I'm trying to setup an app on my Digital Ocean production server, I've followed these instructions, testing gunicorn and nginx,I could access the app in gunicorn and both services start fine with no errors logged. However when I go to the site it does not show anything. This is a subdomain of my main site. Mostly I'm looking to find a place to start troubleshooting this especially since everything looks fine. -
How to index Django models in ElasticSearch using elasticSearch_dsl (how to synchronise)?
im into a project for my master's degree so it's really urgent please, i have models in django containing foreignkeys and manytomany relations, i cant seem to find out how to index them in an elasticSearch document here's my Article model : manytomany fields are referencing a User model. class Article (models.Model): A_Id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) resume = models.CharField(max_length=1000) auteur = models.ManyToManyField(User,related_name="articlelist",blank=True) fichier = models.CharField(max_length=300,blank=True,null=True) urlfichier = models.CharField(max_length=300,blank=True,null=True) sauvegarde = models.ManyToManyField(User,related_name="sauvegardelist",blank=True) recommendationlist = models.ManyToManyField(User,related_name="recommendationlist",blank=True) recommendation = models.IntegerField(default=0) date_posted = models.DateField() if anyone could show me how a document for this model is written, it would really be lifesaving thank you. -
Django run migrations without models.py file
Have created some models in django app and also made the migrations files corresponding to it. Now, AFAIK at the time of deployment we can run the migrations even before the models.py file is pushed and deployed. Now additionally I have to provide initial data with the models so have created the data in migration files using migrations.RunPython(func) as an operation however in the func(apps, schema_editor): xyz_model = apps.get_model('app_name', 'xyz') we have used the model xyz so does it need to have the models.py file updated before running this migration? -
Can't import rest_framework in Django despite it being installed in my venv
Following tutorials and I cannot import rest_framework. I've activated my venv, run python and import rest_framework as suggested in many discussions on stack overflow, though no errors are thrown. I am fairly confident that djangorestframework is installed as it is in the environment directory: venv dir shows rest_framework installed I also restarted VS Code and my venv as suggested to no avail. The error I receive in VS Code: Import "rest_framework" could not be resolvedPylancereportMissingImports Settings.py: INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'EmployeeApp.apps.EmployeeappConfig', 'rest_framework', ] Immediately below INSTALLED_APPS: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', ), } -
Setting a signed cookie for unit tests
In writing a unit test for my view, I am creating a request using the RequestFactory factory = RequestFactory() request = factory.get('/') Before I feed this request to my view for testing, I need to put a signed cookie in it (my view expects it). How can I do that? -
How to create a new user in Django using LDAP?
I'm using Django to create a REST API with LDAP. One of the endpoints gets a username (this is not the same username of the logged in user through IsAuthenticated). I want to check if that username exists in the system, even if he never logged-in. My current code was: try: user = User.objects.get(username=request.data['username']) except: return Response(data={"error": "User does not exist"}, status=status.HTTP_400_BAD_REQUEST) This of course does not work because the database contains users that have logged in at least once. How can I create the user if he does not exist? I know I can use User.objects.create but I want it to fetch the data from LDAP and not just to pass it the username. -
CSRF token issue when upgrading Django to version 4.*
I was using the Django version 3., but then upgraded it to Django version 4. (django==4.0.6). After logging to admin panel of Django project, it is said that CSRF token is invalid. I found this link in Django documentation: https://docs.djangoproject.com/en/4.0/releases/4.0/#csrf-trusted-origins-changes-4-0 And tried to put such variable in settings.py ALLOWED_ORIGINS = ['https://', 'http://'] But it didn't help. What I am doing wrong? -
'utf-8' codec can't decode byte 0xb3 in position 10: invalid start byte
I am trying to import csv do django using function below in my View, but I am getting this error: 'utf-8' codec can't decode byte 0xb3 in position 10: invalid start byte I got this function for another project and there works fine as csv file is created from excel, so decoding utf-8 works. But here I have cvs directly from some webpage and decoding not working. I tried to use my function without method decode(), but then I am getting another error: TypeError at /sales, initial_value must be str or None, not bytes my function for import of csv file in Views.py: class SalesView(LoginRequiredMixin, SuccessMessageMixin, FormView): template_name = "sales.html" form_class = UploadSalesData def test_func(self): return self.request.user.is_superuser def post(self, request, *args, **kwargs): form: UploadSalesData = UploadSalesData(request.POST, request.FILES) if form.is_valid(): csv_file = form.cleaned_data["uploaded_file"] decoded_file = csv_file.read().decode('utf-8-sig') io_string = io.StringIO(decoded_file) reader = csv.DictReader(io_string, delimiter=",", skipinitialspace=True) record_count = 0 for line in reader: SalesData.create_from_csv_line(line=line) context = self.get_context_data() my_text = 'New data uploaded successfully.' messages.success(request, my_text) return render(request, self.template_name, context) else: return self.form_invalid(form) And my model: class SalesData(models.Model): date = models.DateField("Date", null=True, blank=True) product = models.CharField("Product", max_length=150, null=True, blank=True) sales = models.DecimalField("Sales", max_digits=10, decimal_places=2, null=True, blank=True) quantity = models.IntegerField("Quantity", null=True, blank=True) total = models.DecimalField("Total", … -
How to get an object by id in Django
I am trying to get a particular object from Django... When I use filter it returns more than one and I need just one and I don't want to my fields unique... Is there a way I can get object by id since id will be the only unique field by default in Django Sqlite