Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I get .vscode folder and settings.py file on my django project
I was following a tutorial on django . The tutor was using Mac OS he got the .vscode folder and settings.py in json But I can’t access that on my windows I’m using vscode editor -
Cache Key Warning
Project and unit test still works. But showing me this warning. (CacheKeyWarning: Cache key contains characters that will cause errors if used with memcached: ':1:nasa_neo_2019-01-01 00:00:00_2019-01-01 00:00:00') I want to get rid of this warning. So could you help me please? Here I check if there is data in the cache. cache_key = f'nasa_neo_{start_date}_{end_date}'.strip("") json_data = cache.get(cache_key) if not json_data: some process else: making a new request from api. and add to cache memory. cache.set(cache_key, json_data, timeout=4000) -
CSS not loading properly when html element appended using jquery in django template
I'm working on an ecommerce app where trying to get products using ajax and append the product list using .append method and data is being appended the problem is that css doesn't load properly also icons are loading. CSS loads sometimes when hard reloaded then again not loading once refreshed normally. Please find the below codes for your reference and help to resolve. <script> $.ajax({ url: "{% url 'frontend:get_products_by_tag' tag.id tag.slug %}", type: "GET", success: function (data) { {#console.warn(data)#} $("#productsByTagProductList").empty() $.each(data, function (index, value) { console.warn(value) const productId = value.id; const productName = value.name; const productPrice = value.product_price; const productDiscountedPrice = value.product_discounted_price; const thumbnailFront = value.thumbnail_front; const thumbnailBack = value.thumbnail_back; const productSlug = value.slug; const productBrand = value.brand; const productSize = value.size; const productColor = value.color; const avgRating = value.avg_rating; const productCategory = value.category; let addToCartBtn; if (productSize !== null || productColor.length !== null) { addToCartBtn = '<li><a href="javascript:void(0)" class="productViewModal"' + 'data-product-id="'+productId +'"' + 'title="Add to cart">' + '<i data-feather="shopping-bag"> </i></a></li>' } else { addToCartBtn = '<li><a href="javascript:void(0)"' + 'class="addtocart-btn update-cart"' + 'data-action="add"' + 'data-product_id="'+productId +' "' + 'title="Add to cart">' + '<i data-feather="shopping-bag"> </i> </a></li>' } let price if (productDiscountedPrice !== null) { price = '<span class="product-price">' + 'Rs.' … -
How to have multiple one to one relations to a specific model
I have a scientific info model that has a one-to-one relationship to my User model. this is my model: class ScientificInfo(models.Model): id = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) **other fields** I want to add an interviewer field to it as well so that I can chose an interviewer from the user model so I added it like this: class ScientificInfo(models.Model): id = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user') interviewer = models.OneToOneField(User, on_delete=models.CASCADE, related_name='interviews') **other fields** but when I want to create a new user it gives me unique constraint failed error -
Error while loading the pytest module in Django project
I am trying to run pytest in a django project with it is showing me error of no module loading. I have created init.py in test folders, but that also not worked for me to resolve this issue. ______________ ERROR collecting lib/python3.9/site-packages/tenacity/tests/test_tornado.py _______________ ImportError while importing test module '/Users/xxxx/Documents/ecommerce/lib/python3.9/site-packages/tenacity/tests/test_tornado.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: /opt/homebrew/Cellar/python@3.9/3.9.12_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py:127: in import_module return _bootstrap._gcd_import(name[level:], package, level) lib/python3.9/site-packages/tenacity/tests/test_tornado.py:19: in <module> from tenacity import tornadoweb lib/python3.9/site-packages/tenacity/tornadoweb.py:23: in <module> from tornado import gen E ModuleNotFoundError: No module named 'tornado' File Tree is as follows: ecommerce ┣ __pycache__ ┃ ┣ __init__.cpython-39.pyc ┃ ┣ settings.cpython-39.pyc ┃ ┣ urls.cpython-39.pyc ┃ ┗ wsgi.cpython-39.pyc ┣ dashboard ┃ ┣ __pycache__ ┃ ┃ ┗ __init__.cpython-39.pyc ┃ ┣ migrations ┃ ┃ ┗ __init__.py ┃ ┣ tests ┃ ┃ ┣ __pycache__ ┃ ┃ ┃ ┣ __init__.cpython-39.pyc ┃ ┃ ┃ ┗ test_selenium_dashboard.cpython-39-pytest-6.2.5.pyc ┃ ┃ ┣ __init__.py ┃ ┃ ┗ test_selenium_dashboard.py ┃ ┣ __init__.py ┃ ┣ admin.py ┃ ┣ apps.py ┃ ┣ models.py ┃ ┗ views.py ┣ tests ┃ ┣ __pycache__ ┃ ┃ ┣ __init__.cpython-39.pyc ┃ ┃ ┣ selenium.cpython-39-pytest-6.2.5.pyc ┃ ┃ ┗ test_selenium.cpython-39-pytest-6.2.5.pyc ┃ ┣ __init__.py ┃ ┗ test_selenium.py ┣ .DS_Store ┣ __init__.py ┣ asgi.py ┣ settings.py ┣ urls.py ┗ wsgi.py conftest.py db.sqlite3 … -
how to create a employee multiple Experince in django
How to Create Multiple Experinces in Django This is Model.py Files code from django.db import models # Create your models here. class Detail(models.Model): first_name = models.CharField(max_length=96) last_name = models.CharField(max_length=96) email_id = models.CharField(max_length=96) mobile_no = models.CharField(max_length=96) dob = models.CharField(max_length=96) qualification = models.CharField(max_length=96) def __str__(self): return self.first_name class Experince(models.Model): detail = models.ForeignKey(Detail, on_delete = models.CASCADE) organization = models.CharField(max_length=96) designation = models.CharField(max_length=96) date_from = models.CharField(max_length=96) date_to = models.CharField(max_length=96) def __str__(self): return self.organization This is View.py file code: from django.shortcuts import render from .models import * #from .forms import * # Create your views here. def home(request, id): if request.method == 'POST': Detail(first_name = request.POST['first_name'], last_name = request.POST['last_name'], email_id = request.POST['email_id'], mobile_no = request.POST['mobile_no'], dob = request.POST['dob'], qualification = request.POST['qualification']).save() Experince(organization = request.POST['organization'], designation = request.POST['designation'], date_from = request.POST['date_from'], date_to = request.POST['date_to']).save() return render(request,"home.html") This is my html page: <!DOCTYPE html> <html> <head> <title>test page</title> <link rel="stylesheet" href= "https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity= "sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src= "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src= "https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script> <script> $(document).ready(function () { // Denotes total number of rows var rowIdx = 0; // jQuery button click event to add a row $('#addBtn').on('click', function () { // Adding a row inside the tbody. $('#tbody').append(`<tr id="R${++rowIdx}"> <td class="row-index text-center"> <p>${rowIdx}</p> … -
How to execute my python script which is in HTML
Their is a recent update where we can embeed the python script within html code. That is called as pyscript : https://pyscript.net/ Just need to import the CDSN link in between <head> </head> tags of HTML. But only one issue is how do I pass my input to my python script and return output on SUBMIT button click I tried to create a simple page with choose file and submit button My code : <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" /> <script defer src="https://pyscript.net/alpha/pyscript.js"></script> </head> <body> <p>Click on the "Choose File" button to upload a file:</p> <form action="/action_page.php"> <input type="file" id="myFile" name="filename"> <input type="submit"> </form> <py-script> def readfile(): with open(filename) as myfile: head = [next(myfile) for x in range(1,5)] print(head) </py-script> </body> </html> The data in ABC.txt file 1,2,A 1,1,B 0,0,1 1,1,K h,j,l y,u,i a,h,g a,h,l e,t,y How do I call my python script code on SUBMIT button click & print first 5 text lines of file and display. -
Django customUser models
I have faced two or three issues with django customuser model. The first one being the skills models. I wanted to add the Skills in the custom user, realized that there has been some drawbacks, things like, I can not add this skill field properly and when adding the age in django, I dont kno, but the age field seems a bit confusing. My question is, how important is creating the separate userProfile that would inherit the custom user? I think I have come to realise that customuser is better left a lone. How do u guys manage such issues if ever faced? -
I need to split array to sub arrays of similar values in python
lets suppose i have this queryset_array: queryset_array = [{"category":"a"},{"category":"a"},{"category:"b"},{"category":"b"},{"category":"c"}, {"category":"c"}] how can i convert this array using most efficient pythonic way into: array_1 = [{"category":"a"},{"category":a"}}] array_2 = [{"category":"b"},{"category":"b"}] array_3 = [{"category":"c"},{"category":"c"}] -
React - Module parse failed: You may need an appropriate loader to handle this file type 6:15
Help me with this error: NPM run error my webpack setting: module.export = { module: { rules: [ { test: /\.js$|\.jsx/, exclude: /node_modules/, use: { loader: "babel-loader", presets: ['es2015'] } } ], } } -
How do I upload a webcam image using JavaScript ajax to a Django site?
I am creating a livestreaming site using Django and I need to upload an image using an ajax post request to a model form on the django site. I am working with the following code: Models: from django.db import models from django.contrib.auth.models import User class Camera(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='camera') image = models.ImageField(upload_to='live/', null=True, blank=True) Views: from .models import Camera from .forms import CameraForm @login_required @csrf_exempt def golive(request): cameras = Camera.objects.filter(user=request.user) camera = None if cameras.count() == 0: camera = Camera.objects.create(user=request.user) camera.save() else: camera = cameras.first() if request.method == 'POST': print(request.FILES) form = CameraForm(request.POST, request.FILES, instance=camera) if form.is_valid(): form.save() print("Working") return redirect('live:live') return render(request, 'live/golive.html', {'object': request.user.camera, 'form': CameraForm()}) @login_required def live(request, username): profile = get_object_or_404(Profile, user__username=username, identity_verified=True, vendor=True) cameras = Camera.objects.filter(user=profile.user) return render(request, 'live/live.html', {'profile': profile, 'camera': cameras.first()}) Templates: {% extends 'base.html' %} {% block content %} <h1>Go live</h1> <div id="container"> <video autoplay="true" id="video"> </video> <canvas id="canvas" width="1028" height="728"> </canvas> <button id="capture"></button> </div> {% endblock %} {% block javascript %} var video = document.getElementById('video'); var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); function capture(){ ctx.drawImage(video, 0, 0, 1024, 728); ctx.save(); canvas.toBlob(function(blob){ console.log(blob); var fileOfBlob = new File([blob], 'camera.png'); var formData = new FormData(); formData.append('image', fileOfBlob, 'camera.png'); … -
How Can I get the tag id on clicked in Django?
Here's the html <div class="items-link items-link2 f-right"> <a href="{% url 'applytojob' %}" name="job_id" id="{{job.job_id}}" >Apply</a> </div> Here the id is dynamic, so whenever I clicked on this link I need to get id of this tag to my python code in Django. How can I achieve this? Thanks in advance -
I need to apply the values_list() function to queryset after filtering
Following is my View Class: from apps.embla_services.filters import RentPostFilters from django_filters import rest_framework as filters from apps.embla_services.models import RentPost from apps.embla_services.serializers import RentPostBriefSerializer class SearchRentPosts(generics.ListAPIView): def get_queryset(self): city = self.request.query_params.get("city") if city: return RentPost.objects.filter(city__name=city) else: return RentPost.objects.all() serializer_class = RentPostBriefSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = RentPostFilters Following is my Filter Class: from django_filters import rest_framework as filters from apps.embla_services.models import RentPost class RentPostFilters(filters.FilterSet): title = filters.CharFilter(lookup_expr="icontains") is_available = filters.BooleanFilter() rent_type = filters.ChoiceFilter(choices=RentPost.RentTypeChoices.choices) category__id = filters.NumberFilter() available_from = filters.DateFromToRangeFilter() price = filters.RangeFilter() class Meta: model = RentPost fields = ["title", "is_available", "rent_type", "category", "available_from", "price"] Following is my Serializer Class: from apps.embla_services.models import RentPost class RentPostBriefSerializer(serializers.ModelSerializer): uploaded_media = FileSerializer(source='media', many=True, read_only=True) category = serializers.CharField(source="category.title") is_expired = serializers.SerializerMethodField() def get_is_expired(self, obj: RentPost): if obj.available_To and obj.available_To < date.today(): return True return False class Meta: model = RentPost fields = ["id", "available_from", "title", "created_at", "latitude", "longitude", "is_available", "uploaded_media", "delivery", "price", "rent_requests", "is_available", "is_expired", "city","category"] What i want is that after all the filters are applied to queryset, i can split this queryset into sub arrays depending upon the category. For example if query set contains 30 items of 3 different categories (10 items in each category). i want the response that is sent … -
Django: How to filter model with multiple whitespaces?
I have a model with char field with values like this: "Justin Roseman" (one single whitespace betwen words) "Justin Roseman" (two whitespaces betwen words) " Justin Roseman " (a lot whitespaces betwen words) etc. etc... I want get all records searching "Justin Roseman". My database is MySQL. I have tried the icontains function, but it does not work if there is more than one whitespace between words: results = MyModel.objects.filter(name__icontains="Justin Roseman") # Only returns values whit one whitespace between words, none whit two or more whitespaces :( Any ideas? please. Maybe whit regex? Thanks :D -
django project does not write to file and there is no error, the file does not appear
I'm trying to write to a file and django doesn't do it. There is no error of any kind but the file does not appear. Using the process monitor I don't see any attempt to write. In a python file the same code works fine. Test performed: @method_decorator(login_required, name='dispatch') class TestWrite(TemplateView): template_name = 'test.html' with open(r'd:\djangotest.txt', "w") as fo: fo.write('test') fo.close() I did the test with Popen and it doesn't work either. p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) stdout, stderr = p.communicate() returncode = p.returncode In the case of Popen I used pg_dump.exe and in stderr I got the result of the program running correctly but no file anywhere. It doesn't matter which path you select to write, inside the project, outside of it, ect. the file does not appear. I don't know if it's important, but I did the tests in pycharm. -
Is there a switch to store the Wagtail RichTextBlock content to database in UTF-8?
I am new in Django and Wagtail. I developed a website app using Django 4.0 and Wagtail 2.16.1. I found Django models.CharField by default stores content to database in UTF-8, while Wagtail RichTextBlock by default stores content to database in Unicode, which cause a problem when searching the East-Asian characters. models.py class BlogDetailPage(Page): custom_title = models.CharField('Title', max_length=60, help_text='文章标题') author = models.ForeignKey(User, on_delete=models.PROTECT) create_date = models.DateField("Create date", auto_now_add= True) update_date = models.DateField("Update date", auto_now=True) intro = models.CharField('Introduction', max_length=500, help_text='文章简介') tags = ClusterTaggableManager(through=BlogPageTag, blank=True) content = StreamField( [ ('heading', blocks.CharBlock(form_classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ('blockquote', blocks.BlockQuoteBlock(label='Block Quote')), ('documentchooser', DocumentChooserBlock(label='Document Chooser')), ('url', blocks.URLBlock(label='URL')), ('embed', EmbedBlock(label='Embed')), #('snippetchooser', SnippetChooserBlock(label='Snippet Chooser')), ('rawhtml', blocks.RawHTMLBlock(label='Raw HTML')), ('table', TableBlock(label='Table')), ('markdown', MarkdownBlock(label='Markdown')), ('code', CodeBlock(label='Code')), ('imagedeck', CardBlock(label='Imagedeck')), ], null=True, blank=True, ) search.py def search(request): search_query = request.GET.get('query', None).strip() page_num = request.GET.get('page', 1) condition = None for word in search_query.split(' '): if condition is None: condition = Q(custom_title__icontains=word) | Q(intro__icontains=word) | Q(content__icontains=word.encode('utf-8')) else: condition = condition | Q(custom_title__icontains=word) | Q(intro__icontains=word) | Q(content__icontains=word.encode('utf-8')) search_results = [] if condition is not None: search_results = BlogDetailPage.objects.live().filter(condition) The problem is I can search English and Chinese in the intro field, but can only search English in content field. When checking the database (PostgreSQL UTF-8 by … -
How to solve the problem of installing django-simple-history?
In my project i need to use django-simple-history but when i run the command : pip install django-simple-history i got the ERREUR : Could not build wheels for django-simple-history, which is required to install pyproject.toml-based projectsenter image description here any solutions please, thank you in advance -
Problem upgrading django 2.2.27 to 2.2.28 on Mac
I have a Django application that I'm trying to upgrade the django module from 2.2.27 to 2.2.28 to close a SQL injection attack vector. I'm running this on a recent intel Mac with a current OS, Python 3.7.7, and the installation and package management are handled by pipenv. If I clone the repository for the project and run pipenv install things work fine and I can run the application. If I edit the Pipfile and change django line to this: django = "==2.2.28" and run pipenv update I get a long error display: Running $ pipenv lock then $ pipenv sync. Locking [dev-packages] dependencies... Building requirements... Resolving dependencies... ✔ Success! Locking [packages] dependencies... Building requirements... Resolving dependencies... ✘ Locking Failed! INFO:pep517.envbuild:Temporary build environment: /var/folders/fh/jwrr3ps55v97vr65pvvc25ch0000gp/T/pep517-build-env-b7oz222d INFO:pep517.envbuild:Temporary build environment: /var/folders/fh/jwrr3ps55v97vr65pvvc25ch0000gp/T/pep517-build-env-a2zlgyg9 INFO:pep517.envbuild:Temporary build environment: /var/folders/fh/jwrr3ps55v97vr65pvvc25ch0000gp/T/pep517-build-env-wnccio_d INFO:pep517.envbuild:Temporary build environment: /var/folders/fh/jwrr3ps55v97vr65pvvc25ch0000gp/T/pep517-build-env-qdyz7et_ INFO:pep517.envbuild:Temporary build environment: /var/folders/fh/jwrr3ps55v97vr65pvvc25ch0000gp/T/pep517-build-env-f_ntiq_4 INFO:pep517.envbuild:Temporary build environment: /var/folders/fh/jwrr3ps55v97vr65pvvc25ch0000gp/T/pep517-build-env-njy4pcni INFO:pep517.envbuild:Temporary build environment: /var/folders/fh/jwrr3ps55v97vr65pvvc25ch0000gp/T/pep517-build-env-9hanls1n INFO:pep517.envbuild:Temporary build environment: /var/folders/fh/jwrr3ps55v97vr65pvvc25ch0000gp/T/pep517-build-env-nh2nhv5s INFO:pipenv.patched.notpip._internal.vcs.git:Cloning https://github.com/startwithlucy/zoomus.git (to revision v0.2.7) to /var/folders/fh/jwrr3ps55v97vr65pvvc25ch0000gp/T/pipenv-lodkowat-src/zoomus2 INFO:pep517.envbuild:Temporary build environment: /var/folders/fh/jwrr3ps55v97vr65pvvc25ch0000gp/T/pep517-build-env-3tdmn4n6 INFO:pep517.envbuild:Temporary build environment: /var/folders/fh/jwrr3ps55v97vr65pvvc25ch0000gp/T/pep517-build-env-or92fdaw INFO:pep517.envbuild:Temporary build environment: /var/folders/fh/jwrr3ps55v97vr65pvvc25ch0000gp/T/pep517-build-env-4afu8z2s INFO:pep517.envbuild:Temporary build environment: /var/folders/fh/jwrr3ps55v97vr65pvvc25ch0000gp/T/pep517-build-env-1gzv7c4l INFO:pep517.envbuild:Temporary build environment: /var/folders/fh/jwrr3ps55v97vr65pvvc25ch0000gp/T/pep517-build-env-_nb_ij8m INFO:pep517.envbuild:Temporary build environment: /var/folders/fh/jwrr3ps55v97vr65pvvc25ch0000gp/T/pep517-build-env-3mnuqo1i INFO:pep517.envbuild:Temporary build environment: /var/folders/fh/jwrr3ps55v97vr65pvvc25ch0000gp/T/pep517-build-env-8j29fail INFO:pep517.envbuild:Temporary build environment: /var/folders/fh/jwrr3ps55v97vr65pvvc25ch0000gp/T/pep517-build-env-equgr8uv INFO:pep517.envbuild:Temporary build environment: /var/folders/fh/jwrr3ps55v97vr65pvvc25ch0000gp/T/pep517-build-env-pyqzy2cq INFO:pep517.envbuild:Temporary build environment: /var/folders/fh/jwrr3ps55v97vr65pvvc25ch0000gp/T/pep517-build-env-lw3xry9m INFO:pipenv.patched.notpip._internal.operations.prepare:Obtaining … -
Django models: is it possible to force icontains on filter/get for specific field using a manager?
Let's say I have a model with a string field similar to this class Product(models.Model): upc = models.CharField(max_length=12, blank=False, null=False) Is it possible to build a model manager or something similar where every time I use Product.objects.get/Product.objects.filter it overrides the default lookup to force the search/filter to behave like I had used icontains? As in: Product.objects.get(upc="012345678902") Product.objects.filter(upc="012345678902") By default would behave like: Product.objects.get(upc__icontains="012345678902") Product.objects.filter(upc__icontains="012345678902") -
How to show on template just a Model with Foreign Key Django
I have this model: class CustomUser(AbstractUser): phone = models.IntegerField(null=True, blank=True) class RouterModel(models.Model): ip = models.CharField(max_length=15) username = models.CharField(max_length=50) password = models.CharField(max_length=50) port = models.IntegerField() owner = models.ForeignKey('CustomUser', on_delete=models.CASCADE, ) name = models.CharField(max_length=50) def __str__(self): return self.name class Clients(models.Model): name = models.CharField(max_length=50) tcpIP = models.IntegerField() email = models.EmailField() phone = models.IntegerField() zone = models.CharField(max_length=50) owner = models.ForeignKey('RouterModel', on_delete=models.CASCADE, ) def __str__(self): return self.name class Tickets(models.Model): title = models.CharField(max_length=200) comment = models.TextField(max_length=500) owner = models.ForeignKey('Clients', on_delete=models.CASCADE) def __str__(self): return self.title and this view class DashBoard(ListView): model = RouterModel template_name = 'templates/dashboard/dashboard.html' context_object_name = 'router_model' template: {% block content %} {% if user.is_authenticated %} <h3>Hello {{ user.username }}</h3> {% for router in object_list %} <h3>{{ router }}</h3> <h2>{{ router.ip }}</h2> <br> {% endfor %} {% endif %} {% endblock content%} Im getting on the template all the RouterModel created. I mean if user A create a RouterModel when I log in with user B i can see what user A create. how can i display only the user models created by user B? not the A or C. Just B. -
Images are not showing in a Django web app deployed on Heroku
I have a Django app deployed on Heroku the problem is that when I upload an image to the app, it's uploaded fine and it keeps being shown for sometime, when I close the app for a long time and come back the images become corrupted and not shown. I use postgres database. I use django-imagekit package to upload images into the models, I even installed the whitenoise package after I have seen a similar problem with this package as a solution and the problem is still persistent. and I don't know what the problem is. anybody has an idea ? settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', "whitenoise.middleware.WhiteNoiseMiddleware", .... ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'helper', 'USER': '', 'PASSWORD': '', 'HOST': 'localhost', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. 'PORT': '', # Set to empty string for default. } } STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" -
Error when creating a django superuser with Heroku - FileNotFoundError
I'm trying to deploy a django application on Heroku, but when it comes to the part where I need to create a superuser, I get an error: Traceback (most recent call last): File "/app/django_project/manage.py", line 22, in <module> main() File "/app/django_project/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 87, in execute return super().execute(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 232, in handle self.UserModel._default_manager.db_manager(database).create_superuser( File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/auth/models.py", line 171, in create_superuser return self._create_user(username, email, password, **extra_fields) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/auth/models.py", line 154, in _create_user user.save(using=self._db) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/auth/base_user.py", line 68, in save super().save(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/base.py", line 806, in save self.save_base( File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/base.py", line 872, in save_base post_save.send( File "/app/.heroku/python/lib/python3.9/site-packages/django/dispatch/dispatcher.py", line 176, in send return [ File "/app/.heroku/python/lib/python3.9/site-packages/django/dispatch/dispatcher.py", line 177, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "/app/django_project/users/signals.py", line 18, in create_profile Profile.objects.create(user=instance) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py", line 514, in create obj.save(force_insert=True, using=self.db) File "/app/django_project/users/models.py", line 20, in save img = Image.open(self.image.path) File "/app/.heroku/python/lib/python3.9/site-packages/PIL/Image.py", line 3068, in open fp = builtins.open(filename, "rb") FileNotFoundError: [Errno 2] No … -
Getting objects before validating data Django REST
I have to create a new Chat object using this view: class ChatListCreateView(ListCreateAPIView): permission_classes = [IsAuthenticated] serializer_class = ChatSerializer def get_queryset(self): data = Chat.objects.filter( Q(employees=self.request.user) | Q(created_by=self.request.user)).distinct() return data The serializer it uses is: class ChatSerializer(serializers.ModelSerializer): created_by = SimpleEmployeeSerializer(read_only=True) employees = SimpleEmployeeSerializer(many=True, read_only=True) title = serializers.CharField(max_length=255) def create(self, validated_data): """ Creates a new Chat and adds the m2m employees to it """ # Create and save the chat chat = Chat.objects.create( created_by=self.context['request'].user, title=validated_data['title'], ) # Add the employees to the chat validated_employees = validated_data.pop('employees') for user_id in validated_employees: employee = Employee.objects.get(id=user_id) chat.employees.add(employee) return chat My issue is that the SimpleEmployeeSerializer expects a user object but I am submitting an array of employees as such: { "title": "fwef", "employees": [ { "id": "8" }, { "id": "30" } ] } What method can I implement to get the objects from these IDs before validation? -
collectstatic throws AttributeError: 'NoneType' object has no attribute 'startswith
I am following this guide to serve static files for my site using Digital Ocean's spaces. Here are my settings: ... MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') AWS_ACCESS_KEY_ID = os.environ.get("DIGITALOCEAN_STATIC_ACCESS_KEY") AWS_SECRET_ACCESS_KEY = os.environ.get("DIGITALOCEAN_STATIC_SECRET_KEY") AWS_STORAGE_BUCKET_NAME = os.environ.get("AWS_STORAGE_BUCKET_NAME") AWS_LOCATION = os.environ.get("AWS_LOCATION") AWS_S3_ENDPOINT_URL = 'https://nyc3.digitaloceanspaces.com' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_ENDPOINT_URL, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_ROOT ='/home/myname/example/assets' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' When I run python manage.py collectstatic I get this: location as specified in your settings. This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/user/example/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/user/example/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/user/example/env/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/user/example/env/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/user/example/env/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle collected = self.collect() File "/home/user/example/env/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect handler(path, prefixed_path, storage) File "/home/user/example/env/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 338, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "/home/user/example/env/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 248, in delete_file if self.storage.exists(prefixed_path): File "/home/user/example/env/lib/python3.8/site-packages/django/utils/functional.py", line 246, in inner … -
ReactJS / Axios / Django: Update form with the current image from API
I'm trying to create an update form in React, the update works fine as I have set the default values that coming from (get method) using axios and set them as the default if none changed. I get the existing image from API and set it as default value in React update form, if image updated get the new one(this one is working fine) if image was not updated, put the existing image that was received from the API which is not working, I get this message: {image: ["The submitted data was not a file. Check the encoding type on the form."]} my code: React: export function ProductUpdate() { const [p, setProduct] = useState("") const {slug} = useParams() useEffect(() => { function featchProduct() { axios.get(API.products.retrive(slug)) .then(res => { setProduct(res.data) }) } featchProduct() } ,[]) const [loading, setLoading] = useState(false) const [title, setTitle] = useState("") const [image, setImage] = useState(null) const [description, setDescription] = useState("") const [price, setPrice] = useState("") const [active, setActive] = useState("") const [soldout, setSoldout] = useState("") const handleSubmit = (event) => { event.preventDefault(); let formField = new FormData() formField.append('title', title || p.title) formField.append('slug', slug) formField.append('description', description || p.description) formField.append('price', price) formField.append('active', active) formField.append('soldout', soldout) formField.append('image', image || …