Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why does i got error in recaptcha in setting module in django?
when i used settings in Django,i got error because of using captcha in setting package def grecaptcha_verify(request): data = request.POST captcha_rs = data.get('g-recaptcha-response') url = "https://www.google.com/recaptcha/api/siteverify" params = { 'secret': settings.RECAPTCHA_SECRET_KEY, 'response': captcha_rs, 'remoteip': get_client_ip(request) } ``` when i used this method i got error in AttributeError: Settings object has no attribute RECAPTCHA_SECRET_KEY -
Django, how to put database object on a choicefield form
so I have a form that contain a choiche field, I wanna put all the item of my database in that choichefield, how can I do that? thanks for help! (The form is not a models form cause I dont need to edit or change the data) models.py class List(models.Model): item = models.CharField(max_length=100) content = models.TextField() site = models.CharField(max_length=11, choices=THE_SITE) content_list = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.item forms.py data = [ ("LIST1", "LIST1"), ("LIST2", "LIST2") ] class sms_form(forms.Form): list_data = forms.ChoiceField(choices=data) message = forms.CharField(widget=forms.Textarea) -
Problem connecting redis and django in GCP
I have deployed a Redis instance using GCP Memorystore. I also have a django app deployed using App Engine. However, I am facing problems connecting these 2. Both are deployed in the same timezone. The package that I'm using is django_redis The error is: Exception Value: Error 110 connecting to <Redis instance IP>:6379. Connection timed out. Exception Location: /env/lib/python3.7/site-packages/redis/connection.py in connect, line 557 In settings.py I use: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("<Redis instance IP>", 6379)], }, }, } CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": 'redis://<Redis instance IP>/0', "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" } } } -
Is there a way to only load javascript files when certain pages are loaded using Django?
I am making a Django website. I am not an expert but I understand the basics. However I am a complete rookie when it comes to javascript. I am using Django Templates to have each page on my website 'inherit' from a Base page (base.html). I want to include Javascript within a script tag of the base page that will only load when a certain page is loaded. I want to do something like this: {% load static %} <!DOCTYPE html> <html lang="en"> <head> ... ... </head> <body> ... <!-- Main Content --> {% block content %} {% endblock %} ... <script> Some Script on every page </script> <!-- Some Django if statement like the one below goes here --> {% if this_page == '/special_page/' %} <!-- a special script is loaded here --> <script> Special Script </script> {% endif %} </body> </html> I am not sure if this can be done. Can this be done, and if so, is it a security risk? -
Jquery update cart function not sync with Django backend database
I am trying to create a Django eCommerce, and I find a js fiddle where the cart update (increase and decrease operation with final cart calculation) is shown. I am trying to integrate that code with my project. It workes but unfortunately I am not able to syce with my backend database. That means it only working with HTML but not updating my underlying database or in server. I am trying to grab the "data-item-id="{{cart_item.item.id}}"" in the jquery section. but not succeed. i think by grabbing the data-item-id="{{cart_item.item.id}}" can solve the problem. I don't know much js or jquery, so this is a real headache for me. here is my code detail. The exact fiddle that i am following is https://jsfiddle.net/1Lb430o8/18/ Everything is worked but only in the HTML part not in the backend, and that is what I need.So how can it worked with django in the backend? {% block jquery %} var taxRate = 0.15; var shippingRate = 20.00; var fadeTime = 300; $(document).ready(function() { recalculateCart(); }); //On click Plus button $(document).ready(function() { $(".cart-qty-plus").click(function() { var $n = $(this) .parent(".button-container") .parent(".product-quantity") .find(".qty"); $n.val(Number($n.val()) + 1); updateQuantity(this); }); }); // On click minus button $(document).ready(function() { $(".cart-qty-minus").click(function() { var … -
creating windows executable django restful application
I have written a django restful application w/ postgres DB, this application is supposed to be working online over cloud. But I want to add a feature which enables the user to be able to use the application (some features) in case he lost his internet connection then after internet is back I will sync the modifications in DB data with the DB on the cloud. So I want to install the application on his PC in the form of executable EXE file. How can I accomplish this please? -
Create and save django object on click
I have a shoppinglist app. I want that when the user clicks on "add to shopping list" the item is saved to the shopping list. How can I do that? in the template I wrote: <a href="javascript:{document.getElementById('add_item').submit()}" class="btn btn-primary btn-block">Add to shopping list </a> <form action="{% url 'add_to_shopping_list' product.id %}" id="add_item" method="POST"> {% csrf_token %} <input type="hidden"> </form> in urls.py I dispaced the urls like this: urlpatterns = [ path('add_to_shopping_list/<int:pk>', views.add_to_shopping_list, name='add_to_shopping_list'), ] this calls the view add_to_shopping_list where I want create a ShoppingItem object and to link this to the Product object. The problem is that I don't want to redirect the user anywhere, but just stay on the same page without refreshing. But the view wants me to return an HtmlResponse, or I get this error: The view shoppinglist.views.add_to_shopping_list didn't return an HttpResponse object. It returned None instead. Is the idea correct? If yes how can I solve this problem? Thanks -
DRF adding images to a ForeignKey already in the database
I am looking to add Images, to a Listing(ForeignKey), which will already be in my database. I have an Image model.. class Image(models.Model): photo = models.ImageField(blank=True, upload_to=get_image_filename) listing = models.ForeignKey(Listing, on_delete=models.CASCADE) ImageSerializer class ImageSerializer(serializers.HyperlinkedModelSerializer): photo = serializers.ImageField(allow_empty_file=True) class Meta: model = Image fields = ('url', 'photo', 'listing', ) ImageViewSet class ImageViewSet(viewsets.ModelViewSet): queryset = Image.objects.all() serializer_class = ImageSerializer detail_serializer_class = ImageDetailSerializer parser_classes = (FormParser, MultiPartParser) '''Show detailed Image view''' def get_serializer_class(self): if self.action == 'retrieve': if hasattr(self, 'detail_serializer_class'): return self.detail_serializer_class return super(ImageViewSet, self).get_serializer_class() I have tried overriding the create method in the serializer, and perform_create method in the actual viewset. But keep running into errors. Any advice in the right direction would be awesome]1 -
How saving data rows using loop form to save data in django?
I'm trying to save data from input form using django 3.0.3 throw loop form, the problem is when i enter the data into form only the second row saved and repeated in database. This is my code: models.py from django.db import models from datetime import datetime class NumberOfStudent(models.Model): class_num = models.CharField(max_length=100) num_of_student = models.IntegerField() student_abscence = models.IntegerField(default=0) date = models.DateTimeField(blank=True, default=datetime.now) def __str__(self): return self.class_num views.py from django.shortcuts import render, redirect from .models import NumberOfStudent from .forms import Insertdata def home(request): # Number of class's room for Grade 11 num_class_11 = 2 # Check if method of from is post if request.method == 'POST': insertdata = Insertdata(request.POST) # Chck if data inserted is valid if insertdata.is_valid(): for instance in range(num_class_11): instance = insertdata.save(commit=False) instance.pk = None instance.save() return redirect(data) else: insertdata = Insertdata() context = { 'title': 'Home Page', 'num_class_11': num_class_11, 'range': range(num_class_11), 'insertdata': insertdata, } return render(request, 'hello/home.html', context) def data(request): class_11 = NumberOfStudent.objects.all() context = { 'class_11': class_11, } return render(request, 'hello/data.html', context) forms.py from django import forms from .models import NumberOfStudent class Insertdata(forms.ModelForm): class Meta: model = NumberOfStudent fields = ('class_num', 'num_of_student', 'student_abscence') index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> … -
Django pop up message (modal) after the user updating form
What should I do if the user updates their data with a successful message pop-up? for my case it needed to new tab to see the successful message after the user update their data, i would like to pop up the message instead of the new tab page to see the successful message I have this code on my html <form method="post" action="/reactivate/" id="your-form" enctype="multipart/form-data" autocomplete="on" class="btn btn-info modal-ajax-load" data-ajax-link="url" data-toggle="modal" data-modal-title="tilte" data-target="#general_modal">{% csrf_token %} {% for me in ako %} Date: <input type="hidden" value="{{me.enddate}}" name="date" id="start_date">{{me.enddate}} <input type="hidden" value="{{me.id}}" name="id" hidden><p>{{me.Email}}</p> {% endfor %} <select id="days"> {% for perfume in s %} <option value="{{perfume.adddate}}" data-days="{{perfume.adddate}}" id="days">{{perfume.product}} - {{perfume.adddate}} Days</option> {% endfor %} </select> <br><br><br> <label>Deadline:</label><br> <input type="date" name="endate" id="end_date" readonly/> <input type="submit" value="Sign up" /> </form> <div id="general_modal" class="modal fade " > <div class="modal-dialog "> <div class="modal-content "> <div class="modal-header bg-info"> <h6 class="modal-title">Info header</h6> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> <!-- Empty will be field by Js --> </div> </div> </div> </div> this is my script <script> $("#your-form").on('submit',function(e){ e.preventDefault(); var ajax_link = this.getAttribute("data-ajax-link"); var target = this.getAttribute("data-target"); var title = this.getAttribute("data-modal-title"); var size = this.getAttribute("data-modal-size"); var bg = this.getAttribute("data-modal-content-bg"); // $(target+" .modal-body").load(ajax_link); $.ajax({ url:ajax_link, type:'POST', // data: $("#your-form-feilds").serialize(), … -
How to make list_editable show or hide for different user in django admin based on user role?
There is no get_list_editable function unlike get_fields. I want to make list_editable show or hide to different user based on permission given to user in Django admin. Is there any way to hide or show list_editable to different user in Django admin -
Why the django models clean() method doesnt work
I'm trying to overwrite the value of the DateField field if it's empty. As usual, a field with this type is not validated during serialization if the value is not an object of datetime class. I need to write null to the database if the value is empty. To do this, I'm trying to change the clean() model method. serializer.py class VendorsSerializer(serializers.ModelSerializer): contacts = VendorContactSerializer(many=True) class Meta: model = Vendors fields = ('vendor_name', 'country', 'nda', 'contacts',) def create(self, validated_data): contact_data = validated_data.pop('contacts') vendor = Vendors.objects.create(**validated_data) vendor.full_clean() for data in contact_data: VendorContacts.objects.create(vendor=vendor, **data) return vendor models.py class Vendors(models.Model): ... nda = models.DateField(blank=True, null=True) def clean(self): if self.nda == "": self.nda = None view.py class VendorsCreateView(APIView): """Create new vendor instances from form""" permission_classes = (permissions.AllowAny,) serializer_class = VendorsSerializer def post(self, request, *args, **kwargs): serializer = VendorsSerializer(data=request.data) try: serializer.is_valid(raise_exception=True) serializer.save() except ValidationError: return Response({"errors": (serializer.errors,)}, status=status.HTTP_400_BAD_REQUEST) else: return Response(request.data, status=status.HTTP_200_OK) Why clean() doesnt run ? -
The "Include" directory missing from the virtualenv
I installed a virtual environment on Ubuntu 18.04 OS by using the commands: > Installed pip first: sudo apt-get install python3-pip > Install virtualenv using pip3: sudo pip3 install virtualenv > Created a virtualenv: virtualenv env The "env" folder includes only the "bin" and "lib" folders. Where did I exactly go wrong? -
Is there a programmatic way to access a list of all "sets" in a model?
I have three models class Risk(models.Model): notes = models.TextField() ... class Component(models.Model): risk = models.ManyToManyField(Risk) ... class ReportComponent(models.Model): risk = models.ManyToManyField(Risk) ... And right now I'm doing the following: def parent_component(self): print(self.component_set.all()) print(self.reportcomponent_set.all()) Is there a way to dynamically inspect all the available ..._set properties? -
How to effectively embed Python code into Django
Guys how to embed efficiently python code into Django. I have a Django template where it takes value from user, then the request goes to DB and look for the value. Also I have my python code with formulas with values that are based on number retrieved from the DB. view.py def home(request): if request.method == 'POST': form=PersonForm(request.POST) if form.is_valid(): form1=form.save(commit=True) name=form1.name obj=School.objects.get(student=name) context={ 'object':obj } return render(request, 'book/analysis.html', context) else: form = PersonForm() return render(request, 'book/search.html', {'object':obj}) In the past I used to insert python code inside this home(request) function, however my code is bit lengthy and I would like to create separate file and insert there. What worries me is in my python code I define values such as formula.py math_score_final=object.math math_score_final=object.biology final=(math_score_final+math_score_final)/2 Is this a correct way to do it? How would you advice to reorganise my code to make the web function smoothly? Would appreciate your insight on this matter. -
Setting up a foreign key relationship in Django using postgreSQL
I want to model the following entity relationship in Django using PostgreSQL: --------- ------------------ --------------- |objective|----1:Many---- |objectiveToAccount| ----Many:1----|acounts_account| --------- ------------------ --------------- Objective and Accounts are 2 different Django applications and I am using this code to have create my table data structure: # models.py Objective from django.contrib.auth import get_user_model # Import the user model from the Accounts application User = get_user_model() class Objective(models.Model): id = models.AutoField(primary_key=True) objective = models.CharField(null=False, max_length=60) initial_date = models.DateField(default=timezone.now(), null=False) expiration_date = models.DateField() users = models.ManyToManyField(User, through='UserToObjective', through_fields=('user','objective'), related_name='objectives') class UserToObjective(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, db_column='id', on_delete = models.PROTECT) objective = models.ForeignKey(Objective, db_column='id', on_delete = models.PROTECT) ----------------------------------------------------------------------------------- # models.py Accounts class Account(AbstractBaseUser): id = models.AutoField(primary_key=True) email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True ----------------------------------------------------------------------------------- However, when I applied the migrations with python manage.py makemigrations I encounter the following error: objective.Objective.users: (fields.E339) 'UserToObjective.objective' is not a foreign key to 'Account'. HINT: Did you mean one of the following … -
Django error "argument of type 'ForeignKey' is not iterable"
The following code is erroring on the line indicated (near the end with "<==="), or possibly on the line after that: class InspectModelUpdated(InspectModel): """ Updated for compatibility with Django 1.10 + Replaced the get_all_field_names and get_field_by_name methods, which have been removed from the Model._meta API. https://docs.djangoproject.com/en/2.0/ref/models/meta/#migrating-from-the-old-api """ def update_fields(self): """Set the list of django.db.models fields Three different types of fields: * standard model fields: Char, Integer... * relation fields: OneToOne (back and forth), ForeignKey, and GenericForeignKey * many fields: ManyToMany (back and forth) """ self.fields = set() self.relation_fields = set() self.many_fields = set() opts = getattr(self.model, '_meta', None) if opts: for field in opts.get_fields(): model = field.model direct = not field.auto_created or field.concrete m2m = field.many_to_many if not direct: # relation or many field from another model name = field.get_accessor_name() field = field.field <============== jr_rel = field.rel if 'rel' in field else field.remote_field if jr_rel.multiple: # m2m or fk to this model self._add_item(name, self.many_fields) else: # one to one self._add_item(name, self.relation_fields) I added a debug dump just before this line, to output the attributes of field, and for one example of the error it output: in update_fields() - vars(field) = { 'field' : <django.db.models.fields.related.ForeignKey: survey>, 'model' : <class 'app.survey.models.survey.Survey'>, 'related_name' … -
TemplateDoesNotExist at /inventory/render_results/ error message in django
I am using code that I've used before but it is throwing an error, 'TemplateDoesNotExist at /inventory/render_results/' and I cannot find the typo or logic miss. The template does exist and when I review the code, the query is performing correctly. I'm at a loss. search_device.html <form action="{% url 'inventory:render_results' %}" method="POST" > {% csrf_token %} <body> <table> <tr> <td><b>Locations: &nbsp;&nbsp; </b></td> <td> <select name="location_name"> {% for locations in locations %} <option value="{{locations.location_name}}">{{locations.location_name}}</option>{% endfor%} </select> </td> <td><input type="submit" value="Submit"/></td> </tr> </table> render_results.html <html> <h2 align="left">Render Device List based on Location Choice</h2> <b> Locations:&nbsp;&nbsp; </b><br>{{locations }} <br><br><br> <b> Devices: &nbsp; &nbsp; </b><br> {% for device in devices %}{{device.device_name}} <br>{% endfor %} </td> <br> <button type="submit" id="save">Save</button> </html> views.py def render_results (request): location_name = request.POST.get('location_name') my_devices = Devices.objects.filter(locations = Locations.objects.get(location_name = location_name)) context = {"devices": my_devices, "locations": location_name} return render(request, 'inventory/render_results.html', context) def search_device_list(request): locations = Locations.objects.all() print(locations) context = {"locations": locations} for locations in context['locations']: print(locations) location_name=request.POST.get('location_name') if request.method == 'GET': form = LocationsForm() print(locations) return render(request, 'inventory/search_device_list.html', context) and finally urls.py ... url(r'^search_device_list/$', views.search_device_list, name='search_device_list'), url(r'^render_results/$', views.render_results, name='render_results'), -
Trouble installing django-tracking
I'm trying to install django-tracking but I'm getting a few errors settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_cleanup.apps.CleanupConfig', 'tinymce', 'crispy_forms', 'tracking', 'main', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'tracking.middleware.VisitorTrackingMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] pip install django-tracking Output: ModuleNotFoundError: No module named 'listeners' I tried installing listeners with no luck Then I tried pip install git+https://github.com/bashu/django-tracking.git but when I run python manage.py runserver I get from django.contrib.gis.geoip import GeoIP, GeoIPException ModuleNotFoundError: No module named 'django.contrib.gis.geoip' -
Understanding request.POST receive time in django
I am currently facing an issue regarding the exact time of the data received by django post method. Can anyone tell me when the post method starts for receiving file from client side in django? Like does the method starts when the first byte of file is received or after the whole file is finished receiving? I am talking about large file like 3-7 MB sized image. And I have the same question for django rest framework. Cause in rest framework I have found that calling as api from android app it takes a lot of time to response like about 6 to sometimes even 30 sec. Whereas the same file is taking 0.01-0.08 sec for normal django view function. -
Link CSS static to Django
I am pretty new to Django and I do not know how to link CSS to my project. I have added the static on the settings of the app as below, it works fine when trying to locate a picture on the static folder but it doesn't seem to find the CSS files: STATIC_DIR = os.path.join(BASE_DIR, 'static') INSTALLED_APPS = [ 'django.contrib.staticfiles',] STATIC_URL = '/static/' STATICFILES_DIRS = [STATIC_DIR, ] on my HTML for CSS facing issues: <link rel="stylesheet" href="{% static 'css/mycss.css' %}"> Any ideas what i am doing wrong ? Thank you advance -
DRF - M2M through serializer for ImageField gives UnicodeDecodeError
I want to serialize a model using M2M through relation. Its working fine for all other fields except ImageField. Below are my model and serializer files: models.py class Product(models.Model): name = models.CharField('Name', max_length=255, null=True, blank=True) description = models.TextField('Description', max_length=1000, null=True, blank=True) price = models.IntegerField('Price', default=0) image = models.ImageField('Product Image', null=True, blank=True) class Cart(models.Model): user = models.CharField('User ID', default="1000", max_length=255) items = models.ManyToManyField("Product", through='CartActions', blank=True) modified = models.DateField('Last Modified') class CartActions(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE) cart = models.ForeignKey('Cart', on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField(default=0) serializers.py class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Product fields = ['id', 'name', 'description', 'price', 'image'] class CartSerializer(serializers.HyperlinkedModelSerializer): items = CartActionsSerializer(source='cartactions_set', many=True) class Meta: model = Cart fields = ['id', 'user', 'items'] class CartActionsSerializer(serializers.HyperlinkedModelSerializer): name = serializers.ReadOnlyField(source='product.name') price = serializers.ReadOnlyField(source='product.price') image = serializers.ReadOnlyField(source='product.image') # Adding this line gives error class Meta: model = CartActions fields = ['name', 'price', 'image', 'quantity'] This is the error I'm getting when hitting the API: UnicodeDecodeError at /store/api/cart/ 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte This is the sample response I'm getting from /api/products API: { "id": 1, "name": "Product 1", "description": "This is a sample description", "price": 500, "image": "http://192.168.43.210:9000/media/sample_product.jpeg" } I've tried almost all references in stackoverflow and … -
Match users on django backend and amipitude
I want to match users on amplitude and Django back-end database(PostgreSQL). For example, on PostgreSQL database user id is 13, on amplitude user id is 1425362. Is there any way to match user ids or to link them ? -
I couldn't open the 'about.html' when using return render in views.py
Sorry that I am new in Django, as I am creating a website and try to use generic way, but when I use the way for return render, it can't open the related html file(about.html), someone help? views.py: from django.shortcuts import render from django.views import generic from .models import Post # Create your views here. class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on')[:4] template_name = 'index.html' class PostDetail(generic.DetailView): model = Post template_name = 'post_detail.html' def about(request): return render(request, 'about.html') urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.PostList.as_view(), name='index'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), path('about/', views.about, name='about') ] -
Server stops at http://127.0.0.1:8000/admin/ in python django
Here I am creating my first Django application that is basically a polls app. I have followed these steps: Created a django app in pycharm. Wrote two tables in models.py. Done "python manage.py makemigrations". It successfully created my migrations. Done "python manage.py createsuperuser", set its username and password. Now doing, "python manage.py runserver", Its opening great. Issue: When hitting "http://127.0.0.1:8000/admin/", server just stops. No error and nothing happens. I don't understand that why I am not being able to hit the url. urls.py from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), ] Server state while quitting: C:\Users\Maha Waqar\PycharmProjects\DjangoSites>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). March 09, 2020 - 21:40:44 Django version 3.0.4, using settings 'DjangoSites.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [09/Mar/2020 21:41:20] "GET / HTTP/1.1" 200 16351 C:\Users\Maha Waqar\PycharmProjects\DjangoSites>