Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serializer.is_valid() returns False all the time. Serializer.errors is empty
I am trying to send some image(-s) through POSTMAN to my api. However, all the time I am getting 206 status, which is returned if serializer.is_valid() is not True. Moreover serializer.errors is empty for every request It was working fine before I have added images field. MEDIA_ROOT and MEDIA_URL fields are already created. It works well using admin page of django. I am sending request using POSTMAN. Response I am getting: { "data": {} } Headers: Accept: application/json Content-Type: application/json Models.py class Order(models.Model): id = models.UUIDField( primary_key=True, db_index=True, editable=False, default=uuid4, ) city = models.CharField( max_length=50, verbose_name = (u'City'), default="NY", ) description=models.CharField( max_length=255, verbose_name=(u'desc'), default="Офигенная хата", ) price = models.PositiveIntegerField( default=0, verbose_name=(u'Price') ) requirements = models.CharField( max_length=50, verbose_name = (u'Req'), default="Clean" ) address = models.CharField( max_length=50, verbose_name = (Address'), default="Wall st" ) roommates_needed= models.PositiveIntegerField( verbose_name=(u''), default=None ) images = models.FileField( upload_to = 'pic_folder/%Y/%m/%d/', default = 'pic_folder/None/no-img.jpg', verbose_name = (img'), blank = True, ) gender_choices=( (1, u'Lady'), (2, u'Boy'), (3, u'anyone') ) roommate_gender = models.PositiveIntegerField( choices=gender_choices, default=3, verbose_name=(u'gender '),) status_choices = ( (1, u'Active'), (2, u'Not active'), (3, u'Blocked'), ) status = models.PositiveIntegerField( default=1, choices=status_choices, verbose_name=(u'Status')) owner = models.OneToOneField( 'User', on_delete=models.CASCADE, verbose_name=(u'Owner'),) def __str__(self): return self.owner.name class Meta: verbose_name = (order') verbose_name_plural … -
FOREIGN KEY constraint failed , django
I have to insert the post through a form but when i submit i got this error FOREIGN KEY constraint failed, the problem is with the author field models.py class Post(models.Model): STATUS_CHOICES = ( ('draft','Draft'), ('published','Published'), ) title = models.CharField(max_length=100) slug = models.SlugField(max_length=120) author = models.ForeignKey('auth.User',related_name='blog_posts',on_delete=models.CASCADE,blank=True, null=True) body = RichTextField() created = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft') tag = models.OneToOneField(Tag,related_name="blog_tag",on_delete=models.CASCADE,default=0) def __str__(self): return self.title views.py def tagView(request,name): tag = Tag.objects.get(name=name) post_form = PostForm(request.POST or None) if request.method == 'POST': post_form = PostForm(request.POST) if post_form.is_valid(): item = post_form.save(commit=False) item.author = request.user item.save() return HttpResponseRedirect(request.path_info) context = { 'post_form' : post_form, 'tag' : tag, } return render(request,'blog/tagPage.html',context) forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ['title','body'] template <form class="post-form" method="POST" enctype="multipart/form-data" action=""> {% csrf_token %} {{ post_form }} <input class="post-form-submit submit" type="submit" value="Save"> </form> -
POST no save to model. return "this field is required" error on Django
Hi friends I am new for Django I want to make a form with bootstrap. When I click submit Button Post Data is <QueryDict: {'csrfmiddlewaretoken': ['mjzoKZ1GPuHMCR6LQwNpUxDW0Y1KyxRgySSynPSOU7eHK8Zlm5dgqvWwhXpD3F0M'], '<input type="text" name="borclu" maxlength="36" required id="id_borclu">': ['asfasf'], '<input type="email" name="borclu_mail" maxlength="25" required id="id_borclu_mail">': ['asdasd'], '<textarea name="borcluAdres" cols="40" rows="10" maxlength="80" required id="id_borcluAdres">\r\n</textarea>': ['asdasd'], '<input type="text" name="borcluTelefon" maxlength="11" required id="id_borcluTelefon">': ['asdasd'], '<input type="number" name="tutar" required id="id_tutar">': ['asdasd'], '<input type="text" name="cek_tarih" required id="id_cek_tarih">': ['12-02-2019']}> But data no saved to model My model like that; class cekler(models.Model): borclu=models.CharField(max_length=36,verbose_name="Keşideci") borcluAdres=models.TextField(max_length=80,verbose_name="Keşideci Adresi") borclu_mail = models.EmailField(max_length=25,verbose_name="Keşideci E Posta Adresi") borcluTelefon=models.CharField(max_length=11,verbose_name="Keşideci Telefon") tutar=models.IntegerField(verbose_name="Tutar") bankalar = ( ('Ziraat Bankası', 'Ziraat Bankası'), ('YapıKredi Bankası', 'YapıKredi Bankası'), ('Vakıflar Bankası', 'Vakıflar Bankası'), ('Teb', 'TEB'), ) banka=models.CharField(max_length=20, choices=bankalar, verbose_name="Banka Adı:") cek_tarih=models.DateField(verbose_name="Çek Tarihi") son_tarih = models.DateTimeField(blank=True, null=True) def _get_gecen_gun(self): "Returns the person's full name." day=date.today()-self.cek_tarih ggun = str(day) ggun = ggun.split(' ')[0] return '%s' % (ggun) gecenGun = property(_get_gecen_gun) def __str__(self): return self.borclu def save(self, *args, **kwargs): if not self.pk: self.son_tarih = self.cek_tarih + datetime.timedelta(days=80) super(cekler, self).save(*args, **kwargs) class Meta: ordering = ['-id'] My Form.py; from django import forms from .models import cekler class CekForm(forms.ModelForm): class Meta: model=cekler fields=[ 'borclu', 'borcluAdres', 'borclu_mail', 'borcluTelefon', 'tutar', 'banka', 'cek_tarih', ] My Template <form method="post"> {% csrf_token %} <div class="container"> <div class="form-row"> … -
how to develop django-rest-framework signup using google sign in android
i have installed Django social-auth-app-django==3.1.0 for Django web for google sign in (working fine) but in same project i have installed Django rest framework and client is android app in this android app i added Firebase google sign in button when click button it shows the list of the available google account when you click one of the account android app proceed to next activity. but now my problem is how to sync(add user to db, send token if it is valid email) with Django rest framework with google sign in button from android app, i search all blog did not find solution -
why my login authentication is not working ? this code is neither redirecting me anywhere nor showing me any error
def login(request): if request.method=='POST': user = auth.authenticate(username=request.POST['username'],password=request.POST['password1']) if user is not None: auth.login(request,user) return redirect('../') else: return render(request,'login.html',{'error':'username or password is wrong'}) else: return render(request,'login.html') -
Cannot resolve keyword 'id' into field. Choices are: complete, task_priority, text, user, user_id
I am working on a Todo list which has seperate users with their own list. Initially I had the models.py as: from django.db import models from django.contrib.auth.models import User class Todo(models.Model): text = models.CharField(max_length=40, default='Test User') complete = models.BooleanField(default = False) task_priority = models.CharField(max_length=40, default='high') def __str__(self): return self.text But then when im trying to link single user with its own set of todotask(text field) and its priorites and status. I added one to one field like this: from django.db import models from django.contrib.auth.models import User class Todo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key='user_id') #new text = models.CharField(max_length=40, default='Test User') complete = models.BooleanField(default = False) task_priority = models.CharField(max_length=40, default='high') def __str__(self): return self.text It threw an error like this: FieldError at / Cannot resolve keyword 'id' into field. Choices are: complete, task_priority, text, user, user_id I didnt completely understand the concept of one to one fields and looking at the tutorials online im confused weather I need to make another table and link it to the Todo table or add another field with some primary key? Help me understand this concept. Thanks in advance. -
Very weird behaviour concerning ManyToMany filtering and combining querysets
Calendars have a owner and have a ManyToMany field 'assistants' i have a Calendar who has 2 assistants one of which is its owner. I think these 3 lines of code in the django shell can explain the weird behaviour quite well. In [17]: Calendar.objects.filter(assistants=customer).exclude(owner=customer) Out[17]: <QuerySet []> In [20]: Calendar.objects.filter(owner=customer) Out[20]: <QuerySet [<Calendar: aliz cal>, <Calendar: yassi has a calendar>]> In [19]: Calendar.objects.filter(owner=customer) | Calendar.objects.filter(assistants=customer).exclude(owner=customer) Out[19]: <QuerySet [<Calendar: aliz cal>, <Calendar: aliz cal>, <Calendar: yassi has a calendar>]> Of course expected the result of queryset join to be the actual union of them. -
How do I connect to Hbase using the functionality of Django framework
We have previously coded an appication to connect to MS Sql through django using django models which worked on MongoDB without change of code. We would like to do the same with Hbase.Previously answered questions on Stack Overflow are old , So I would like to know if presently there is any way to do this. -
How can I create model instance with CreateAPIView by post JSON
I made StudyGroup model with users. If I want to make StudyGroup with CreateAPIView, what data I have to post to create StudyGroup model? from django.db import models from django.contrib.auth.models import User class StudyGroup(models.Model): class Meta: ordering = ('created',) created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=20) users = models.ManyToManyField(User, related_name='study_groups') from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'study_groups') class StudyGroupSerializer(serializers.ModelSerializer): users = UserSerializer(many=True) class Meta: model = StudyGroup fields = ('id', 'name', 'users') from rest_framework import generics, permissions from django.contrib.auth.models import User class StudyGroupCreate(generics.CreateAPIView): permission_classes = (permissions.IsAuthenticatedOrReadOnly,) queryset = StudyGroup.objects.all() serializer_class = StudyGroupSerializer urlpatterns = [ path('create_study_group/', views.StudyGroupCreate.as_view()), ] Posted datas ("name": "created_group" was in body, and auth was OK) "users": [2, 3] // 2, 3 is userid in DB "users": 2 "users": ["A", "B"] // A, B is username in DB "users": "A" Response status=400 { "users": [ "This field is required." ] } -
how can i record date from a function to a datefield
i want to record submitted date when the submit button is clicked. the button is linked to the submit_report view. the rest works perfectly but the date is not recorded #models.ppy class Report(models.Model): createdOn = models.DateField(default=timezone.now) SubmittedOn = models.DateField(auto_now=False, null=True,blank=True) userName = models.CharField(max_length=250) weekNo = models.CharField(max_length=20) location = models.CharField(max_length=100) projectCode = models.CharField(max_length=100) totalAmount = MoneyField(max_digits=14, decimal_places=2, default_currency='ugx') flatsComment = models.CharField(max_length=300, default="") financeComment = models.CharField(max_length=300, default="") submitted = models.BooleanField(default=False) -
ORM Django Many to Many
I am trying to retrieve ONE order ID for ticket/s purchased a user made. When I put Order.objects.all()---it shows all the order ID from the Db, but I am trying to retrieve just one order ID. When I instead query: Order.objects.filter(buyer=Ticket.objects.get(id='tic_id'))----it gives me an error: invalid literal for int() with base 10: 'tic_id'. Can someone please verify if my models are correct and how to query to obtain just one order ID and not all of the order IDs? For example, it currently shows: "Your order number is 123456789101112131415" and I am aiming it to show "order number is 11"; Thank you, I appreciate your patience! models.py class User(models.Model): first_name=models.CharField(max_length=100) last_name=models.CharField(max_length=100) email=models.CharField(max_length=100) password=models.CharField(max_length=100) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) class Ticket(models.Model): venue=models.CharField(max_length=100) quantity=models.PositiveIntegerField() price=models.DecimalField(default=25.00, max_digits=5, decimal_places=2, null=True, blank=True) loop=models.CharField(max_length=100) purchaser = models.ForeignKey(User, related_name="purchases", on_delete=models.PROTECT) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) class Order(models.Model): full_name=models.CharField(max_length=100) cc_number=models.PositiveIntegerField() exp_date=models.PositiveIntegerField() cvc=models.PositiveIntegerField() buyers=models.ManyToManyField(Ticket, related_name="bought_tickets") created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) views.py def process(request): Order.objects.create(full_name=request.POST['full_name'], cc_number=request.POST['cc_number'],exp_date=request.POST['exp_date'], cvc=request.POST['cvc']) return redirect('/checkout') def checkout(request): context={ "user":User.objects.get(id=request.session['user_id']), "tickets": Ticket.objects.filter(purchaser=User.objects.get(id=request.session['user_id'])).annotate(total=Sum(F('quantity') * F('price'), output_field=FloatField())).annotate(tax=ExpressionWrapper(F('quantity') * F('price')*0.0725, output_field=FloatField())).annotate(total_price=ExpressionWrapper(F('quantity') * F('price') + F('tax'), output_field=FloatField())), "order":Order.objects.filter(buyer=Ticket.objects.get(id='tic_id')) } return render(request, 'first_app/checkout.html', context) checkout.html <p class="lead">Your order number is:<strong>{% for o in order %}{{o.id}}{% endfor %}</strong><p class="lead">with ticket number:</p><strong>{% for ticket in tickets %}{{ticket.id}}{% endfor %}</strong> -
Django: Get a list of all related objects in models.py
it's a stupid question but i'm new to django and I didn't find a answer so far. I'm trying to get a list of all related Years in the get_savings function. Don't look at the attributes of Year and Plan. They all exist. The focus is on the For loop. I also tried for year in self.year_set.all: but it didn't work eather. models.py class Plan(models.Model): title = models.CharField(max_length=50) ... @property def get_saving(self): delta: timedelta = now() - self.date_created months_gone = delta.days / 30 saving = 0 for year in Year.objects.all(): if months_gone > year.months: saving: saving + year.savings_year else: saving: saving + months_gone * year.income_month return saving class Year(models.Model): title = models.IntegerField() ... plan = models.ForeignKey(Plan, on_delete=models.CASCADE) -
How to keep an Object between calls without using sessions in Django?
I'm configuring MangoPay for my web application and it's now time for credit card registration. I'm using the python SDK that MangoPay recommends. The workflow requires a CardRegistration to be created on the backend, which can be used to generate a form in the front end. On this form the user adds the credit card details, which are sent to a 3rd party tokenisation service and returned to the users front end. This token can be sent now to my backend and, added to the CardRegistration object, can be saved enabling the card for the user. My issue is that I don't know how to store CardRegistration object between calls in the backend while I wait for the user to generate the token and return it. Sessions can not be used, as the preregistration object contains sensitive data. To prove if it would have worked and I tried to use pickle but it raises a PicklingError, so serialization and storage doesn't look like an option either. What should I look into? Is there some kind of design pattern I can use to store the object quickly for retrieval? -
How to overcome cold start issue in aws?
I have deploved api (Django application) in AWS using zappa. I'm facing cold start issue. It is taking nearly 7-8 sec to start application (code is nearly 25 MB ).How to overcome this issue ?? In zappa settings.json , i have kept keep_warn=True but of no use. I have written lambda function to trigger api, it is triggering ( i can see in zappa logs ) but problem not solved. sample code of my handler is : import json def lambda_handler(event, context): # TODO implement return { 'statusCode': 200, 'body': json.dumps('Hello from Lambda!') } -
How to import photo from excel with django import-export?
I want to upload image using django-import-export using excel. without image its working fine but i have binary image data in my excel sheet and i want to import data from excel with photo to django. -
convert a list of dictionaries into a django accessible object
I am executing a SQL query in a django function like this: cursor.execute('''Select * from classroom_quiz as cq, classroom_activetruck as ca where cq.origin=ca.origin and cq.destination=ca.destination and cq.subject_id=ca.subject_id and cq.total_trucks<=ca.total_trucks;''') invoices = dictfetchall(cursor) and this gives me output in this form: [{'id': 15, 'name': 'test', 'origin': '0', 'destination': '0', 'total_trucks': 7, 'material_type': 'Fragile', 'scheduled_date': '0', 'offered_price': 0, 'owner_id': 1, 'subject_id': 1}, {'id': 1, 'name': 'truck', 'origin': '0', 'destination': '0', 'total_trucks': 5, 'material_type': 'Fragile', 'scheduled_date': '0', 'offered_price': 0, 'owner_id': 1, 'subject_id': 1}] How can I use this list of tuples so that I can project it on the output screen of my app ? One way I can think of is to convert it into a django object but that's just a hunch. -
Python/Django django.contrib.auth.models.User.userprofile.RelatedObjectDoesNotExist: User has no userprofile
Recently, my project needs to build a book lending system. I found an example on GitHub and wanted to use it as an example. When I tested this example, I found that I always failed to borrow books. How can I solve this problem? https://github.com/sxfs-github/BookBorrowPy django.contrib.auth.models.User.userprofile.RelatedObjectDoesNotExist: User has no userprofile. I wish I could show the success of borrowing books, but in fact it always shows the failure of borrowing books. -
Return URL in POST-method when working with base64ImageField and nested serializers
First of all, I'm pretty new to Django and equally new to backend development so please go easy on me. I'm setting up a backend for a mobile application in which a user should be able to post an advert with an image attached to it over Http Requests. Right now, this works like it should, a user sends a POST request containing all the needed information and gets a response back containing all the relevant information, except for the image which is null. I know that the image successfully gets uploaded to the server, however I can't figure out how to return the URL of the image back into the response. The following is my code: models.py class Advert(models.Model): owner=models.ForeignKey(User, on_delete=models.CASCADE, related_name="adverts") book_title = models.CharField(max_length=250) price = models.PositiveSmallIntegerField() created_at = models.DateTimeField(default=now()) def __str__(self): return self.book_title + ' - ' + self.contact_info class AdvertImage(models.Model): advert = models.ForeignKey(Advert, on_delete=models.CASCADE, related_name="image", null=True) image = models.ImageField(upload_to = 'ad_images', null=True) def __str__(self): return self.image.name My serializers looks as following: serializers.py from rest_framework import serializers from .models import Advert, AdvertImage from drf_extra_fields.fields import Base64ImageField from django.contrib.auth.models import User class AdvertPostSerializer(serializers.ModelSerializer): image = Base64ImageField(max_length=None, use_url=True, required=False) class Meta: model = Advert fields = ( 'id', 'price', … -
How to asses dicts key with django models in template?
code as below, I want to use item in models as dictionary's key in html page but I can't asses 2 layer django template ... MODELS.PY: class models (models.Model): m= models.CharField(max_length=1, default='k') ... VIEW.PY: mydict = {"k":"v"} ... HTML: {% for model in models %} my dict key is : {{model.m}} //hope to show "k",and use it as my dictionary's key my dict value is :{{mydict.{{model.m}} }} //hope to show "v" but fail {% endfor %} ... -
How to get next pages in load more django
I get data using ajax with button load more, and if it's not have next pages, it will render "all data has been displayed" index.html <div class="panel-body"> <div id="display-data"> <span id="loading-help">Loading data. . .</span> </div> </div> <script> var page = 1 $(document).ready(function(){ $.get("{% url 'account:profile' %}?param=get_data&page="+page, function(data){ $("#display-data").append(data) $("#loading-help").remove() page++ }) </script> data-ajax.html {% for data in datas %} <div class="list-trx-data"> <div class="row align-items-center"> <div class="col-md-8"> <div class="row align-items-center"> <div class="col-md-4 col-sm-12 col-12 data-date"> {{data.get_formatted_date}}</div> <div class="col-md-8 col-sm-12 col-12 data-name"> <a href="#">{{data.get_data}}</a></div> </div> </div> <div class="col-md-4"> <div class="row align-items-center"> <div class="col-md-6 col-8 data-amount"> {{data.get_formatted_amount}}</div> <div class="col-md-6 col-4 "> <div class="data-progress"> <div class="pg-bar" style="width: {{data.get_data.get_progress_str}}"></div> </div> </div> </div> </div> </div> </div> {% endfor %} {% if datas.has_other_pages %} {% if datas.has_next %} <a href="javascript:void(0)" class="btn btn-ghost btn-block mt-2" id="load-more-btn">Load More</a> {% else %} <a href="javascript:void(0)" class="btn btn-ghost btn-block mt-2" id="load-more-btn">All data has been displayed</a> {% endif %} {% endif %} <script> $("#load-more-btn").click(function(){ $.get("{% url 'account:profile' %}?param=get_data&page="+page, function(data){ $("#display-data").append(data) page++ }) }) </script> I have try it but it's render all button before click load more after click load more how to fix it ? -
Query errors in a panda Dataframe
I am facing an issue with my code using queries on simple pandas DataFrame, I am sure I am missing a tiny detail. Can you guys help me with this? I don't understand why I've only NAN values. Thank you for your help, Best -
Why the elasticsearch highlight did not work?
I try to highlight the result of my searching using elasticsearch. Unfortunately, somehow it did not work. This is my code: def page_results(request, page_id): s = Search(using=Elasticsearch()) keyword = request.GET.get('q') if keyword: posts = s[start:end].query( "multi_match", query=keyword, fields=['head_title^4', 'description^3','url^5', 'description.ngram'], ) posts = posts.highlight('description') -
Simulate CSRF Attack on Login Required URL
I want to simulate/demo a CSRF attack. With Django, I setup a site (a.com) and one url (/foo/) do not enable anti-CSRF stuff. First I made this URL can be access without login. I can see the POST request (see code below) is done succeed. (Actually, I met a no Access-Control-Allow-Origin issue, the document #main content is not updated. But the post is done with 200 status. i.e. The Money is transferred to my account :). So I did a successful CSRF attack. Then I make a.com/foo/ wrapped in a login_required(), which means, you need first login on site a.com before to do actions in a.com/foo/ page. 1) I did a login on one Chrome tab of a.com. 2) And then I open another Tab in this same Chrome window and open localhost:8000 (see below). When I run the JS function, the POST begin to get 403 (redirecting to login page of a.com instead of the 200 OK status before). Why? If this is the case, How CSRF attacks is useful/possible for login-required pages of another domain? JS Code to do the Fake request (from localhost:8000 etc, a different domain): function hack_it() { var http = new XMLHttpRequest(); var url … -
Permission Role using Django Admin
I have created a model forms in Django. In the Django admin site, I created 2 users and added it to the Group permission. As an Superuser, I want some fields to be DISABLE in forms for the 2 users. How do I achieve that? -
Django select_for_update() for arbitrary object
I want to make an atomic update an object whose type may vary. The structure looks something like this: class MyMixin(models.Model): size = models.BigIntegerField(null=False, default=0) class SubClassA(MyMixin, models.Model): <...> class SubClassB(MyMixin, models.Model): <...> # obj is of type SubClassA or SubClassB def some_func(obj): with db.transaction.atomic(): # obj = SubClassA.objects.select_for_update().get(id=obj.id) # How do I do this? new_size = calculate() obj.size = new_size obj.save() All of the examples I can find explicitly use the <Class>.objects.select_for_update() pattern but my problem is I don't know what the class will be at runtime. In my code, I already have an instance of the object/model but I need to re-fetch it from the database in order to lock it. I'm trying to draw ideas from the "Pessimistic approach" found in this guide - https://medium.com/@hakibenita/how-to-manage-concurrency-in-django-models-b240fed4ee2 Should I put a very simple method in MyMixin which allows me to set and save the size? Or I could explicitly check the type of the obj at runtime and have a bunch of elifs (to do something like if/elif type(obj) == SubClassA: SubClassA.objects.select_for_update()...)but that's both ugly and not very maintainable.