Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CreateView not saving on submit, but is on UpdateView
I've been scratching my head on this for 2 days now, hoping someone can help me figure out what I am missing. I was able to submit before, but changed something, and I can't figure out what. When I try and add a new Client, the page just reloads, doing nothing. But when I go and edit one that is already created (using the admin console) it works as expected. views.py from django.views.generic import DetailView, ListView, UpdateView, CreateView from .models import Client from .forms import ClientForm from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import get_object_or_404 from django.urls import reverse_lazy class ClientListView(LoginRequiredMixin,ListView): model = Client def get_queryset(self): if not self.request.user.is_staff: return Client.objects.filter(sales_person=self.request.user) else: return Client.objects.all() class ClientCreateView(LoginRequiredMixin,CreateView): form_class = ClientForm model = Client class ClientDetailView(LoginRequiredMixin,DetailView): model = Client # def get_object(self): # if not self.request.user.is_staff: # return get_object_or_404(Client, sales_person=self.request.user) # else: # queryset = self.get_queryset() # obj = get_object_or_404(queryset) # return obj class ClientUpdateView(LoginRequiredMixin,UpdateView): model = Client form_class = ClientForm forms.py from django import forms from .models import Client class ClientForm(forms.ModelForm): class Meta: model = Client fields = ['first_name', 'last_name', 'street_address', 'city', 'zipcode', 'phone_number', 'email_address', 'financing_type', 'contract_amount', 'contract_pdf', 'electric_bill', 'roof_type', 'edge_of_roof_picture', 'rafter_picture', 'biggest_breaker_amp', 'electric_panel_picture', 'electric_box_type', 'main_panel_location', 'additional_notes', 'customer_informed'] urls.py from django.urls import … -
django-filter - How to parse field name with suffix such as "_id" (dynamic field names)
I would like to be able to parse a query string's params by the name as well as the value. Is this possible with django-filters or django-rest-framework? Example: /api/user/?custom_field_{id}={value} -
How can I validate if Django model has field given via GET parameter?
How can I validate if Django model has field given via GET parameter? Cannot resolve keyword 'item_typea' into field. Choices are: item_type, name, id... order_by = self.request.GET.get('order_by', None) # item_typea Item.objects.all().order_by(order_by) Note that GET parameter can has value with minus sign (it's for sorting purposes), for example: -item_type or item_type -
Afet async task executed, how can I send result to front-end?
I'm using celery + redis + django Suppose the situation is as follows : For example, create_ad is a time-consuming task for me, when I get the create_ad request from front-end, I will return a result intermediately, then I put task into redis, and handle this task back-end by using celery. My question is when the actual task executed, how can I send the result to front-end? update My main code below, if it helped # urls.py # ... # async creare_ad re_path( r'^createAdsAsync/(?P<account_id>\w+)$', CreateAdsAsyncView.as_view(), name='createAdsAsync'), # ... # views.py class CreateAdsAsyncView(NeedAccessTokenLimitView): ''' async creare_ad here ''' def post(self, request, account_id): ret = BaseResponse() status, info = BaseService.async_create_ads(request, account_id) ret.success = status ret.info = info return JsonResponse(ret.getData) # BaseService.async_create_ads def async_create_ads(self, request, account_id): task_param = { #... param } from app_management.tasks import actually_create_ads actually_create_ads.apply_async(kwargs={"task_param":task_param}) # actually call create_ads function by using celery return True, None # return result back to front-end imediately here. # app_management.tasks @app.task def actually_create_ads(task_param): # do actual work here After taks actually_create_ads finished, I want to send some return value to front-end giving some info to current login-user, What should I do to make it? Any commentary is very welcome. great thanks. -
Django rest framework social oauth2 api url and response customization
I am making an API system which follows url like localhost:8080/api/v1/end_name and i'm using django-rest-framework-social-oauth2 library for social authentication also for my custom user authentication. The problem is they are providing api response for url like localhost:8080/auth/token in following format e.g. { "access_token": "........", "expires_in": 36000, "token_type": "Bearer", "scope": "read write", "refresh_token": "......" } but i need to customize it in my way as my response format is different. My one is like following.. { "error": false, "message": "User created successfully", "data": { "email": "localtestuse2@beliefit.com" } } i need the response in my data: {}. My one question is How can I do it? My another question is Can i customize the api url localhost:8080/auth/token to localhost:8080/api/v1/auth/token? -
Django: exclude objects while checking ManyToMany Field
I'm sure someone already asked similar question but I couldn't figure out how I can do what I want to achieve. Please modify the title if there is a better title. What I want to do is like this class Game(models.Model): created_by = models.ForeignKey(User, on_delete=models>CASCADE) class User(AbstractUser): block_users = models.ManyToManyField("self", blank=True) I want to list Game obejcts but want to exclude if self.request.user is in the parent's (created_by) ManyToManyField block_users I tried to do this but it doesn't work. def get_queryset(self): return Game.objects.exclude(created_by__block_users=self.request.user) -
How to get previous data of model in forms
How to get previous data of model TrustyRequest field status. I need previous data of status field because of this condition if User.objects.filter(email=email).exists() and status=='Accepted': I want to see the previous state of status field and compare with current status which is being update - status=='Accepted'. class TrustyRequestForm(forms.ModelForm): class Meta: model = TrustyRequest fields = [ 'masjid_name', 'masjid_address', 'first_name', 'last_name', 'email', 'phone_number', 'status', ] def clean(self): cleaned_data = super().clean() email = cleaned_data.get("email") status = cleaned_data.get("status") if User.objects.filter(email=email).exists() and status=='Accepted': raise forms.ValidationError("Email Already Exists") -
fetching values from two tables based on each table having different conditions in django ORM
i have 2 models test1 and test2. i want to query status condition from test1 and progress condition in test2 . class test1: iID = models.AutoField(primary_key=True) iEID = models.BigIntegerField(_("EID"),default=0) istatus = models.BooleanField(_("Status"),default=0) class test2: iid = models.AutoField(primary_key=True) iEID = models.BigIntegerField(_("EID"),default=0) progress = models.IntegerField(_("pgs"),blank=True,null=True) i want query something like progess > 7 in test2 model and istatus = 1 in test1 model and common field for both tables is iEID -
Angular http post request appending parenthesis unexpectedly
When a request is made. i have seen that extra parenthesis are attached before the request type. like below. {"username":"demo","password":"123"}POST /authentication/ and my back-end is refusing this with error code 405 method not allowed. Back-end is in Django rest_framework and front end is in Angular 6. I don't know how to rid from these parenthesis. Either i have to look into front end, why it is appending these extra parenthesis or i have to see which middle-ware is stopping this in Django. Sample request code of angular is below: this.http.post(url, JSON.stringify(datum),{'headers':headers}).subscribe() -
where is the error in my code in ajax or in django?
i am trying to insert data into the database using django and ajax. i have a form that allow user to enter data into the text fileds and to choose between 2 options using radio button. the problem is when i try to enter the path the system display the below error : ValueError at /addperson/ The view map.views.addperson didn't return an HttpResponse object. It returned None instead. models.py class Person(models.Model): boolChoice = ( ("Male","M"),("Female","F") ) name = models.CharField(max_length=50) date = models.DateField() description = models.TextField() gender = models.BooleanField(choices= boolChoice) def __str__(self): return str(self.name) addPerson.html {% extends 'base.html' %} {% block content %} <div class="hero__content"> <form method="POST" class="form-style-9">{% csrf_token %} {{ form.as_p }} <ul> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <li> <h2>Add Member</h2> </li> <li> <input type="text" name="name" class="field-style field-split align-right" placeholder= "enter ur name " id="name"/> </li> <li> <input type="date" name="date" class="field-style field-full align-none" placeholder= " your birthdate" id="birthdate" /> </li> <li> <input type="radio" name="gender" id="male" value="male"> Male<br> <input type="radio" name="gender" id="female" value="female"> Female<br> </li> <li> <textarea name="description" class="field-style" placeholder= "introduce yourself " id="description"></textarea> </li> <li> <input type="submit" class="field-style field-full align-none" id="save" value="ADD" /> <script type="text/javascript"> $(function(){ $('#save').on('click',function(e){ e.preventDefault() name=$('#name').val() birthdate=$('#birthdate').val() description=$('#description').val() radioValue = $("input[name = 'gender']:checked").val() alert("radioValue =", radioValue) $.ajax({ url:'/addperson/', method:'POST', … -
Serializing a field of the related model in a model DRF
I have a serializer as follows: class ImageSerializer(serializers.HyperlinkedModelSerializer): prop_post = serializers.SlugRelatedField(queryset=PropertyPost.objects.all(), slug_field='pk') class Meta: model = Image fields = ( 'url', 'photo', 'prop_post', ) This works Ok. Now my PropertyPost has a title field that I need to include in my ImageSerializer. I was wondering how could I do that. I was thinking it might be like fields = ( 'url', 'photo', 'prop_post', 'prop_post__title' ) but it didn't work. Any help is apreciated -
how to combine icontains filter so it searches from one field and another at the same time
def search(request): queryset_list = Listing.objects.order_by('-list_date').filter(is_published=True) if 'keywords' in request.GET: keywords = request.GET['keywords'] if keywords: queryset_list = queryset_list.filter(description__icontains=keywords) if keywords: queryset_list = queryset_list.filter(realtor__name__icontains=keywords) I would like to be able to search 2 things at the same time. for example if description contains "big" and realtor__name doesn't I would like to still see the the object with big and same for realtor__name even if description doesn't have it I would like to get it. Thanks -
My comment reply function is not working?
I am making a blog but I am stuck on a comment replies fucntion. i DON,T KNOW HOW TO MAKE A REPLY FUNCTION FROM WHICH USERS CAN REPLY TO THe comments. I tried a lot but it,s still displaying those comments like other comments not as replies to that specific comment. Here,s the models.py def BlogDetail(request,pk): post = get_object_or_404(Post,pk = pk) comment = CommentForm(request.POST or None) subscribe = Subscribe() reply = ReplyForm(request.POST or None) if request.method == 'POST': subscribe = Subscribe(request.POST) comment = CommentForm(request.POST) reply = ReplyForm(request.POST) if comment.is_valid(): comment.instance.post = post comment.save() elif subscribe.is_valid(): subscribe = subscribe.save(commit = True) return redirect('index') elif reply.is_valid(): reply.instance.com = com reply = reply.save(commit = True) return redirect('index') return render(request,'app/blog.html',{'blog_object':post,'comment':comment, 'subscribe':subscribe,'reply':reply, }) Here,s the blog.html <form method ='POST' action="."> {%csrf_token%} <div class="row"> <div class="col-xs-12 col-sm-12 col-md-4"> <div class="col-inner ts-20 m-sm"> <input type= "submit" value = "Subscribe to my daily letter" class="btn btn-primary subscribe"> </div> </div> <div class="col-xs-12 col-sm-12 col-md-8"> <div class="ts-20"> <div class="form-group form-group-with-icon comment-form-email"> {{subscribe.email}} </form> <div class="form-control-border"></div> </div> </div> </div> </div> <h3 style = "color: #ff714a; font-weight:300;" > Leave a comment </h3> {% if request.user.is_authenticated %} <div class="comments"> <div class="row"> <div class="container"> </div> <form action="." method="post" id="commentform" class="comment-form" > {% csrf_token %} … -
How to specify maximum value for model decimal field django?
I am trying to make price field that has a maximum value. But I have seen that it is not possible to specify max value in models decimal field. Therefor I created a form decimal field which takes max value attribute but if do that I am not able to use the model's price field's properties. In models.py price = models.DecimalField(max_digits=5, decimal_places=2) In forms.py price = forms.DecimalField(max_value=500) I know I can just write all of them in forms and leave the blank and null in model's decimal field but doing that is redundant as I have many other fields. Is there a way I can use the model's decimal field and still specify the max length and min length for that field through forms class. -
how to display table generated in python through javascript
I am working on a django application. In this application a csv file can be uploaded using a form. Once the file is uploaded the csv file is displayed as a html table. I am using ajax so that the page does not reload when the form is submitted. The problem is I do not know how to call the table, which is generated using pandas in the views file, through javascript. this is my code so far views.py def on_csv_upload(request): path = './csv/' if request.method == 'POST': if 'file' in request.FILES: handle_uploaded_file(request.FILES['file'], str(request.FILES['file'])) df = pd.read_csv(os.path.join(path, str(request.FILES['file']))) table_heading = list(df.columns.values) table_content = df.to_html(classes='table table-bordered table-hover thead-dark', index=False) context = {'table_heading': table_heading, 'table_content': table_content} return render(request, 'index.html', context) index.html <form action="{% url 'csv_upload' %}" method="POST" enctype="multipart/form-data" class="mt-2 mb-2 csv_upload_form"> {% csrf_token %} <input type="file" name="file" id="file" class="inputfile"/> <label for="file" class="btn btn-outline-dark btn-lg btn-block select">Choose .csv file</label> <input class='btn btn-warning btn-lg btn-block upload_csv_button' type="submit" value="Upload file" disabled/> </form> <div class="scroll_it"> {{ table_content|safe }} </div> index.js $(document).on('submit', '.csv_upload_form', function(event) { event.preventDefault(); csvUploadAjax(); }); function csvUploadAjax() { let $form = $(".csv_upload_form"); let form_data = new FormData($form[0]); $.ajax({ url: $form.attr('action'), type: $form.attr('method'), data: form_data, dataType: 'html', processData: false, contentType: false, success: function (data) { … -
How to include data from foreign key object in Django ORM query?
I'm trying to query for an object in my DB, and get data from another object that shares a Foreign Key relationship. For example, if I have these models: class Book(models.Model): language = models.ForeignKey('Language') ... class Language(models.Model): name = models.CharField(max_length=255, unique=True) I want to query these models and get a QuerySet of books, then return the books via an API. In raw SQL I would do something akin to: SELECT book, language.name FROM book JOIN .... Is there any way to accomplish this with the Django ORM? -
Order by a queryset by number of GenericForeignKey times
I have an issue ordering queryset by number of GenericForeignKey times. Please help me. I have model Store which just sell One vehicle only: class Store(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) vehicle_type = models.ForeignKey(ContentType, related_name="vehicle_type", on_delete=models.SET_NULL, blank=True, null=True) vehicle_id = models.PositiveIntegerField(blank=True, null=True) vehicle = GenericForeignKey('vehicle_type', 'vehicle_id') vehicle is GenericForeignKey which relates to 2 models: class Bike(models.Model): name = models.CharField(max_length=20) and: class Car(models.Model): name = models.CharField(max_length=20) Example I want to get MOST BIKES TO BE SELLING (queryset of all Bikes which ordered by number of stores which selling it) -
how not to run celery task on `python manage.py test`
I have a model I am sending email and sms to user in post_save signal I am creating the model multiple times so it is sending email and sms multiple time. I am planning to write new test for testing sms and email. def send_activation_mail_sms(sender, instance, created, **kwargs): if created : mobile_activation = UserMobileActivation.objects.create(user=instance,randomword=randomword(50),ref=ref) email_activation = UserEmailActivation.objects.create(user=instance,randomword=randomword(50),ref=ref) long_url_email = "{0}view/v1/email/activation/{1}/".format(HOSTNAME,email_activation.randomword) short_url_email = url_shortener(long_url_email) url_sms = "{0}view/v1/mobile/activation/{1}".format(HOSTNAME,mobile_activation.randomword) app.send_task("apps.tasks.send_sms", args=[TEXTLOCAL_APIKEY,mobile_activation.stockuser.user.username ,'TXTLCL','Activate your mobile here {0}'.format(url_sms)]) app.send_task("apps.tasks.send_email", args=[email_activation.user.user.email, EMAIL_VERIFICATION_SUBJECT, EMAIL_VERIFICATION_TEMPLATE, {"host": HOSTNAME, "verify_email_url": url_email}]) I am passing created arg in post_save signal is there any way I can pass extra arg here so that while doing python manage.py test it will skip sending sms and email. I used versioning one way I was thinking to have different version of API for testing but as there is no request coming here I cannot catch request.version here. Please suggest. -
Docker Django Application not serving project static files but serves public static
I cannot get my site to serve my projects "base.html" template or any other project level files. It successfully serves items from the public directory and any content from the apps directory. However nothing from my "BASE_DIR". I am running this site in a docker container just internally. The django-admin loads perfectly with all its css. settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) path.append(BASE_DIR) PROJECT_ROOT = os.path.dirname(BASE_DIR) path.append(os.path.join(PROJECT_ROOT, "apps")) path.append(os.path.join(PROJECT_ROOT, "libs")) MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'public/media') MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(PROJECT_ROOT, 'public/static') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages' ], }, }, ] -
Afet async task executed, how can I send result to front-end?
I'm using celery + redis + django Suppose the situation is as follows : For example, create_ad is a time-consuming task for me, when I get the create_ad request from front-end, I will return a result intermediately, then I put task into redis, and handle this task back-end by using celery. My question is when the actual task executed, how can I send the result to front-end? -
endless loop incompatible when i pip install requirements (django1.99)
1 I get the warning msg when i pip install my django project requirements wechat-sdk 0.6.4 has requirement requests==2.6.0, but you'll have requests 2.9.1 which is incompatible. 2 then follow the tips i uninstall requests and install proper version, but i get another warning python-social-auth 0.2.21 has requirement requests>=2.9.1, but you'll have requests 2.6.0 which is incompatible. so , i'm trap in the endless loop Can anyone give an advice? -
Single Table or Multiple table for hierarchy data
I must implement this following hierarchy data: Category (id, name, url) SubCategory (id, name, url) SubSubCategory (id, name, url) NOTE that this is many-to-many relationship. EG: Each node can have multiple parents or children. There will be no circulation relationship (thank GOD). Only some SubSubCategory may belong to multiple SubCategory My implementation: I use single table for this Cat (id, type(category, subcategory, subsubcategory), name, url) CatRelation (id, parent_id, child_id, pre_calculated_index for tree retrieval) pre_calculated_index can be left right implementation of modified preorder tree traversal [1, 2] or a path in my implementation. This pre_calculated_index is calculated when add child to one node so that when retrieve a tree you only need to sort by this field and avoid recursive query. Anyway my boss argued that this implementation is not ideal. He suggest having each table for each type of category, and then have a pivot tables to link them: Category (id, name, url) SubCategory (id, name, url) SubSubCategory (id, name, url) Category_SubCategory(category_id, sub_category_id) SubCategory_SubSubCategory(sub_category_id, sub_sub_category_id) When you retrieve a tree, you only need to join all tables. His arguments is that later when you add some attribute to any category type you don't need and null field in single table … -
Inheritance of permission between the related models in DRF
I have 3 models like bellow: class CustomUser(AbstractUser): pass class PropertyPost(models.Model): owner = models.ForeignKey( get_user_model(), related_name='posts4thisowner', on_delete=models.CASCADE) class Image(models.Model): prop_post = models.ForeignKey( PropertyPost, related_name='images4thisproperty', on_delete=models.CASCADE) The idea here is that the user can post many PropertyPost and each PropertyPost can have many images. Things are working fine. My problem is in the permission. I have set a set of permissions as follows for my PropertyPostDetail views, and no permission for the ImageDetail view: class PropertyPostDetail(generics.RetrieveUpdateDestroyAPIView): ... permission_classes = ( permissions.IsAuthenticatedOrReadOnly, custompermission.IsCurrentUserOwnerOrReadOnly, ) class ImageDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Image.objects.all() serializer_class = ImageSerializer name = 'image-detail' which I meant that only the post owner can mess around with its posts. Now, because the image model is for the PropertyPost I expected that this permission carry over to the images as well. However apparantly any user can edit any image, which is obviously a flaw. My question is how could I set my image view to inherit permissions from its parent which is PropertyPost without creating an owner field for it. -
Django IntegerField in PostgreSQL getting a "numeric field overflow" error at 1000
Context: I have moved my project from a local SQLite database into an AWS RDS PostgreSQL database. It was a blank database so migrations went fine, but now that I'm testing actually saving data, I'm getting an error on an IntegerField. models.py class Item(models.Model): name = models.CharField(max_length=100) description = models.TextField(null=True, blank=True) amount = models.IntegerField(default=0) test.py testItem = Item(name="Test item valued at 1000") testItem.description = "please delete" testItem.amount = 1000 testItem.save() And so I'm getting this error: numeric field overflow DETAIL: A field with precision 5, scale 2 must round to an absolute value less than 10^3. The error is pretty obvious, I dial it back down a bit and it's fine. But I was under the impression that IntegerFields can go up to 2147483647. I have no clue why there's precision and scale involved with an integer. I'm just not quite sure what's happening, does my database think this is a decimal? I ran a fresh migration that went off without a hitch, and the field has never been a DecimalField previously. I feel like I'm probably missing something extremely simple here. -
This is so simple and really frustrating a New Rails dev from Django Python @post.userview.users << current_user
It's so simple: @post.userview.users << current_user I have this, every post has a userview, each userview has many users. How do I place the current_user into the many-to-many relationship of the views? I just want one single many to many to have a simple .add() and .remove() function like django, and I'm looking everywhere and this is all I've found. But brings up some SQL error, so it can't be right. It's suggesting I add a post_id.