Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'django.contrib.'
I'm getting this weird error when I'm trying to run my Django project, more details (Social_Media is the project's name): ModuleNotFoundError: No module named 'django.contrib.' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "E:\= Programming Office\Django Projects\Social_Media\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "E:\= Programming Office\Django Projects\Social_Media\lib\site-packages\django\core\management\commands\runserver.py", line 157, in inner_run handler = self.get_handler(*args, **options) File "E:\= Programming Office\Django Projects\Social_Media\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 31, in get_handler handler = super().get_handler(*args, **options) File "E:\= Programming Office\Django Projects\Social_Media\lib\site-packages\django\core\management\commands\runserver.py", line 78, in get_handler return get_internal_wsgi_application() File "E:\= Programming Office\Django Projects\Social_Media\lib\site-packages\django\core\servers\basehttp.py", line 49, in get_internal_wsgi_application raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: WSGI application 'Social_Media.wsgi.application' could not be loaded; Error importing module. wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Social_Media.settings') application = get_wsgi_application() Can anyone help me? -
I need to open the response which is video url in separate page
For this one I get response in a separate page as text, I need to convert this text into a url so that when I click that button it redirects to that page. const getData = () => { try{ axios.get(`${geturl}`,{ }).then(res=>document.write(res.data.result.content.previewUrl)); }catch(err){ console.log(err.message); }; -
Django REST Framework Serializer - how to save InMemoryUploadedFile to disk?
At my Django RestAPI I can upload an image, instead of saving this image at an ImageField referenced at the database I just want to save it to the disk without any further processing. Currently, my code looks like this: class UserAvatarUpdateSerializer(ClearNullSerializer, serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) avatar = serializers.ImageField(write_only=True, required=True) class Meta: model = get_user_model() fields = ('id', 'user', 'avatar',) read_only_fields = ('id', 'user') def save(self, **kwargs): new_avatar = self.validated_data['avatar'] directory = (str(MEDIA_ROOT) + "tmp/") filename = str(uuid.uuid4()) new_avatar.save(os.path.splitext((directory + filename))[0] + '.png', optimize=True, format='png') But I'm running into: AttributeError: 'InMemoryUploadedFile' object has no attribute 'save' So my question is how can I save a InMemoryUploadedFile to disk? -
How to access data in Docker from my Django app?
I am new to Docker so I wonder if I have 2 containers, a streamer that pushes data to the queue and vernemq which is the message queue. How can I access the data to work with it in my django rest api app? I was wondering is there a way to export or the data and create a separate database in django with it or it's not how it works? Or is there a way to directly access the data in docker from django app. Note the django rest api app is not in a docker Image. -
Make first name field unique for User in django
I am making a web app with django and I need to make the Users first name unique. I have searched around and it doesnt seem like there is a simple way to do this. The reason i need the first name to be unique is because i am using the first name field as a spotify username field because it makes it convenient because i can use the user creation form. -
how to filter the first 4 objects of a model
I wanna get the first 4 Blog objects associated with the Blog Model. I tried this: #views blog_list = blog.objects.all().order_by("id")[:4] This works until I create more than 4 blog objects, and then the result doesn't include the recently created objects rather it gets stuck with the first 4 objects. -
How to create a statistics endpoint?
I'm learning DRF and I've been stuck on this for a few days. I'm trying to create an endpoint that receives a date range .The response should return a report with the monthly sales distribution for the selected period between date_after and date_before. The value field should contain the total sum of all sold products in this month. Input: 127.0.0.1:8000/api/stats/?date_after=2022-08-12&date_before=2022-08-29 Desired response: [ { month: “2022 Jan”, value: 18.00 }, { month: “2022 Feb”, value: 36.00 }, ] My models: class Product(models.Model): title = models.CharField(max_length=200) price = models.DecimalField(max_digits=1_000, decimal_places=2) def __str__(self): return self.title class Order(models.Model): date = models.DateField() # TODO: Add auto_now_add True products = models.ManyToManyField(Product, blank=True, related_name='orders') My viewsets: class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer class OrderViewSet(viewsets.ModelViewSet): queryset = Order.objects.all().order_by('-date') serializer_class = OrderSerializer My serializers: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['id', 'title', 'price'] class OrderSerializer(WritableNestedModelSerializer, serializers.ModelSerializer): products = ProductSerializer(many=True, required=False, read_only=False) class Meta: model = Order fields = ['id', 'date', 'products'] I have no idea how to go about this so I've just been blindly scouring the docs. Any help is greatly appreciated. -
How to implement the penalty in loan
In Django Rest Framework, I'm creating a loan API. Can someone suggest how I implement the penalty function? This is how the penalty works. If the loan is not fully paid by 3 months, the remaining balance will be penalised by 1%, and then by another 1 month, if not fully paid, the remaining balance will be penalised by 1% again. For example, if I loan 50,000 on 8-23-2022, I will be penalised 1% of the remaining balance on 11-23-2022 and then by next month, 12-23-2022, if not fully paid, penalised again of 1%. this is my model for loan: class Loan(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) loan_amount = models.IntegerField() date = models.DateField(auto_now_add=True) and this is model for payments class LoanPayment(models.Model): loan = models.ForeignKey(Loan, on_delete=models.CASCADE) payment_amount = models.IntegerField() date = models.DateField(auto_now_add=True) -
Django QuerySet filter by Range with DateTimeField
I tried to fix my queryset method, checked some answers on Stackoverflow, but still couldn't do it. Basically i want to validate my form, so when there is an lesson within ceratin range, a Student cannot propose this specific timerange to it's lesson. The problem is that when i try to find a queryset withing DateTimeField that exists, i still got an empty queryset: My model: class Lesson(models.Model): student = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.ForeignKey(Classroom, on_delete=models.CASCADE) description = models.CharField(max_length = 200) start_time = models.DateTimeField() end_time = models.DateTimeField() accepted = models.BooleanField(default=False) Method in form: def clean(self): cleaned_data = super().clean() lesson_start_time = cleaned_data.get('start_time') lesson_end_time = cleaned_data.get('end_time') queryset = Lesson.objects.filter(start_time__range=(lesson_start_time,lesson_end_time)) print(lesson_start_time) #2022-08-23 15:44:00+00:00 print(lesson_end_time) #2022-08-23 15:36:00+00:00 print(queryset) # <QuerySet []> if lesson_end_time < lesson_start_time: raise ValidationError("End time cannot be lower than start time!") And there is for sure a Lesson Object within this range. What i know for now is that it requeries something else to filter DateTimeField by range, but everything that i tried didn't work (for example: Django - Filter objects by DateTimeField with a date range). Could you please help me? -
Linking to different models problem Django
I have to models models.py class Member(models.Model): full_name = models.CharField(max_length=125, unique=True) email = models.EmailField(max_length=125, blank=True, null=True) phone = models.CharField(max_length=20) detail = models.CharField(max_length=256, blank=True, null=True) image = models.ImageField(max_length= 256, upload_to='media', null=True, blank=True) date_created = models.DateTimeField(default=django.utils.timezone.now) class Meta: verbose_name_plural = "All Members" def __str__(self): return str(f"{self.full_name}") def save(self, *args, **kwargs): # delete old file when replacing by updating the file try: this = Member.objects.get(id=self.id) if this.image != self.image: this.image.delete(save=False) except: pass # when new photo then we do nothing, normal case super(Member, self).save(*args, **kwargs) class ActiveMember(models.Model): member = models.OneToOneField(Member, on_delete=models.CASCADE, related_name='is_member') start_date = models.DateField(default=django.utils.timezone.now) end_date = models.DateField(default=django.utils.timezone.now) status = models.CharField(max_length=2, choices=(('1','Active'), ('2','Inactive')), default = '1', blank=True, null=True) def __str__(self): return str(f"{self.member}") Just to get an idea of the site see picture. When I click on active (on Navbar) then under Actions edit. I am redirected to second image. This works fine for a while then after sometimes if I click on Harry it will take me to Ron or someone else. There's a problem with the Id that is being passed when a member is edited updated or deleted maybe everything gets screwed and stops working properly. I have to delete the database and starts again and it works again for awhile. … -
How to join values of two tables. python django
I am trying to use two tables inside one django query. But my query is resulting as "invalid JSON" format. I want to filter data in Request table by (status="Aprv"). The Request table contains attributes 'from_id' and 'to_id'. The uid is the id of the user who is currently logged in. If the current user(uid) is having the 'from_id' of Requests table, the query should return data of 'to_id' from the 'RegUsers' table. If the current user(uid) is having the 'to_id' of Requests table, the query should return data of 'from_id' from the 'RegUsers' table. class frnds(APIView): def post(self, request): uid = request.data['uid'] ob = Requests.objects.filter(status="Aprv") fid = ob.value('from_id') tid = ob.value('to_id') if fid == uid: obj = RegUsers.objects.filter(u_id=tid) else: obj = RegUsers.objects.filter(u_id=fid) ser = android_serialiser(obj, many=True) return Response(ser.data) Please Do Help me Currect the syntax. -
Django: How to navigate multi-level reverse relationships?
I have several models that are related hierarchically: Projects have one or more Experiments Experiments have one or more Scans Scans have one or more Scan Decisions Simplified Models: class Project(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255) class Experiment(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=255, blank=False) project = models.ForeignKey('Project', related_name='experiments', on_delete=models.CASCADE) class Scan(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) name = models.CharField(max_length=127, blank=False) experiment = models.ForeignKey('Experiment', related_name='scans', on_delete=models.CASCADE) class ScanDecision(models.Model): id = models.UUIDField(primary_key=true, default=uuid4, editable=False) scan = models.ForeignKey('Scan', related_name='decisions', on_delete=models.CASCADE) If I have a specific Scan Decision and I want to get the Project associated with that decision, how can I do so? The Django documentation speaks of backward relationships but the examples seem limited to a single level of relationship. For example, to get the ScanDecision associated with a Scan I could do something like: sd = ScanDecision.objects.get(id=1) sd.scan_set.all() # Returns all scan objects related to the specific ScanDecision But what if I want to get the Project that is associated with the ScanDecision indirectly through Scan and Experiment? e.g., something like this but without all the steps? sd = ScanDecision.objects.get(id=1) # The desired ScanDecision object s = sd.scan_set.all() # Gets the related Scan object e … -
whoosh schema in haystack and django
I am trying to integrate a whoosh searcher into a django project. I saw that you can do that using haystack but I am realizing I can't (dont know yet) how to add my custom whoosh index into the searcher. My schema has ID, KEYWORD and TEXT but they are all text in reality. I used these schemes because it suits my search needs for each of the documents. How do I use this schema in Haystack. PS: A solution without Haystack is ok too. Here is my whoosh schema/writer/searcher import pandas as pd from whoosh.index import create_in from whoosh.fields import * from whoosh.qparser import QueryParser from whoosh.query import * def nan2none(x): y = None if pd.isna(x) else x return(y) df = pd.read_csv("df.csv", index_col=[0]) schema = Schema(a = ID(stored=True), b = KEYWORD(lowercase=True), c = TEXT, d = KEYWORD(lowercase=True)) ix = create_in("indexdir", schema) writer = ix.writer() for index, row in df.iterrows(): writer.add_document(a = index, b = nan2none(row['b']), c = nan2none(row['c']), d = nan2none(row['d'])) writer.commit() search_term = "hobbit" with ix.searcher() as searcher: a_query = QueryParser("a", ix.schema).parse(search_term) b_query = QueryParser("b", ix.schema).parse(search_term) c_query = QueryParser("b", ix.schema).parse(search_term) d_var_query = QueryParser("d", ix.schema, termclass=Variations).parse(search_term) d_fuzz_query = QueryParser("d", ix.schema, termclass=FuzzyTerm).parse(search_term) query = Or([a_query, b_query, c_query, d_var_query, d_fuzz_query]) results … -
Field 'mobile' expected a number but got ['2222222', '2222222']
This is Error showing TypeError at /page Field 'mobile' expected a number but got ['22222', '3333']. Request Method: POST Request URL: http://127.0.0.1:8000/page Django Version: 4.1 Exception Type: TypeError Exception Value: Field 'mobile' expected a number but got ['22222', '3333']. While Submitting Form This error occurs. I am trying to submit form of same name twice simultaneously to same model Views.py def page(request): if request.method == 'POST': description = request.POST['description'] price = request.POST['price'] name = request.POST.getlist('name') mobile = request.POST.getlist('mobile') pay = bill(description=description,price=price) pay.save() mypayee = payee(billId=pay,name=name,mobile=mobile) mypayee.save() return render(request, 'split_app/page.html') this model from django.db import models # Create your models here. class bill(models.Model): price = models.IntegerField() description = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.description class payee(models.Model): billId = models.ForeignKey(bill,on_delete=models.CASCADE,related_name='persons') name = models.CharField(max_length=50) mobile = models.IntegerField() this is image of HTML FORM generated using javascript enter image description here ** This is how I am submitting data with form having same form twice of same name(name & mobile) ** HTML generate <div class="container my-3"> <button type="button" class="btn btn-secondary">ADD NEW BILL</button> <form action="/page" method="POST"> {% csrf_token %} <div class="input-group mb-3"> <label for="discription" class="col-sm-2 col-form-label">DESCRIPTION:</label> <div class="col-sm-2"> <input type="text" name="description" id="discription" placeholder="Bill For.." /> </div> </div> <div class="input-group mb-3"> <label for="price" class="col-sm-2 … -
In Django define a validation function to avoid number overlaps
In django apps i have a model for the range number In my model.py def valide_range(value): all_ranges = RangeNumber.objects.all() for a_range in all_ranges: if a_range.start_num_int <= value <= a_range.end_num_int: raise ValidationError('The number is in an exiting number range') class RangeNumber(models.Model): start_num = models.IntegerField(validators=[valide_range]) end_num = models.IntegerField(validators=[valide_range]) This validation is ok for the create range but not for the udapte range, because is check all range(the edited range and the other), for the update I want just check the other. Thanks -
Django - NOT NULL constraint failed with modelchoicefield
I am making an auction site for an assignment, but I cannot manage to make the category non-obligatory when creating a new listing. I get a NOT NULL constraint failed error after pressing "Create listing", while I have null=True and blank=True in my model. What am I doing wrong? my category model looks like this: class Category(models.Model): name = models.CharField(max_length=64, blank=True, null=True) def __str__(self): return self.name forms.py looks like this: class CreateListing(forms.ModelForm): category = forms.ModelChoiceField(queryset=Category.objects.all(), empty_label="No category", required=False) class Meta: model = AuctionListing fields = ('title', 'description', 'starting_bid', 'url', 'category', 'user') widgets = { 'title': forms.TextInput(attrs={'placeholder':'Write your listing title here...'}), 'description': forms.Textarea(attrs={'placeholder':'Write your comment here...', 'rows':3}), 'user': forms.HiddenInput(), } def __init__(self, *args, **kwargs): user = kwargs.pop('user') super().__init__(*args, **kwargs) self.fields['user'].initial = user.id And this is the view for creating a listing: def create_listing(request): form = CreateListing(request.POST, user=request.user) if request.method == "POST": if form.is_valid(): form.save() return HttpResponseRedirect(reverse("index")) else: print("RIP") return render(request, "auctions/create_listing.html", {"form": form}) return render(request, "auctions/create_listing.html", { "form" : CreateListing(user=request.user) }) -
RemovedInDjango20Warning: Error handlers should accept an exception parameter. Update your code as this parameter will be required in Django 2.0
Hi Stackoverflow community, does anybody knows how to cope with the Django warning? RemovedInDjango20Warning: Error handlers should accept an exception parameter. Update your code as this parameter will be required in Django 2.0 -
Jquery code in my django app is not working
Well i have an issue with my Jquery code.I'm including my script file - which depends on jQuery - after jQuery. So i dont know what is the issue. The HTML page i extended jquery from : <!-- Core JS --> <!-- build:js assets/vendor/js/core.js --> <script src="{% static 'main/vendor/libs/jquery/jquery.js' %}"></script> <script src="{% static 'main/vendor/libs/popper/popper.js' %}"></script> <script src="{% static 'main/vendor/js/bootstrap.js' %}"></script> <script src="{% static 'main/vendor/libs/perfect-scrollbar/perfect-scrollbar.js' %}"></script> <script src="{% static 'main/vendor/js/menu.js' %}"></script> <!-- endbuild --> <!-- Vendors JS --> <!-- Main JS --> <script src="{% static 'main/js/main.js' %}"></script> <!-- Page JS --> {% block js %} {% endblock %} HTML with ajax code <script> paypal .Buttons({ createSubscription: function (data, actions) { return actions.subscription.create({ plan_id: "my plan", // Creates the starter plan }); }, onApprove: function (data, actions) { $.ajax({ type: "POST", url: "{% url 'payment-success' %}", data: { subscriptionID: data.subscriptionID, userId: "{{user.profile.uniqueId|safe}}", csrfmiddlewaretoken: "{{csrf_token}}", }, sucess: function (data) {}, }); }, onCancel: function (data) { $.ajax({ type: "POST", url: "{% url 'payment-success' %}", data: { 'userId': "{{user.profile.uniqueId|safe}}", 'csrfmiddlewaretoken': "{{csrf_token}}" }, sucess: function (data) { alert(data.result); } }); alert("You have canceled your subscription"); } }) .render("#paypal-button-container-1"); // Renders the PayPal button </script> My views.py from django.shortcuts import render, redirect, HttpResponse from django.contrib.auth.models import … -
Django template looping for each character
I have a text file like generated from 100 Cisco switches like this: ['device1', 'device2', 'device3', 'device4', ....., deviec100] and I want to show this information using loop in template. So I have something like this in my HTML file to loop through each device: {% for x in devie_list %} {{ x }} {% endfor %} But it is just adding a space between each character, so the result is like this: [ ' d e v i c e 1 ' , ' d e v i c e 2 , .... ] How can I tell Django, to loop through each item within the commas? or better say each list item. -
django.utils.datastructures.MultiValueDictKeyError: 'file'
Hey i got this function to save file into folder. @csrf_exempt def SaveFile(request): file=request.FILES['file'] file_name=default_storage.save(file.name,file) return JsonResponse(file_name,safe=False) Firstly it worked fine, i managed to upload image. But after few tries it stopped working showing the error like this: django.utils.datastructures.MultiValueDictKeyError: 'file' [22/Aug/2022 15:58:34] "POST /events/savefile HTTP/1.1" 500 72933 I upload it with postman, post method-body-form-data, no idea where is the problem. I read some posts about that, tried to add get after file=request.FILES['file'], but didnt worked. Any advice where could be the problem? -
Assign RBAC role to ManagedIdentity from python function
I have an azure python function which creates bunch of resources and after they are created, I need to assign some roles to Web App hosted on Azure so it can access those newly created resources and that web app use System Assigned Managed Identity. That Azure python function also use system assigned Managed Identity. If I will use code credential = ManagedIdentityCredential() this will return credentials for my azure python function. How can I get to Managed Identity of the Web App in my azure function so I can start assigning some roles? I know I should use AuthorizationManagementClient but it need credential token and in case of system assigned managed identity, there are no parameters for ManagedIdentityCredential() so I can't point to that Web App. -
Getting an error App 'org' doesn't have a 'Topic' model when running tests in django app
I have the below function in the migrations file to add initial data to db: def add_topics(apps, schema_editor): topic_model = apps.get_model('org', 'Topic') for topic in TOPICS: topic_model.objects.get_or_create(name=topic['name'], display_name=topic['display_name']) However running tests is giving an error, in get_model LookupError: App 'org' doesn't have a 'ContextualSubTopic' model. App 'org' doesn't have a 'Topic' model. -
Best way to get the model object that has a DateTime field closest in DateTime to current DateTime
I want to make an efficient ORM query that returns the model object in which the objects datetime is the closest to the current datetime. So if the current datetime is 22/08/2022 15:00 and I have objects with datetimes of object1.datetime == 22/08/2022 15:30 and object2.datetime == 22/08/2022 15:45 I want to be able to query the DB for the object with the closest datetime which would be the object1 object. So basically I want to find the object that is closest, in the future, to the current datetime. The only solutions I've been able to think of are inefficient and involve looping and comparing multiple objects by adding them to lists etc. dt = datetime.datetime.now() objs = Model.objects.all() for obj in objs: if obj.dateTime //etc... Obviously this isn't a good solution because it's going to loop through my whole model database. How can I make this query in the most efficient way? -
What is the use of token return after login or registration from django-rest-knox?
Hy there, I work on project where I used django-rest-knox for token authentication. I have doubt that 1.How token be used that has return while registering and login. ( when i pass token in postman as like, in header section Authentication Token abcjdkkfjjrhehrjlajn@kfjdk ) this doesnot work 2.when i call logout and logoutall endpoint it say, { "detail": "Authentication credentials were not provided." } even though i pass all correct credentials. Here is the code that i follow, in setting.py REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( 'knox.auth.TokenAuthentication', "rest_framework.authentication.BasicAuthentication", "rest_framework.authentication.SessionAuthentication",)} REST_AUTH_TOKEN_MODEL = 'knox.models.AuthToken' REST_AUTH_TOKEN_CREATOR = 'users.authentication.create_knox_token' REST_AUTH_SERIALIZERS = { 'USER_DETAILS_SERIALIZER': 'users.serializers.CustomUserSerializer', 'TOKEN_SERIALIZER': 'users.serializers.KnoxSerializer' } in urls.py path('auth/register/',KnoxRegisterView.as_view(),name='register'), path('auth/login/',KnoxLoginView.as_view(),name='login'), path('api/auth/logout/',knox_view.LogoutView.as_view(),name='knox_login'), path('api/auth/logoutall/',knox_view.LogoutAllView.as_view(),name='knox_alllogin'), in authentication.py from knox.models import AuthToken def create_knox_token(token_model, user, serializer): token = AuthToken.objects.create(user=user) return token in serializers.py class KnoxSerializer(serializers.Serializer): """ Serializer for Knox authentication. """ token=serializers.CharField() user = CustomUserDetailsSettingsSerializer() in views.py class KnoxRegisterView(RegisterView): def get_response_data(self, user): return KnoxSerializer({'user': user, 'token': self.token}).data def perform_create(self, serializer): user = serializer.save(self.request) self.token = create_knox_token(None, user, None) complete_signup(self.request._request, user, allauth_settings.EMAIL_VERIFICATION, None) return user class KnoxLoginView(LoginView): def get_response(self): serializer_class = self.get_response_serializer() data = { 'user': self.user, 'token': self.token } serializer = serializer_class(instance=data, context={'request': self.request}) return Response(serializer.data, status=200) -
How to automatically replace a word with another?
I am currently using Django 4.0 and trying to find a way to transform the following: [year] to the current year. It needs to be automatically replaced every time [year] is found. Be it from the admin panel, from CKEDITOR, or comments, etc. I can find ways to do this when [year] is hardcoded, but I don't know how to make it work when I am posting a blog post from Django Admin, for example. To also add, I have tried using JS to transform the [year] tag to the current year. The problem with this is that it doesn't work on the page title or for search engines. They will still index the page with [year] instead of 2022, for example. Using JS works well for people, but not from a SEO perspective. Your help would be appreciated! Thanks.