Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django project not in virtual environtment folder?
I was cloning django project, then i try to run the project that next step is to install virtual environtment. I was confusing because usually project is in the virtual environtment folder(see the pic) but it is not, althought the project run properly. Anybody can explain? This is my project layout -
Edit formdata in Django Rest framework
I have a simple form in my app which contains manytomany field and an document uploader. The data in this form is being sent as multipart/form-data for e.g. transaction_no: 5001 document: (binary) items: [{"product":1,"quantity":"12","fault":"Repairable"}] allotment: 2 The create function works perfectly fine but when I try to edit the data in this form I get an error The data sent during "editing" is similar to the data sent during "creation". data: transaction_no: 5001 items: [{"id":5,"quantity":"10","fault":"Repairable","product":1}] allotment: 2 Serializer.py class DeliveredItemsSerializer(serializers.ModelSerializer): class Meta: model = DeliveredItems fields = "__all__" class DeliveredSerializer(serializers.ModelSerializer): items = DeliveredItemsSerializer(many=True, required=False) class Meta: model = Delivered fields = "__all__" def create(self, validated_data): items_objects = validated_data.pop('items', None) prdcts = [] try: for item in items_objects: i = DeliveredItems.objects.create(**item) prdcts.append(i) instance = Delivered.objects.create(**validated_data) instance.items.set(prdcts) return instance except: instance = Delivered.objects.create(**validated_data) return instance def update(self, instance, validated_data): items_objects = validated_data.pop('items',None) prdcts = [] for item in items_objects: print("item", item) fk_instance, created = DeliveredItems.objects.update_or_create(pk=item.get('id'), defaults=item) prdcts.append(fk_instance.pk) instance.items.set(prdcts) instance = super(DeliveredSerializer, self).update(instance, validated_data) return instance Error: 'NoneType' object is not iterable and this is the line of error: for item in items_objects: How come when I am sending the same data in exact same format is not received by the serializer during … -
LEFT JOIN in Django ORM (left join bettwen two tables and stock the result in a third table)
I have the following models: class Somme_Quantity_In_T(models.Model): Family_Label = models.CharField(max_length=50) Site = models.CharField(max_length=10) Product = models.CharField(max_length=10) Vendor = models.CharField(max_length=200) class Produit(models.Model): Taux = models.CharField(max_length=50, null=True) Famille = models.CharField(max_length=50) NIP = models.CharField(max_length=50) NGS = models.CharField(max_length=5, null=True) class Produit_a_ajouter(models.Model): Family_Label = models.CharField(max_length=50) Site = models.CharField(max_length=10) Product = models.CharField(max_length=10) Vendor = models.CharField(max_length=200) I want to query for this following query: SELECT Somme_Quantity_In_T.* FROM Somme_Quantity_In_T LEFT JOIN Produit ON Somme_Quantity_In_T.product = Produit.NIP AND Somme_Quantity_In_T.Family_Label = Produit.Famille WHERE Produit.NIP is null And I want to stock the result of this query in Produit_a_ajouter table -
How to reuse a big, expensive-to-load dictionary in Python?
I've got a 1 GB dictionary that takes a while to load into memory. But once the loading process is complete, running lookups in that dictionary is pretty fast. How do I best reuse that loaded dictionary from various Python scripts that may get spawned in response to network requests? I'd be interested in either general-purpose solution that I can test locally on my laptop before deploying to my Django server or, if there's none, in a Django-specific one. -
Requirement not fulfiled at heroku
I am getting the error while deploying Django project on heroku. ERROR: Could not find a version that satisfies the requirement apturl==0.5.2 (from -r /tmp/build_3724e729_/requirements.txt (line 1)) (from versions: none) ERROR: No matching distribution found for apturl==0.5.2 (from -r /tmp/build_3724e729_/requirements.txt (line 1)) I tried reinstalling apturl and I can see below- unpacking aptutl 0.5.2 but still I am getting error at heroku. sudo apt-get install apturl apturl-common Reading package lists... Done Building dependency tree Reading state information... Done The following packages were automatically installed and are no longer required: efibootmgr libboost-program-options1.65.1 libegl1-mesa libfwup1 libgoogle-perftools4 libllvm9 libpcrecpp0v5 libtcmalloc-minimal4 libwayland-egl1-mesa libyaml-cpp0.5v5 linux-headers-5.4.0-45-generic linux-hwe-5.4-headers-5.4.0-42 linux-hwe-5.4-headers-5.4.0-45 linux-image-5.4.0-45-generic linux-modules-5.4.0-45-generic linux-modules-extra-5.4.0-45-generic mongo-tools mongodb-server-core Use 'sudo apt autoremove' to remove them. Suggested packages: libgtk2-perl The following NEW packages will be installed: apturl apturl-common 0 upgraded, 2 newly installed, 0 to remove and 52 not upgraded. Need to get 19.4 kB of archives. After this operation, 228 kB of additional disk space will be used. Get:1 http://in.archive.ubuntu.com/ubuntu bionic-updates/main amd64 apturl-common amd64 0.5.2ubuntu14.2 [10.9 kB] Get:2 http://in.archive.ubuntu.com/ubuntu bionic-updates/main amd64 apturl amd64 0.5.2ubuntu14.2 [8,464 B] Fetched 19.4 kB in 1s (31.2 kB/s) Selecting previously unselected package apturl-common. (Reading database ... 229913 files and directories currently installed.) Preparing to unpack .../apturl-common_0.5.2ubuntu14.2_amd64.deb … -
Why the python Tornado frame not have the start log like Flask or Django?
such as flask have Serving Flask app "main" (lazy loading) Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. Debug mode: off Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) -
Accidentally deleted .mypy_cache folder
While running python type checker for django project with invoke I get the error: File "/Users/myusername/.pyenv/versions/3.8.3/lib/python3.8/genericpath.py", line 55, in getmtime return os.stat(filename).st_mtime FileNotFoundError: [Errno 2] No such file or directory: '.mypy_cache/3.8/django/core/exceptions.data.json' I accidentally deleted .mypy_cache folder to troubleshoot another problem. So now I don't know where the .mypy_cache folder should live and is there any command to get it back again? -
access data ForeignKey django reverse way
I have 2 models class Book(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Publish') ) name = models.CharField(max_length= 500) status = models.CharField(max_length = 10, choices = STATUS_CHOICES, default = 'draft') class Author (models.Model): name = models.CharField(max_length) book = models.ForeignKey(Book, on_delete=models.CASCADE) now i want to implement query on books table and get it Author also, I don't want to apply query on author and myquery should be like that select * from book left join ON book.id = author.book_id where book.status = 'published' How could i implement this in django -
How to insert multiple instance in Django Rest API @api_view?
How can insert multiple data at once in Django rest API with Json array Json Arry [{ "order_token": "8000253120", "name": "lg", "mobile_number": "9739615236", "address1": "arjun", "city": "bangalore", "state": "karnataka", "pincode": "562122" }, { "order_token": "8000253125", "name": "iphone", "mobile_number": "807312784", "address1": "V H Palya", "city": "bangalore", "state": "karnataka", "pincode": "562122" } ] when creating with @api_view i get error : list indices must be integers or slices, not str @api_view(['POST',]) @permission_classes((IsAuthenticated, )) def create_order(request): if request.method == 'POST': data = {} serializer = OrderSerializer(data=request.data, many=isinstance(request.data, list)) if serializer.is_valid(): serializer.save() data['success'] = 'created successfully' return Response(data=data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
View counter - how can I display most popular articles in last 10minutes?
I have views counter (I used django-hitcount) Models: class Article(Created, HitCountMixin): title = models.CharField(max_length=120) body = RichTextField(null=False) hit_count_generic = GenericRelation( MODEL_HITCOUNT, object_id_field='object_pk', related_query_name='hit_count_generic_relation') Views: class AllArticlesListView(ListView): template_name = 'news/articles_list.html' model = Article paginate_by = 5 and I sort articles by number of article views like this: def get_queryset(self): return self.model.objects.all().order_by('-hit_count_generic__hits') and everything is OK. Now I want make most viewed in last 10minutes, like: def get_queryset(self): return self.model.objects.all().order_by('-hit_count_generic__hits_in_last(minutes=10)') But it doestn work... still sort articles by all views not views in last 10minutes. How can I do? -
'DjangoFormMutationOptions' object has no attribute 'model'
I am trying to create a mutation using DjangoFormMutation, I am getting an error that DjangoFormMutationOptions has no attribute 'model', here is the error that I am getting. { "errors": [ { "message": "'DjangoFormMutationOptions' object has no attribute 'model'", "locations": [ { "line": 2, "column": 3 } ], "path": [ "updateLocation" ] } ], "data": { "updateLocation": null } } here is my mutation class UpdateLocation(DjangoFormMutation): location = graphene.Field(LocationType) class Meta: form_class = UpdateLocationForm def perform_mutate(cls, form, info): return super().perform_mutate(form, info) and this is my form class UpdateLocationForm(forms.Form): name = forms.CharField() id = forms.IntegerField() class Meta: fields = ['name', 'id'] -
How to update multiple images at a time?
Here I am trying to update each product image of a particular product. But it is not working properly. Here only the image of first object is updating. models class ProductImage(models.Model): image = models.ImageField(upload_to='imgs',blank=True, null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE) template {% for image in p_images %} <tr><td>{{image.pk}}</td> <td><img src="{{image.image.url}}" width="50" height="50"></td> <td>&nbsp;&nbsp;<input type="file" name="image"></td> </tr> {% endfor %} views images = request.FILES.getlist('image') p_images = ProductImage.objects.filter(product=product).order_by('pk') for p, img in zip(p_images, images): p.image = img p.save() # Tried this way too: for img in images: ProductImage.objects.filter(product=product).update(image=img) -
Django redirect, succesfull HTTP GET, no redirect
I'm trying to use a django redirect but I'm without much luck. My structure is as follows: views: def pageOne(request): return render(request, 'pageOne.html') def pageTwo(request): return render(request, 'pageTwo.html') def addInstance(request): instance = Model(name=request.POST['name']) return redirect('../pageTwo/') Then on pageOne I have a button (in a React app, hosted on a node server, called in pageone.html) to add the model instance which calls addInstance through a JQuery ajax call. All three function seems to work, I can visit the url's of both pages. When I add the instance on page one, I see the following happening in the Django console: [] "POST /addInstance/ HTTP/1.1" 302 0 [] "GET /pageTwo/ HTTP/1.1" 301 0 However, and this is the part I do not get, the browser screen does not redirect to pageTwo. I have tried various things in the redirect function: path name '/pageTwo/' 'pageTwo/ 'pageTwo I feel this is correct given the http status. Anyways, any tips will be greatly appreciated! -
How can I sort tags by count manytomany field Django
thank you for the time you spend reading my post so I'll get to the point. I tried to arrange my most common tags in the order of the most used tags to the most unused first 5 values but I dont know how. This is what I've tried : models.py: class Tag(models.Model): tag = models.CharField(max_length=250) def __str__(self): return self.tag class BlogPost(models.Model): # blogpost_set -> queryset tags = models.ManyToManyField(Tag, null = True) context_processor.py: def blog_cat_tags(request): # Top Tags most_common = BlogPost.objects.values('tags').annotate(truck_count=Count('tags')).order_by('-truck_count') most_common_n = Tag.objects.values('tag').annotate(truck_count=Count('tag')).order_by('-truck_count') common_tags = [] for tag in most_common: common_tags.append(tag) common_tags = common_tags[:5] This is the resault: Tags are aranged in order but i cant get the name and if I change from most_common variable to most_common_n in for I get this. But this is not the right order. Any ideas? -
How to extend a model with many optional models in django?
Say I have a master model with several optional slave models: class Master(models.Model): field_m1 = models.IntegerField(default=0) field_m2 = models.IntegerField(default=0) class slave1(models.Model): field_s11 = models.OneToOneField( Master, on_delete=models.CASCADE, primary_key=True, ) field_s12 = models.IntegerField(default=0) class slave2(models.Model): field_s21 = models.OneToOneField( Master, on_delete=models.CASCADE, primary_key=True, ) field_s22 = models.IntegerField(default=0) at first I create a createview and a updateview: class MasterCreate(CreateView): model = Master class MasterUpdate(UpdateView): model = Master then I use them in template master_form.html ... <form method="post">{% csrf_token %} ... {{form.field_m1 }} {{form.field_m2 }} ... </form> ... everything seems OK so far, but how to integrate the slave models into the master's model so I can use these field in template just like use Master.field_m1 and Master.field_m2 -
My heroku app is not able to import the Phonenumber_field module
I am trying to deploy a Django application to Heroku. This is my settings.py file: import os import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'aijsndkajskjndkjasnkansndas' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] AUTH_USER_MODEL = 'appname.User' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'appname.apps.AppnameConfig', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'projectname.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'projectname.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATICFILES_STORAGE … -
How can I change the server database in my local database at Django?
I want to change my local database tables to server database tables. The server database includes user information and related tables (ForeignKey, Many-To-Many). What I want is to dump some tables from the local to the server-side -
How to create product variation in Django with size and colors(with multiple images)?
my question is that how can i create Product variation of a product for Size and colour and each color variation of that product will have multiple images Just like how amazon do my admin.py from django.contrib import admin from .models import Product, Images class ProductImageInline(admin.TabularInline): model = Images extra = 7 class ProductAdmin(admin.ModelAdmin): list_display = ['image_tag', 'title', 'category'] list_filter = ['category'] readonly_fields = ('image_tag',) inlines = [ProductImageInline] #prepopulated_fields = {'slug': ('title',)} admin.site.register(Product, ProductAdmin) admin.site.register(Images) my models.py from ckeditor_uploader.fields import RichTextUploadingField from django.db import models from django.urls import reverse from django.utils.safestring import mark_safe class Product(models.Model): brand = models.CharField(max_length=50) title = models.CharField(max_length=120) keywords = models.CharField(max_length=120) description = models.TextField() image = models.ImageField(upload_to='images/', null=False) mrp = models.DecimalField(decimal_places=2, max_digits=10) price = models.DecimalField(decimal_places=2, max_digits=10) detail = RichTextUploadingField() slug = models.SlugField(blank=True, unique=True) created_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title def image_tag(self): if self.image.url is not None: return mark_safe('<img src="{}" height="50"/>'.format(self.image.url)) else: return "" image_tag.short_description = 'Image' class Images(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) title = models.CharField(max_length=50, blank=True) image = models.ImageField(blank=True, upload_to='images/') def __str__(self): return self.title my views.py from django.http import HttpResponse, JsonResponse from django.shortcuts import render from .models import Product, Images def product_detail(request, id, slug): product = Product.objects.get(pk=id) images = Images.objects.filter(product_id=id) context = { … -
python stripe is not returning expected result
In my python code i have a code to get 3 stripe customer list using this code: import stripe stripe.api_key = "sk_test_DftufeqrQlvZHqPdIgGmf9ro00exkHljNF" stripe.Customer.list(limit=3) print(stripe) what output i am getting is : <module 'stripe' from '/var/www/html/project/myenv/lib/python3.6/site-packages/stripe/__init__.py'> I dont know why i am getting this instead of result can anyone please help me related this ?? -
Retrieving the message of a custom exception in Python
I am raising a custom exception like that: class File_Upload_Exception(Exception): pass def myfn(): raise File_Upload_Exception(_('FILE_TYPE_NOT_ALLOWED')) My question: How do I get the exception message? The below gives the following error: File_Upload_Exception is not JSON serializable try: myfn() except File_Upload_Exception as e: print(e) #I want to retrieve the message "File type not allowed" -
JavaScript, CSS, and Image File Imports Won't Load When Running Live Server On Pycharm with Django
This might be a very basic question but I've been stuck on it a while and ended up deciding to ask on here...greatly appreciate any help! So I've just been making a basic website using pycharm and django and everything loads fine when I run the code through a browser. However, when I use runserver, it only shows the HTML code and not any of the files I have imported including javascript files, css files, and image files. All of my files are contained within the same templates folder. This is the error I receive in the terminal when opening up a live server. [13/Oct/2020 06:29:02] "GET /homepage.css HTTP/1.1" 404 2264 Not Found: /Page2.css [13/Oct/2020 06:29:02] "GET /Page2.css HTTP/1.1" 404 2255 Not Found: /Page3.css [13/Oct/2020 06:29:02] "GET /Page3.css HTTP/1.1" 404 2255 Not Found: /footer.css [13/Oct/2020 06:29:02] "GET /footer.css HTTP/1.1" 404 2258 Not Found: /login.css [13/Oct/2020 06:29:02] "GET /login.css HTTP/1.1" 404 2255 Not Found: /join.css [13/Oct/2020 06:29:02] "GET /join.css HTTP/1.1" 404 2252 Not Found: /demo.css [13/Oct/2020 06:29:02] "GET /demo.css HTTP/1.1" 404 2252 Not Found: /navbar.js [13/Oct/2020 06:29:02] "GET /navbar.js HTTP/1.1" 404 2255 Not Found: /LitChatLogo2.png [13/Oct/2020 06:29:02] "GET /LitChatLogo2.png HTTP/1.1" 404 2276 Not Found: /rectangle.png [13/Oct/2020 06:29:02] "GET /rectangle.png HTTP/1.1" 404 … -
Python Django Validation Error Message in Dictionary Form
I am working on certain validation and wants to raise human readable validation Error message in form of dictionary but I am stuck how to pass error messages and dictionary values inside dictionary here is what I have tried in other way: def _is_valid(self): boarding_points = self._location.point.all() if not set(self._data.get('point')).issubset(set(boarding_points)): for boarding_points_name in self._data.get('point'): raise ValidationError({'point', boarding_points_name, 'is not in location', self._location.name} ) above method is surely a wrong approach as it is set and secondly gives validation error message as [ "{'point', 'is not in location', 'London', <BoardingPoint: Manchester>}" ] I want error message as {'point': Boarding point: Manchester is not in Location: London} how can I do with python dictionary way to throw readable error message?TT -
Reverse for 'surveydetails' not found. 'surveydetails' is not a valid view function or pattern name
I've been stuck on this for a while, can't seem to fix the error. I've checked the code a hundred times but obviously there is something I'm missing. I have installed my app also. Can anybody see what I'm missing? views.py def survey_details(request, id=None): context = {} surveys = Survey.objects.get(id=id) context['survey'] = survey return render(request, 'surveydetails.html', context) feedback.urls.py path('details/<int:id>', views.survey_details, name="survey_details"), surveys.html {% extends 'main.html' %} {% block content%} <h1>Surveys</h1> <h2>list of {{title}} </h2> {% if surveys %} <ul> {% for survey in surveys %} <li> <a href="{% url 'feedback:surveydetails' %}">{{ survey.title }}</a> </li> {% endfor %} </ul> {% else %} <p>There are no surveys.</p> {% endif %} {% endblock %} surveydetails.html {% extends 'main.html' %} {% block content%} <h1>Surveys</h1> <h2>Detail page</h2> <h3>{{question.title}}</h3> <p>Details page of {{question.title}}</p> {% endblock %} -
how to configure Aapahe mod-wsgi for python 3.6 which is by default configured with python 2.7?
Hye everyone.. I have installed Python 3.6 and created a virtual environment and installed all required libraries including Django in that virtual environment. I want to host a django application on Linux server with wsgi but it says ImportError: No module named django.core.handlers.wsgi from what I search and think this problem is because the server is not accessing my virtual environment of python 3.6 where django is installed. My server details are: Python 3.6 [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] Django Version :3.1.1 Server version: Apache/2.4.46 (cPanel) Server Can anybody tells me how the Apache will get the djnago from my virtual environment? In other words how I can configure my server which is configured with python 2.7 to python 3.6 with libraries installed in virtual environment. Any help will be appreciated. -
How to add samesite=None in the set_cookie function django?
I want to add samesite attribute as None in the set_cookie function This is the code where I call the set_cookie function "redirect = HttpResponseRedirect( '/m/' ) redirect.set_cookie( 'access_token', access_token, max_age=60 * 60 )" This is the function where I set the cookie def set_cookie(self, key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False): self.cookies[key] = value if expires is not None: if isinstance(expires, datetime.datetime): if timezone.is_aware(expires): expires = timezone.make_naive(expires, timezone.utc) delta = expires - expires.utcnow() delta = delta + datetime.timedelta(seconds=1) expires = None max_age = max(0, delta.days * 86400 + delta.seconds) else: self.cookies[key]['expires'] = expires else: self.cookies[key]['expires'] = '' if max_age is not None: self.cookies[key]['max-age'] = max_age # IE requires expires, so set it if hasn't been already. if not expires: self.cookies[key]['expires'] = cookie_date(time.time() + max_age) if path is not None: self.cookies[key]['path'] = path if domain is not None: self.cookies[key]['domain'] = domain if secure: self.cookies[key]['secure'] = True if httponly: self.cookies[key]['httponly'] = True