Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Image media is not getting upload on AWS S3 media folder-CKEditor
When I was uploaded image from backend django admin then the image is not getting upload on aws s3 media folder with name django-ckeditor-5/example.img. It is creating one folder with name django-ckeditor-5 on local server. but Not uploading on aws s3 media folder. I have tried these both path but not working url(r'^ckeditor5/(?P<path>.*)/?$', include('django_ckeditor_5.urls')), and path("ckeditor5/", include('django_ckeditor_5.urls')), Click here to see the image of problems. below is my settings.py configuration for aws and media url STATIC_URL = 's3url/static/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_ROOT = "s3url/static/" MEDIA_URL = 's3url/media/' DEFAULT_FILE_STORAGE = '' PUBLIC_MEDIA_LOCATION = 'media' AWS_ACCESS_KEY_ID = 'XXXXXXXXXXXXXX' AWS_SECRET_ACCESS_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' AWS_STORAGE_BUCKET_NAME = 'SOME-bucket' AWS_S3_CUSTOM_DOMAIN = '' AWS_LOCATION = '' AWS_DEFAULT_ACL= None -
Django Dynamic Formsets Add Button Doesn't Work
I new in Django and in web development. I follow this tutorial https://engineertodeveloper.com/dynamic-formsets-with-django/ to implement a dynamic formset in my Django project. I don't know to much about Javascript yet, so can anyone help me? I wrote the same javascript code in my Django app and my template is very similar with the tutorial's template, I used the same id to identify the HTML tags, but the "Add Another Image" button isn't working for me. When a click on it, nothing happens, on the other hand, the "Delete" button is working fine. My main form and my formset are different than the tutorial's mainform and formset. My form and my formset have three fields each. Javascript by: https://engineertodeveloper.com/dynamic-formsets-with-django/ const imageForm = document.getElementsByClassName("image-form"); const mainForm = document.querySelector("#pet_form"); const addImageFormBtn = document.querySelector("#add-image-form"); const submitFormBtn = document.querySelector('[type="submit"]'); const totalForms = document.querySelector("#id_form-TOTAL_FORMS"); let formCount = imageForm.length - 1; function updateForms() { let count = 0; for (let form of imageForm) { const formRegex = RegExp(`form-(\\d){1}-`, 'g'); form.innerHTML = form.innerHTML.replace(formRegex, `form-${count++}-`) } } addImageFormBtn.addEventListener("click", function (event) { event.preventDefault(); const newImageForm = imageForm[0].cloneNode(true); const formRegex = RegExp(`form-(\\d){1}-`, 'g'); formCount++; newImageForm.innerHTML = newImageForm.innerHTML.replace(formRegex, `form-${formCount}-`); mainForm.insertBefore(newImageForm, submitFormBtn); totalForms.setAttribute('value', `${formCount + 1}`); }); mainForm.addEventListener("click", function (event) { if (event.target.classList.contains("delete-image-form")) … -
TypeError: __str__ returned non-string (type NoneType) in Django
I am pulling data with where conditions and trying to print the object but it's throwing error TypeError: __str__ returned non-string (type NoneType) in Django help me with this error as I am learning Django This is my function def example_view(request): if request.method == 'POST': abc = request.data.get('abc') xyz = request.data.get('xyz') for obj in User.objects.raw('select * from public."Example_App_user" where abc = %s and xyz = %s',[abc,xyz]): print(obj) -
I am getting user data which I need to manually validate and then send it to a django model to save in the database after manual validation
i am getting user data from a Django form which i need to validate manually and then save it to django model database, the problem is that validation might take 24-48 hours. How do i hold the data temporarily so that when validated that data can be sent to the database using django models automatically, is there any functionality in django which will allow me to do that, if not how to do it. -
Nuxt middleware - user is not authenticated with Django backend
I created a Nuxt frontend that uses Django for everything authentication related. I'm using the standard Django Session Authentication system, but i'm having a problem. I created a middleware that checks if the user is authenticated. In order to check if the user is authenticated, it sends a GET request to an API endpoint in my Django backend, and Django checks if the user is authenticated. Here is the code for the middleware: export default function (context) { return axios.get('http://127.0.0.1:8000/api/check') .then(response => { console.log(response.data['state']) }) } And here is the Django code: @csrf_exempt def check(request): response = {'state': str(request.user.is_authenticated), 'username': str(request.user)} return JsonResponse(response, safe=False) The problem with my code is that when i'm authenticated, this code returns False when the request is sent from the middleware, which means that according to Django i'm not authenticated. But if i send the same request after the page is loaded, Django will return True, so the user is authenticated. Why is that? Does it have anything to do with the SessionID cookie that Django sets? -
changes in models.py not reflecting on website even after running successful makemigrations and migrate commands
my models.py looks like this from django.db import models from django.urls import reverse class Product(models.Model): PRODUCTS_CATEGORY = [ ('None', 'None'), ('Sterilisation', 'Sterilisation'), ('Cleaning Chemistry', 'Cleaning Chemistry'), ('Bacterial Barrier', 'Bacterial Barrier'), ('Waste Management', 'Waste Management'), ('Instrument Tracking', 'Instrument Tracking'), ('Validation', 'Validation') ] prod_id = models.AutoField prod_name = models.CharField(max_length=100) prod_category = models.CharField( max_length=100, choices=PRODUCTS_CATEGORY, default='None') prod_desc = models.TextField() prod_img = models.ImageField(upload_to='product_images') slug = models.SlugField(null=True, blank=True) def __str__(self): return self.prod_name i changed the spelling of Sterilisation to Sterilization (replacing the 's' with 'z') i ran python manage.py makemigrations and it returned Migrations for 'website': website/migrations/0003_auto_20210407_1842.py - Alter field prod_category on product i then ran python manage.py migrate and it returned Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, website Running migrations: Applying website.0003_auto_20210407_1842... OK but i dont see the changes reflected on the website. the spelling still remains to be Sterilisation! What can be the reason for this? PS: I am using sqlite3 and the website is on Ubuntu 20.04x64 which is a VPS. -
Does Django ORM implement Builder pattern?
I'm not sure but it seems that Django ORM implements Builder pattern, right? Example of query making: Entry.objects \ .filter(headline__startswith='What') \ .exclude(pub_date__gte=datetime.date.today()) \ .filter(pub_date__gte=datetime.date(2005, 1, 30)) -
Django Filter Issue Many to Many
I am having a problem where my chained filter using many to many lookups are not performing as I expected. Here are the pertinent details: views.py def cs_edit_result(request, ctype=None, survey_id=None): #if POST request resume answering survey answers from a selected customer survey. if request.method == 'GET': sid = Survey.objects.get(pk=survey_id) if request.method == 'POST': sid = Survey.objects.get(pk=survey_id) form = CustomerSurveyForm(request.POST, instance=sid) #filter placeholders to only form data from customer survey: if form.is_valid(): cs_result = form.save() answers = SurveyAnswers.objects.filter(surveyid=sid.id) for x in answers: x.status=False x.save() print(form) citype = form.cleaned_data['institution_type'] cproducts = form.cleaned_data['products'] cpurchases = form.cleaned_data['purchase'] cservices = form.cleaned_data['services'] colb = form.cleaned_data['olb_vendor'] cph1 = SurveyAnswers.objects.filter(surveyid=cs_result).filter( Q(placeholder__purchase__in=cpurchases), Q(placeholder__institution_type__in=citype), Q(placeholder__olb_vendor__in=colb), models.py class PlaceHolder(models.Model): output_choices = [ ('link','Link'), ('plain text', 'Plain Text'), ('html', 'HTML') ] purchase = models.ManyToManyField(Purchase, related_name='purchase_place') institution_type = models.ManyToManyField(InstitutionType, related_name='itype_place') products = models.ManyToManyField(Product,blank=True, related_name='products_place') services = models.ManyToManyField(Service,blank=True, related_name='services_place') olb_vendor = models.ManyToManyField(OLB_Vendor,blank=True, related_name='olb_place') output_type = models.ManyToManyField(Output_Type) question = models.TextField(null=True, verbose_name = 'question/title') silvercloud_placeholder = models.CharField(max_length=50) output_type = models.CharField( max_length=100, choices= output_choices, default='Plain Text') answer = models.TextField(blank=True,null=True, verbose_name='url/answer') def __str__(self): return self.silvercloud_placeholder class Survey(models.Model): customer = models.CharField(max_length=50) purchase = models.ManyToManyField(Purchase) institution_type = models.ManyToManyField(InstitutionType) products = models.ManyToManyField(Product) services = models.ManyToManyField(Service,blank=True) olb_vendor = models.ManyToManyField(OLB_Vendor) def __str__(self): return ('{} Survey {}'.format(self.customer, str(self.id))) class SurveyAnswers(models.Model): #contributor = admin. surveyid … -
Django UniqueConstraint to check if value is unique in model property
I have two models: Header and TroopsType, which is used in OneToOneField in Header. What I am trying to achieve is to check if Header's name is unique, but not only in Header's name field, but also in TroopsType's one. That's because if you choose some value in troops_type, then name field is not required and it should, so to speak, inherit that name from TroopsType object to not duplicate values by copying it. Of course, if you keep troops_type NULL, then Header's name is required. How would you do so? To clearify my train of thought, I attach my current code which I am trying to modify - currently I just copy the name. models.py: class TroopsType(models.Model): name = models.CharField(max_length=32, unique=True) unit = models.ForeignKey(Unit, on_delete=models.RESTRICT) def __str__(self): return self.name class Header(models.Model): name = models.CharField(max_length=32, blank=True, unique=True) troops_type = models.OneToOneField( TroopsType, on_delete=models.CASCADE, blank=True, null=True ) data_type = models.ManyToManyField(DataType) class Meta: constraints = [ models.CheckConstraint( check=(~models.Q(name="")), name="%(app_label)s_%(class)s_required_name", ), ] def __str__(self): return self.name admin.py: class HeaderAdminForm(forms.ModelForm): class Meta: model = Header fields = "__all__" def clean(self): troops_type = self.cleaned_data["troops_type"] if troops_type: self.cleaned_data["name"] = troops_type.name elif not self.cleaned_data["name"]: raise forms.ValidationError("No name or troops type.") super().clean() @admin.register(Header) class HeaderAdmin(admin.ModelAdmin): form = HeaderAdminForm -
django-crispy-forms with jinja2 FormHelper support
This an expansion on an old question that does not fully answer my question (django crispy forms with jinja2). I am using django-crispy-forms with jinja2 and have already figured out how to get these two to work together using the answer provided in that link. What you lose when doing that is all support for FormHelper and Layout. Has anybody figured out a way to get this functionality with Jinja2? -
IntegrityError at /quizmaker/ (1048, "Column 'id_id' cannot be null")
I am trying to make quiz making application, since am new to django am unable to build the logic for saving foreign key field in database table. Someone please help me for the same. models.py In models.py , class quiztitle is for title of the quiz and id(foreign key,User model) of user who created that quiz. class question is for question along with 4 options and the correct answer. Quizid(foreign key,quiztitle model) and id(foreign key,User model) class answer is for the answer submitted by user who take the quiz. from django.db import models from django.contrib.auth.models import User class quiztitle(models.Model): Quiz_id = models.AutoField(primary_key=True) Quiz_title = models.CharField(max_length=600) id= models.ForeignKey(User, on_delete=models.CASCADE) class question(models.Model): Qid = models.AutoField(primary_key=True) id = models.ForeignKey(User,on_delete=models.CASCADE) Quiz_id = models.ForeignKey(quiztitle,on_delete=models.CASCADE) Qques = models.TextField() Qoption1 = models.TextField() Qoption2 = models.TextField() Qoption3 = models.TextField() Qoption4 = models.TextField() QAnswer = models.TextField() class answer(models.Model): Ansid = models.AutoField(primary_key=True) Qid = models.ForeignKey(question,on_delete=models.CASCADE) Quiz_id = models.ForeignKey(quiztitle, on_delete=models.CASCADE) id = models.ForeignKey(User, on_delete=models.CASCADE) Answer = models.TextField() forms.py from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django import forms from django.contrib.auth.models import User class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username','email','password1','password2'] views.py from django.shortcuts import render,redirect,HttpResponseRedirect from .models import question ,quiztitle from django.contrib import messages from django.contrib.auth import … -
Django Annotation Aggregation Speed
I'm using the following annotation to generate a count of related objects in a database: challenges = Challenge.objects.annotate( solve_count=Count('solves', filter=Q(solves__correct=True)), unlock_time_surpassed=Case( When(release_time__lte=timezone.now(), then=Value(True)), default=Value(False), output_field=models.BooleanField(), ), votes_positive=Count("votes", filter=Q(votes__positive=True), distinct=True), votes_negative=Count("votes", filter=Q(votes__positive=False), distinct=True), ) The query this generates takes around 2000ms to execute with 1000 Challenges and 1 million Solves. if I replace solve_count=Count('solves', filter=Q(solves__correct=True)), with solve_count=Value(0, output_field=models.IntegerField()), the time spent on queries goes from 2000ms to 50ms (but obviously the solve count is lost in the process) Is there anything I can do to increase the performance of the Count operation? -
Can't database cache be used in django celery?
I know that a typical memory base cache is not available in the celery. But can't we also use database cache? And When I use DatabaseCache in tasks, cache value not stored in database, but that the code run normally. Is memory cache used instead of database cache by force? -
My django login form isn't working, says 'request' has no atrribute 'method'
When I try to login on my django site, I get this error: AttributeError at /login/ 'User' object has no attribute 'method' What is the problem? I'm fairly sure it was working yesterday, and now it isn't. This is my login view: from django import forms from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.http import HttpResponseRedirect class LoginForm (forms.Form): username = forms.CharField() password = forms.CharField() def login (request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): # username = request.POST['username'] # password = request.POST['password'] username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None and user.is_active: login(user) return redirect ("/login/success") form = LoginForm(request.POST) else: form = LoginForm(request.POST) return render (request, 'login.html', {'form':form}) -
how can use Yes, No filter in django
In template when i select any category it just show the last category which i added. After select any category it should show the that category but it show last added category by default Template {% block content %} <label> <select name="SelectCategory" > <option disabled="disabled" value="True" selected="{{ selectedCategory|yesno:"yeah, no, maybe" }}"> Select Category</option> {% for category in categories %} <option value="{{ category.id }}" selected="{% if category.id == selectedCategory %} {% endif %}"> {{ category.name }} </option> {% endfor %} </select> </label> {% endblock %} -
UpdateView that creates or increments existing instance
I have a model that keeps track how much items have been "bought" at a certain value. For example, one could think of items as stocks, value as the price they have been bought at. class Inventory(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() value = models.PositiveIntegerField() class Meta: db_table = 'app_version' constraints = [ models.UniqueConstraint(fields=['item', 'value'], name='unique valued items') ] Now, I'm trying to write a class-based Create/UpdateView in which one simply declares which item has been bought at what price. Then, the view should either create a new instance or increment an existing instance's quantity. I already figured out that an UpdateView might be the best start as I can overwrite the get_object method to have this "create or update" behaviour. However, I'm not sure how to do the incrementing. Perhaps I'm also completely on the wrong track and there is a much simpler solution I am missing here. It would be great to get some ideas and input on how to approach this problem. Thank you so much! -
Just getting the status code but not the data, but in postman it does
I want to send an error message through data when some errors occurs in API, here is the API code: @api_view(['GET']) def RespuestaListView(request, idQuestion): try: question = Question.objects.get(pk=idQuestion) except Question.DoesNotExist: return Response(data={'error': 'That question does not exist'}, status=status.HTTP_404_NOT_FOUND) try: answers= Answer.objects.filter(question=question).select_related() except: return Response(data={'error': 'It can't be done'}, status=status.HTTP_409_CONFLICT) if (answers.count() == 0): return Response(data={'error': 'There is no answers for that questions'}, status=status.HTTP_204_NO_CONTENT) res = [] for answers in answers: res.append(AnswerSerializer(answer).data) return Response(data=res, status=status.HTTP_200_OK) If I call this from postman, it receives the error messages in data: Please ignore the spanish call But when I try to do it from a function in reactjs, when one of the handled errors occurs it just does not work, and I just get the status code. -
How to make a GraphQL api request from Django application?
I would like to know how to retreive data using the GraphQl api service and NOT to create the API. -
I am unable to fetch partial data from related table in django
One order have many order items and if i exclude one of its order items, then it will exclude all other order items of that order id. Can somebody please tell me why? Here is order-id = 8056313100 and two order-items that have ids = 8056313101, 8056313102. Here is View.py order = Order.objects.distinct().filter(orderitem__status=request.data['status']).exclude(orderitem__order_item_id=8056313102) serializer = ListOrderSerializer(order, many=True) return Response(serializer.data) Serializer.py class ListOrderSerializer(serializers.ModelSerializer): order_items = ListOrderItemSerializer(many=True, read_only=True) class Meta: model = Order exclude = ('id',) Order-item-id = 8056313101 will also exclude. Please help me. -
Spyne/Django: Add reversed OneToOne field to response
I'm looking to make use of spyne + django to provide a soap api. In django I have two related models with a one to one relation between them. # models.py class MainThing(): number = models.CharField(max_length=32) # plus other CharFields here class RelatedThing(): number = models.CharField(max_length=32) main = models.OneToOneField('MainThing', on_delete=models.CASCADE) I then have a "service" that connects spyne to django: # service.py from .models import MainThing as MainThingModel class MainThing(DjangoComplexModel): class Attributes(DjangoComplexModel.Attributes): django_model = MainThingModel class MainThingService(DjangoService): @rpc(primitive.String, _returns=MainThing) def retrieveThing(ctx, number): return MainThingModel.objects.get(number=number) api = Application(services=[MainThingService], tns='http://a.tns.com/', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11()) Calling retrieveThing will give a response that includes all the fields from MainThing, but not the OneToOne from RelatedThing. I would like to include the "relatedthing" number in the retrieveThing response. Is there a way to do this? -
Getting None type value from ManytoMany Field in django rest framework
I cannot retrieve answer choice id in ManytoMany field in serializers list or retrieve instead I got quiz.Choice.None and I understand why is that, but if I remove answer = serializers.CharField() this line from serializer. It raised an error when creating Question: { "answer": [ "Incorrect type. Expected pk value, received str." ] } I cannot pass answer from frontend, I expected to retrieve "answer": [2,3] instead of None and I also know that if I remove answer = serializers.CharField() this line from serializer. It solves the problem, But it raises another problem that I cannot pass an answer choice id that is not even created yet. What is the best solution for this type of problem? I also tried answer validations to an empty array. But that's not working even. { "id": 5, "label": "Question 1", "answer": "quiz.Choice.None", "explanation": "New Added fhfd", "mode": 1, "subtopic": 2, "choice": [ { "id": 5, "option": "option 6 Edited New One", "question": 5 }, { "id": 6, "option": "option 5 Hllloo Sakib", "question": 5 } ] } My Model: # Question Mode MODE = ((0, "Easy"), (1, "Medium"), (2, "Hard")) class Question(models.Model): """Question Model""" label = models.CharField(max_length=1024) answer = models.ManyToManyField("Choice", related_name="quesans", blank=True) explanation … -
AttributeError: 'MovieSerializer' object has no attribute 'id' + Serialization
The perfect scenario would be to use the RatingSerializer inside the MovieSerializer but since it is below the actual mvserializer code, i cannot use it. Therefore, I started to serialize the rating object using json.dumps() and it looks very ugly after serialization. serializers.py class MovieSerializer(serializers.ModelSerializer): id = 15414 director = PersonSerializer() rating = serializers.SerializerMethodField() # I want to use here RatingSerializer() def get_rating(self, obj): r = list(Rating.objects.filter(movie_id=self.id).values())[0] r['rating'] = float(r['rating']) return json.dumps(r) class Meta: model = Movie fields = ['id', 'title', 'director', 'rating'] class RatingSerializer(serializers.ModelSerializer): movie = MovieSerializer() class Meta: model = Rating fields = ['id', 'movie', 'rating', 'votes'] result, the rating field is serialized very bad { "id": 16906, "title": "Frivolinas", "director": { "id": 2014, "name": "Iron Eyes Cody", "birth": 1907 }, "rating": "{\"id\": 1, \"movie_id\": 15414, \"rating\": 5.4, \"votes\": 12}" }, is there a way I can use RatingSerializer inside MovieSerializer? Doing this way (my way), i also cannot find the actual id in the get_rating method, i have hard coded it. -
geopy returning "Civitas Vaticana" string instead of actual city name in django
I am using geopy in django. here I am printing this dictionary from geopy and I need only city name from this dictionary: {'city': 'Singapore', 'continent_code': 'AS', 'continent_name': 'Asia', 'country_code': 'SG', 'country_name': 'Singapore', 'dma_code': None, 'is_in_european_union': False, 'latitude': 1.3024, 'longitude': 103.7857, 'postal_code': '13', 'region': None, 'time_zone': 'Asia/Singapore'} here is my code for getting city name: #views.py from geopy import Photon from .utils import get_geo def calculate_distance_view(request): distance = None destination = None obj = get_object_or_404(Measurement, id=1) form = MesurementModelForm(request.POST or None) geolocator = Photon(user_agent='measurements') ip = '185.252.221.75' country,city,lat,lon = get_geo(ip) print('location country', country) print('location city', city) print('location lat, lan ', lat,lon) location = geolocator.geocode(city) print("###",location) result I am getting: location country {'country_code': 'SG', 'country_name': 'Singapore'} location city {'city': 'Singapore', 'continent_code': 'AS', 'continent_name': 'Asia', 'country_code': 'SG', 'country_name': 'Singapore', 'dma_code': None, 'is_in_european_union': False, 'latitude': 1.3024, 'longitude': 103.7857, 'postal_code': '13', 'region': None, 'time_zone': 'Asia/Singapore'} location lat, lan 1.3024 103.7857 ### Civitas Vaticana why I am getting "Civitas Vaticana" as city name instead of Singapore. I am not seeing any kind of string like "Civitas Vaticana" in my city dictionary. how to get city name? anyone please help -
How to send data through a form for processing and prevent the page from refreshing?
I am working on my first django project and I encountered a problem that I have no idea how to solve it. I have tried various code samples but unsuccessfully. I got stuck with the following problem: I have a form which looks like the following: <form action="{% url 'cart-add' %}" method="GET" id="myform"> {% csrf_token %} <label> <input type="hidden" name="{{ product.pk }}"> <input type="number" max="{{ product.quantity }}" min="1" name="quantity" value="1"> <button type="submit" value="">Add to chart</button> </label> </form> When I hit the submit button, the handler, by default, throw me to the cart page, where data is being proccessed. For a better user experience, I want when somebody click "add to cart" button, to not be thrown to another page. For this, I have tried several JQuery and javascript code snippets that I found on internet. It is still not working properly. $(document).ready(function () { $('#myform').on('submit', function (e) { e.preventDefault(); $.ajax({ url: "https://localhost:8080/product_details/" + {{product.pk}}, type: "GET", data: $(this).serialize(), success: function (data) { $("#myform").html(data); }, error: function (jXHR, textStatus, errorThrown) { alert(errorThrown); } }); }); }); The above code is the final result, but it is still not working. NOTE: When I look into page source on browser, the following script … -
How to make id (primary key) of new created objects start from some value?
I have an existing django model in my project, and it's already in production database (PostgreSQL) and has records in it. And what I basically want is to set id (autoincrement pk) of new created objects to have at least 5 digits and start from 5. So for example if I have last record in database with id 1924 I want my next object to have id 51925 (last id + 1 + 50000). So it will be like this: older objects ... 1921 1922 1923 1924 # last in production 51925 # next object to be created must autoincrement from 50001 + previous id 51926 51927 .... and so on Is it possible and what is the best way to do it? thanks