Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How change Schemes from HTTP to HTTPS in drf_yasg?
I'm using drf_yasg for swagger documentation. When I publish my DRF app behind AWS Application Load Balancer and set listener to listen on 443 HTTPS and redirect to my EC2 on which DRF is running, swagger UI is trying to send a request to endpoint http://example.com/status rather than e.g. https://example.com/status. This creates a Google Chrome error: swagger-ui-bundle.js:71 Mixed Content: The page at 'https://example.com/swagger#/status/status_list' was loaded over HTTPS, but requested an insecure resource 'http://example.com/status'. This request has been blocked; the content must be served over HTTPS. So my solution to solve this was to explicitly set my server URL in drf_yasg.views.get_schema_view. So my code looks like: schema_view = get_schema_view( openapi.Info( title="Server Api Documentation", default_version="v1", description="", url="http://example.com/status" ) # noinspection PyUnresolvedReferences swagger_patterns = [ path("", schema_view.with_ui("swagger", cache_timeout=0), name="schema-swagger-ui"), I would like to be able not to explicitly set URL string but rather choose Schemes between HTTP or HTTPS. Is it possible in drf_yasg? -
How to create nested foreign key relations in Django Rest Framework
I have multiple foreign key relationships as defined in my Models: class Order(models.Model): total_price = models.DecimalField(decimal_places=2, max_digits=4, null=False) status = models.ForeignKey(OrderStatus, related_name='order', on_delete=models.CASCADE, null=False) customer = models.ForeignKey(Customer, related_name='order', on_delete=models.CASCADE, null=False) placed_datetime = models.DateTimeField(null=False) delivery_datetime = models.DateTimeField(null=True) class Pizza(models.Model): order = models.ForeignKey(Order, related_name='pizza', on_delete=models.CASCADE) quantity = models.IntegerField(null=False) size = models.CharField(max_length=2, null=False) price = models.DecimalField(decimal_places=2, max_digits=4, null=False) class PizzaIngredient(models.Model): pizza = models.ForeignKey(Pizza, related_name='pizzaingredient', on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, related_name='pizzaingredient', on_delete=models.CASCADE) class Ingredient(models.Model): display_name = models.CharField(max_length=255, null=False) code = models.CharField(max_length=10, null=False) price = models.DecimalField(decimal_places=2, max_digits=4, null=False) My POST request will look like so: { "customer":123, "pizzas":[ { "quantity":1, "size": "M", "ingredients":[ "PEPPERONI", "GROUNDBEEF", "ONION", "GREENPEP", "PINEAPPLE", "TOMATO" ] } ] } Where the array ingredients refers to the code column in Ingredients table. On a POST of an Order, I want to create a Pizza entry and the PizzaIngredient entries. Is there an easy way to do this, or am I going have to manually create them? I currently have the following for my Order view: class OrderListCreateView(generics.ListAPIView): # GET order/ # POST order/ queryset = Order.objects.all() serializer_class = OrderListSerializer def post(self, request, *args, **kwargs): try: total_price = random.uniform(5.00, 50.00) order_status = OrderStatus.objects.filter(label='Placed').first() placed_datetime = datetime.datetime.now() customer = Customer.objects.get(id=request.data['customer']) order = Order.objects.create( total_price=total_price, status=order_status, … -
How can I construct a Django model whose fields are dependent upon another model's fields
I currently am making a simple newspaper Django application, and am working on the Articles model which looks as follows: class Article(models.Model): title = models.CharField(max_length=255) body = models.TextField() #date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) topic = models.CharField(max_length=255) score_choices = [(-5,'-5'), (-4, '-4'), (-3,'-3'), (-2, '-2'), (-1,'-1'), (0,'0'),(1,'1'), (2,'2'), (3,'3'), (4,'4'), (5,'5')] score = models.IntegerField(choices=score_choices, default=0) I am attempting to create another model that looks something like this: class Topic(models.Model): topic_name = models.CharField(max_length=255) average_score = Within the topic model, what I would like to do is somehow query all the Articles that have topic_name as their topic, and then return a list of scores that have been entered for Articles with that topic. I'm currently pretty lost on this issue and I'm not even sure anymore if using the Django models is the best route. I've been reading through the Django Documentation as well as Third-Party books for a while but I can't find any reference here. To summarize, I have two models: Article and Topic. Article has a field called 'topic' as well and I would like to create a field for my Topic class that is a function of the score field for all Article objects … -
Javascript modal to crop existing images ? how ti iterate through list of modals to handle them?
I have a page that has multiple images uploaded by user and user could select a part of these images to submit in a form ( just the coordinates x,y,h,w ) so I made a modal for every image but my problem is with the javascript function as it doesn't trigger the modal to show and I'm not really familiar with javascript yet. I use cropper.js to grab the cropping data and it loaded successfully when I tried it on a regular file upload form where there was one form in the page and the modal was triggered by the file field but now I want to use it with already existing image. the images list: <div class="row"> {% for image in Patient_detail.images.all %} <div class="col-md-4 img-box"> <div class="card mb-4 shadow-sm"> <a href="{{ image.pre_analysed.url }}" data-lightbox="patient's images" > <img src="{{ image.pre_analysed.url }}" class="img-thumbnail" id="img{{image.pk}}" > </a> <div class="card-body"> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> {% endif %} <form method="POST" enctype="multipart/form-data" action="{%url 'patients:image_crop' pk=image.pk %}" id="formUpload{{image.pk}}"> <input type="hidden" name="x" id="id_x{{image.pk}}"> <input type="hidden" name="y" id="id_y{{image.pk}"> <input type="hidden" name="width" id="id_width{{image.pk}"> <input type="hidden" name="height" id="id_height{{image.pk}"> </form> <button type ="button" class="btn btn-sm btn-outline-defaul" id="crop{{image.pk}}">Crop</button> </div> </div> </div> </div> </div> {% endfor %} </div> and the … -
How to add two def function in django
def get_total_co2_electric(self, obj): totalpieces = ElectricBike.objects.all().aggregate(total_co2_electric=Sum('co2')) return totalpieces["total_co2_electric"] # Total Co2 save by Electric def get_total_co2_classic(self, obj): totalprice = ClassicBike.objects.all().aggregate(total_co2_classic=Sum('co2')) return totalprice["total_co2_classic"] def get_total_co2(self): totalprice = (self.get_total_co2_classic() + self.get_total_co2_electric()) return totalprice I am trying to add this two def tag and get result but i am getting error "takes 1 positional argument but 2 were given" So how to add this -
Add more field in SignupForm using django-allauth
Models: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) nationality = models.CharField(max_length=20) def __str__(self): return self.user.first_name @receiver(post_save, sender=User) def create_user_profile(self, sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(self, sender, instance, **kwargs): instance.profile.save() Forms: from allauth.account.forms import SignupForm class CustomSignupForm(SignupForm): first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) class Meta: model = Profile fields = ('first_name', 'last_name', 'nationality', 'bio') def signup(self, request, user): # Save your user user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() user.profile.nationality = self.cleaned_data['nationality'] user.profile.gender = self.cleaned_data['bio'] user.profile.save() Views: ACCOUNT_FORMS = {'signup': 'all_auth.forms.CustomSignupForm',} This process isn't work. Error is: Model class all_auth.models.Profile doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. How can I solve it? Or, How can i add more field with SignupForm using django-allauth? -
How to handle Social Auth Authentication in Custom User Model?
I have a Application with custom user model,it contains 2 fields (email , username) as required fields. So to create a user, need to pass these 2 mandatory fields. I installed social_auth_django_app package, and added Google OAuth2 Login as backend authentication as well.. When I tried to login through Google I am getting an error stating that user can't be created without username field. I googled and found there is way to handle these social authentication using custom pipelines.. Can anyone help me, how to create custom pipeline and handle the above scenario for getting extra data from Google OAuth2 and assign a username field for creating a new new user..And if there are any downsides please let me know Sample Models.py class User(AbstractBaseUser): email = models.EmailField( verbose_name='Email Address', max_length=255, unique=True, ) unique_username = models.CharField( verbose_name='Username', max_length=30, unique=True, ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['unique_username',] ....... Settings.py INSTALLED_APPS = [ ...... #Social Login 'social_django', ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.github.GithubOAuth2', ........... 'django.contrib.auth.backends.ModelBackend', ) MIDDLEWARE = [ .......... # Social Login 'social_django.middleware.SocialAuthExceptionMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ .............. # Social Login 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] #Google SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = 'App ID' … -
Dependent Multiselect dropdown
I have a chained dropdown i.e.. based one the selection in one dropdown second dropdown is loaded. **Models.py** class LoB(models.Model): lob = models.CharField(max_length=200) def __str__(self): return self.lob class Meta: verbose_name_plural = "LoB" class Client(models.Model): l = models.ForeignKey(LoB, on_delete=models.CASCADE) client = models.CharField(max_length=200) def __str__(self): return self.client class Meta: verbose_name_plural = "Client" class user(model.Models): **client = models.ForeignKey(Client, on_delete=models.SET_NULL, null=True)** lob = models.ForeignKey(LoB, on_delete=models.SET_NULL, null=True) support = models.ForeignKey(Support, on_delete=models.SET_NULL, null=True) I want to add multi select for the Client dropdown? How do I go about doing this? As Client is a foreign key to my user table. This is the current outputThis is the img -
Autocomplete Address Fill in Django CreateView
Ok so I need some help. I am trying to have the address field from my CreateView form auto populate with the Places API result. So I see 2 options: Override the address field in the CreateView. Use the address input for Places API as the input into the address field for my model. Autocomplete the address field in the form, from the output of the address input (Places API lookup). Any suggestions would be greatly appreciated. I have tried multiple different options and cant seem to get it to actually work correctly. Thanks. autocomple.html var placeSearch, autocomplete; var componentForm = { street_number: 'short_name', route: 'long_name', locality: 'long_name', administrative_area_level_1: 'short_name', country: 'long_name', postal_code: 'short_name' }; function initAutocomplete() { // Create the autocomplete object, restricting the search predictions to // geographical location types. autocomplete = new google.maps.places.Autocomplete( document.getElementById('autocomplete'), {types: ['geocode']}); // Avoid paying for data that you don't need by restricting the set of // place fields that are returned to just the address components. autocomplete.setFields(['address_component']); // When the user selects an address from the drop-down, populate the // address fields in the form. autocomplete.addListener('place_changed', fillInAddress); } function fillInAddress() { // Get the place details from the autocomplete object. var place … -
how to Upload Image Using JQuery And Django
I'm trying to build a system that allows users to upload images, I'm using Django 2.1 and I follow this course [https://simpleisbetterthancomplex.com/tutorial/2016/11/22/django-multiple-file-upload-using-ajax.html][1] I'm using the exact code but it doesn't work, I don't know what is the problem may be js code is not running This is my code item_images_creation.html ```{% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{% block title %}Photos Library - Simple is Better Than Complex{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <style type="text/css"> .page-header { margin-top: 0; } </style> <script src="{% static 'js/jquery-3.1.1.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> <script src="{% static 'js/jquery-file-upload/vendor/jquery.ui.widget.js' %}"></script> <script src="{% static 'js/jquery-file-upload/jquery.iframe-transport.js' %}"></script> <script src="{% static 'js/jquery-file-upload/jquery.fileupload.js' %}"></script> <script src="{% static 'photos/js/progress-bar-upload.js' %}"></script> </head> <body> <div class="container"> <h1 class="page-header"> Photos <small></small> </h1> <div class="row"> <div class="col-md-3"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Examples</h3> </div> <a href="{% url 'item:progress_bar_upload' %}" class="list-group-item{% if request.path == '/progress-bar-upload/' %} active{% endif %}"> Progress Bar Upload </a> </a> </div> </div> </div> <div class="col-md-9"> <div style="margin-bottom: 20px;"> <button type="button" class="btn btn-primary js-upload-photos"> <span class="glyphicon glyphicon-cloud-upload"></span> Upload photos </button> <input id="fileupload" type="file" name="file" multiple style="display: none;" data-url="{% … -
How to export my django models (pycharm) to neo4j?
I have created my models in django and I want to export them to neo4j. I've been browsing for days and I have not found anything remotely useful. I'm new to python/django btw. -
Celery Django Redis - Multiple tasks same requests
I need some light about two problems that I have with an implementation with celery, Django and Redis. My code, do the follow steps: - Receive a XLS with, parse and start create (save) the users data in this file, or, I can create this user one-by-one, single request. - For each user, I send notifications (email, sms and whatsapp). - This notifications are decorated with @shared_tast (from Celery) (task 1) - There others celery tasks (as record this user in other server) (task 2) The problem 1: If XLS file have 3 users to create, just one notification is sent (start celery task). The problem 2: If I try record 1 user and call the task 1 and task 2, just one of this tasks stated). But!!! this happens only when I deploy in AWS EB, locally works fine! The Python, Celery, redis, ... is the same version. Here parts of code: ## File user_service.py ## class UserService(BaseService): def import_users(file) users_to_import = process_file() for user in users: self.save(user) def save(self, serializer, company_id=None): instance = serializer.save() self.notify_user(company_id, instance, temp_pass) return instance def notify_user(self, company_id, user_instance, password): # do a lot think! data = { ... } task1.delay(**data) task2.delay(**data) ## File … -
How to blacklist a JWT token with Simple JWT (django rest)?
I'm using Simple JWT to use JWT tokens in my Django rest API. It works great but I would like to be able to blacklist a token when a user logs out. In the documentation, it is said: If the blacklist app is detected in INSTALLED_APPS, Simple JWT will add any generated refresh or sliding tokens to a list of outstanding tokens. It will also check that any refresh or sliding token does not appear in a blacklist of tokens before it considers it as valid. The Simple JWT blacklist app implements its outstanding and blacklisted token lists using two models: OutstandingToken and BlacklistedToken. Model admins are defined for both of these models. To add a token to the blacklist, find its corresponding OutstandingToken record in the admin and use the admin again to create a BlacklistedToken record that points to the OutstandingToken record. However, I didn't find any code example and I'm not sure how this should be implemented. An example would be greatly appreciated. -
Which order i should follow to upgrade in Python, DJango and DJango-cms?
I have to upgrade my python project, Which currently running on Python 2.7/Django 1.10.8 and Django-cms 3.4.5. To version, Python 3.7 Django 2.2 Django-cms 3.7 May I know, From where I should start and is there any upgrade tools like Pylint to do this? -
Filter by a range of values of attribute
I have a model: class Product(models.Model): title = models.CharField(max_length=255) description = models.TextField(null=True, blank=True) amount = models.IntegerField() price = models.FloatField() I need to create a filter on price such that I can input a price range (i.e. min_price=10, max_price=100) and it will give me products with price in that range. Is there a way to do that in Django-admin (or Jet)? -
How to export information display in table to excel django
I want to export the information display in the template under table tag to excel. I already tried to implement code but it is now exporting the information. This is my template: <div id="info" style="padding-left: 130px"> <table class="table table-hover" style="width: 1200px;"> <thead> <tr><th> Student Name</th> <th> Attendance Mark </th> </tr> </thead> <tbody> {% for student in students %} <tr><td>{{student.studName__VMSAcc}}</td> <td>{{student.mark}}</td> </tr> {% endfor %} </tbody> </table> <a href="{% url 'exportdata' %}">export data</a> </div> my View.py @require_http_methods(["GET"]) def file_load_view(self,request): f = StringIO() writer = DictWriter(f, ["Student Name", "Attendance"]) writer.writerheader() report_line = { "Student Name" : student.studName__VMSAcc, "Attendance" : student.mark } writer.writerow(report_line) report = f.getvalue() resp= HttpResponse(report, mimetype="application/octet-stream") resp["Content-Disposition"] = "attachment; filename='{}'".format("report.csv") return resp my URLS.py url(r'^try//$', views.file_load_view, name="exportdata") How do i export the information in the table to excel sheet? Appreciate your help. THANK YOU SO MUCH! -
DRF response me by 403 error with { "detail": "You do not have permission to perform this action." } payload when I try to request as a client
In settings.py file I have written this settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } When I call any API with a token from a password grant application, then It's working fine, but when I try to call the same APIs with a token from a client credential grant application, it doesn't work and response with 403 error. Is it because of default permission? I don't know what permission do I have to use instead!? -
I'm a beginner learning python, now set django framework on ubuntu 18.04.3. but cant use django-admin
I'm a beginner learning python, now set django framework on ubuntu 18.04.3. but cant use django-admin, then need add ~/.local/lib/python3.6/site-packages/django/bin/django-admin.py to path. but I don't know where to add and how... anyone can help? -
How can i filter a manytomany field based on a foreign key?
I have a many-to-many field "tag" and a foreign key field "appName", I want to select only the tags that are related to the specific appNames. Now, when the dropdown for selection is opened it displays all the many-to-many fields irrespective of its related apps. class AppName(models.Model): appId = models.AutoField(primary_key=True) appName = models.CharField(max_length=200) appVersion = models.CharField(max_length=100,blank=True) appVersionName = models.CharField(max_length=100,blank=True) appPackageName = models.CharField(max_length=300) class Tag(models.Model): tagId = models.AutoField(primary_key=True) tag = models.CharField(max_length=300) tagDes = models.TextField() tagAddedDate = models.DateTimeField(default=timezone.now) appName = models.ForeignKey(AppName,on_delete=models.CASCADE, null=True, blank=True) class Company(models.Model): CId = models.AutoField(primary_key=True) appName = models.ForeignKey(AppName,on_delete=models.CASCADE, null=True, blank=True) tag = models.ManyToManyField(Tag,blank=True) Expected output is list of tags with respect to the appName selected. -
How to create Custom Pipeline for Social Auth Django App
I have a Application with custom model class,it contains 2 fields (email , username) as required. So to create a user, need to pass these 2 mandatory fields. I installed social_auth_django_app package, and added Google OAuth2 Login as backend as well.. When I tried to login through Google I am getting an error stating that user can't be created without username field. I googled and found there is way to handle these social authentication using custom pipelines..Can anyone help me, how to create custom pipeline and handle the above scenario for getting extra data from Google OAuth2 and assign a username field to create new user..And if there are any downsides please let me know -
how to add field dynamically in the form with django?
if this is possible then please give the solution. I think when we add the new field we need to migrate then how can we add field dynamically in form. -
How to set help_text of password fields in custom Django Allauth form?
I would like to set help_text for the password1 field in my custom SignupForm (set with ACCOUNT_SIGNUP_FORM_CLASS = 'myapp.forms.SignupForm'). The form works fine otherwise but I can't modify the password1-field since it is created when Allauth inherits from my SignupForm. My SignupForm, where I add a checkbox and adjust a few simple things: class SignupForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = Client fields = [ 'phone_number', 'pin', 'address', 'zipcode', 'city', ] widgets = { 'phone_number': phone_number_widget, } agree_to_terms = forms.BooleanField( label=mark_safe( ugettext('I agree to the <a href="/terms">terms and conditions</a>') ) ) field_order = ['name'] + Meta.fields + [ 'email', 'password1', 'password2', 'agree_to_terms' ] And in Allauths's account/forms.py: class SignupForm(BaseSignupForm): def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwargs) self.fields['password1'] = PasswordField(label=_("Password")) if app_settings.SIGNUP_PASSWORD_ENTER_TWICE: self.fields['password2'] = PasswordField( label=_("Password (again)")) ... ... Is there a way to work around this? -
Django and celery: What is the need for setting DJANGO_SETTINGS_MODULE for the 'celery' program since its already set in manage.py
While i was understanding how to use celery i found the following import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'picha.settings') app = Celery('picha') In the above code we are setting the env variable DJANGO_SETTINGS_MODULE It's the same thing we do in the manage.py def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'basic_django.settings') Since DJANGO_SETTINGS_MODULE its being set in the manage.py why to set it again in celery -
Django Template URLs and NoReverseMatch
I'm just starting out with Django and having some issues with URLs in templates. If I have my template like this the link works fine but will anger the Django puritans, apparently: <h1><a href="addNums">New Message</a></h1> but if I put it like this, as the tutorial suggests, I get a NoReverseMatch error <h1><a href="{% url 'addNums' %}">New Message</a></h1> I have the urls set up as so: urlpatterns = [ path('addNums/', add) ] What is going on here? What is the difference in semantics between the two methods? -
How to solve Uncaught TypeError: $.ajax is not a function
{% extends "users/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST" id="moviesForm" data-cast-url="{% url 'ajax_load_cast' %}" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">{{form_name|capfirst}}</legend> <div class="form-group"> <label for="id_cast" class="col-form-label requiredField">Cast<span class="asteriskField">*</span> </label> <div class=""> <input type="text" name="cast" value="" maxlength="50" class="textinput textInput form-control" required="" id="id_cast"> </div> <div id="add_cast2"></div> </div> <div id="" class="form-group"> </div> </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Submit</button> </div> </form> </div> {% block js%} <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#id_cast").keyup(function () { var url = $("#moviesForm").attr("ajax_load_cast"); var text_input = $(this).val(); $.ajax({ url: url, data: { 'text_input': text_input }, success: function (data) { $("#add_cast2").html(data); } }); }); </script> {% endblock js%} {% endblock content %} i dont know what the problem is it work fine with on change dropdown option and down't work with keyup and gives error Uncaught TypeError: $.ajax is not a function at HTMLInputElement. ((index):517)