Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Parsing serialized Json from Django to Js
I have problem with parsing JSON in JS. I'm writting search app in Django - which is meant to look for objects in database due to users text input, it has to return JSON of object with the same name as input as the response. JSON was first serialized in Django, and after this I want to parse it in JS to further use it on frontend. So aim is to take search for Object in Db-> take QuerySet object -> serialize in Django->get it in Template by Json_script->make it variable in JS -> Parse it-> Further use View as JsonResponse for debugging purpose: def search_name(request,sname): search_for=sname result = Person.objects.filter(name=search_for) if result == None: result = "No results for this Querry" serialized_result = serializers.serialize('json',result, fields=('name')) #kwargs = {'result':serialized_result} return JsonResponse(serialized_result,safe=False) #result = "[{\"model\": \"jsonek.person\", \"pk\": 1, \"fields\": {\"name\": \"Dottore\", \"city\": \"Lublin\", \"age\": 29}}]" View: def search_name(request,sname): search_for=sname result = Person.objects.filter(name=search_for) if result == None: result = "No results for this Querry" serialized_result = serializers.serialize('json',result, fields=('name')) kwargs = {'result':serialized_result} return render(request,'jsonek/result.html',kwargs) It goes to Js: const sbar = document.getElementById("sbar"); const poka = document.getElementById("poka"); const confirmBtn = document.getElementById("confirm-btn"); const json = document.getElementById("result") const json2 = '{"name":"Jan","age":25}' //test object to check if it … -
Docker compose up giving error no such file or dir. for .sh files in ubuntu
I am trying to run the docker container for web which has script start.sh file to start it, but docker-compose up web is giving an error. ERROR: for web Cannot start service web: OCI runtime create failed: container_linux.go:349: starting container process caused "exec: \"/home/app/start.sh\": stat /home/app/start.sh: no such file or directory": unknown By the following command it shows the start.sh is present in the docker image docker run -it web bin/bash Details: docker version: Docker version 19.03.6, build 369ce74a3c docker-compose version: docker-compose version 1.17.1, build unknown base image of dockerfile: ubuntu:18.04 -
Show whether a post is a pinned news
Django 3.0.8 admin.py class PostAdmin(admin.ModelAdmin): list_display = ("is_pinned",) def _get_pinned_news(self): pinned_news = None try: pinned_news = PinnedNews.objects.get(key="pinned_news") except ObjectDoesNotExist as e: pass # Do nothing return pinned_news.pinned_post def is_pinned(self, obj): pinned_news = self._get_pinned_news() return obj == pinned_news is_pinned.boolean = True This code shows the desired result revealing which post is a pinned news (at the main page). But it is highly ineffective as the selection query is done in a loop. By the way, django-cachalot will be used in production. So, maybe only one selection will be really done from the database. Could you tell me whether there is a better solution? -
Django ordering by multiple fields
I am having strange issue with django ordering. For some reason I am not able to order my List View by multiple fields. Here is my class. class Syslog(models.Model): receivedat = models.DateTimeField(default=timezone.now) facility = models.PositiveSmallIntegerField() priority = models.PositiveSmallIntegerField() fromHost = models.CharField(max_length=50) message = models.TextField(max_length=500) class Meta: ordering = ['id','receivedat', 'fromHost'] Here is my view class as well: class HomePageView(ListView): model = Syslog template_name = 'home.html' context_object_name = 'all_logs' paginate_by = 10 ordering = ['-id', 'receivedat', 'fromHost'] When a single field in ordering is specified (e.g. ordering = ['-id']), but when I add a second or third parameter everything goes back to defaults (only the first field of ordering is getting recognized) Does anyone have encounter a similar problem? The same problem persists in the Django shell as well. When I execute the following query Syslog.objects.all().order_by('id') everything looks good, but when I add another field to order_by (e.g. Syslog.objects.all().order_by('id','fromHost')) the second field doesn't get recognized at all. Regards, Jordan -
how to delete previously uploaded image from folder when the user change profile image in python?
I have a user profile page from where the user can update its detail and change profile image as well. The uploading of image is working fine . but i want that when the user change its profile image. the previously uploaded image should get deleted from the folder. I have a UserProfile Model which have OneToOneField() associated to user_auth table models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_img = models.ImageField(upload_to='ProfileImg') views.py profile_img = request.FILES['profile-upload'] if profile_img.name.endswith(tuple(ALLOWED_EXTENTIONS)): if user.userprofile.profile_img is not None: os.remove(user.userprofile.profile_img.name) <---------this solution is not working user.userprofile.profile_img = profile_img user.save() How to delete old image when update ImageField? I tried this solution but it raises an error: Exception Type: FileNotFoundError Exception Value: [WinError 3] The system cannot find the path specified: 'ProfileImg/model-5.jpg' i have already recheck the folder and the image is still there. I don't know where i'm getting wrong. Any kind of help will be appreciated -
New to React. I can't render all the elements from JSON data I am receiving from Django. I am stuck for a week
This is the JSON: [{id: 1, category1: "english", category2: "bulgarian",…},…] 0: {id: 1, category1: "english", category2: "bulgarian",…} category: [{id: 1, value1: "table", value2: "маса", date_publish: "2020-07-19T15:07:15.423703Z", category: 1},…] category1: "english" category2: "bulgarian" id: 1 user: 1 App.js return ( <div className="App"> <header className="App-header"> <h1>Flip Cards</h1> </header> <div className="leyout"> <AllElements pear={pear} /> </div> </div> ); } export default App; AllElements.js import React from 'react'; function AllEllemnts(props){ return ( <div className="AllElemts"> { props.pear && props.pear.map((pear) => { return ( <div key={pear.id} className="Allelements"> <h2>{pear.category1}-{pear.category2}</h2> <p>{pear.category.value1}</p> </div> ) })} </div> ) } export default AllEllemnts; -
No object create in model after submit form in Django
I have a form for add obj to models, no error for the whole process, but also no any objects adding to models. Did I miss somethings? below is my model, the field is matched to the forms but not all of it. product_name = models.CharField(max_length=200) price = models.DecimalField(decimal_places=2, max_digits=10, blank=True) created = models.DateTimeField(auto_now=True) img = models.ImageField(upload_to='product', default='xxxxx') img2 =models.ImageField(upload_to='product', null=True, default='xxxxxx') img3 =models.ImageField(upload_to='product', null=True, default='xxxxx') img4 =models.ImageField(upload_to='product', null=True, default='xxxxxxx') storage_amount = models.PositiveIntegerField(validators=[MinValueValidator(0)]) out_of_storage_or_not = models.BooleanField(default=False) description = models.TextField(blank=True, null=True) Hot = models.BooleanField(default=False) type = models.CharField( max_length=2, choices=PRODUCT_CHOICES, default=xxxxx, ) status = models.IntegerField(choices=STATUS, default=0) slug = models.SlugField(max_length=255, unique=True) forms.py: class Add_Product(forms.ModelForm): product_name = forms.CharField() price = forms.DecimalField() img = forms.ImageField() img2 = forms.ImageField() img3 = forms.ImageField() storage_amount = forms.IntegerField() description = forms.CharField(widget=forms.Textarea(attrs={'cols': 80, 'rows': 20})) Hot = forms.BooleanField(widget=forms.CheckboxInput()) type = forms.ChoiceField(widget=forms.RadioSelect, choices=PRODUCT_CHOICES) status = forms.ChoiceField(choices=STATUS) slug = forms.CharField() class Meta: model = Product fields = ('product_name', 'price', 'img', 'img2', 'img3', 'storage_amount', 'description', 'Hot', 'type', 'status', 'slug') views.py: if request.method == 'POST': form = Add_Product(data=request.POST) if form.is_valid(): product = form.save(commit=False) product.save() messages.success(request, 'Success') return redirect('/') else: form = Add_Product() context = {'form': form} return render(request, 'add_product.html', context) add_product.html: <form method="POST" class="card-body" > {% csrf_token %} <h3 style="text-align: center">Add Product</h3> {{ form … -
using Wagtail's site settings outside wagtail app
I have a Django project with a Wagtail app and I would like to use Wagtail Site settings outside Wagtail app but inside the Django project. The BaseSetting model seems to be well definded, I can setup fields and modify them through the Wagtail admin interface: @register_setting class MarketplaceSettings(BaseSetting): test = models.CharField(max_length=30, null=True) ... First try Following the documentation, I have tried to load settings template tags: within wagtail templates which was working within other templates of the project which was not working Second try I tried to create simple tags and inclusion tags in which I have loaded wagtail's site settings data, so that I could have loaded them in a template which was not holding a wagtail view but it was not working. Third try I tried to register get_settings function from wagtailsettings_tags.py module outside wagtail an call it within a template but it was also a fail. I feel like I am running out of ideas to solve this issue. If someone has a clue it would be great, i am sure there is a smart way to extend wagtail site settings to my entire project. -
Want to save chart.js charts to image using django cron job
I want to save the chart.js canvas HTML 5 tag chart to an image, with cron/batch job with using Django. Do let me know if is there anyway, as I have searched a lot but there is not any such type of library or package I found. The purpose of doing this to show images as a chart instead of a canvas tag, as we are facing issues while showing a chart in iPhone safari browser, due to memory issue. -
How do I debug python application? [duplicate]
How do I debug a python server application(e.g. django)? Right now I'm just using print statements but it's not the best way to it and there should be a better way. Is there a command line debugger available for python? -
Not able to figure out the way to call a function at the correct place in django website
I am working on a django website and have come across an error which I am not able to solve and Its been a couple of days but I wasnt able to solve the error. I am trying to integrate a payment gateway to my site. I have a payment button which on click is supposed to post the data to the database as well as go to the payment site. But it is storing the data but not going to payment site. Here is the javascript for my button: document.getElementById('payment-info').addEventListener('click', function (e) { submitFormData() }) function submitFormData() { console.log('Payment Button Clicked') var userFormData = { 'name': null, } var shippingInfo = { 'address': null, } shippingInfo.address = form.address.value userFormData.name=form.name.value var url = "/process_order/" fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'form': userFormData, 'shipping': shippingInfo }), }) .then((response) => response.json()) .then((data) => { console.log('Success:', data); alert('Transaction Completed') window.location.href = "{% url 'index' %}" }) } </script> This is my views.py: def processOrder(request): transaction_id = datetime.datetime.now().timestamp() data = json.loads(request.body) if request.user.is_authenticated: customer=request.user.customer order, created=Order.objects.get_or_create(customer=customer, complete=False) total=float(data['form']['total']) order.transaction_id=transaction_id if total == order.get_cart_total: order.complete = True order.save() ShippingAddress.objects.create( customer=customer, order=order, address=data['shipping']['address'], name=data['form']['name'], ) //Code for integration below param_dict = … -
Multiple slug_field in SlugRelatedField Django Rest Framework
In my Django application I am getting Json like this: "sales_order": 102, "transport_by": 4, I want to expand the sales_order and replace it with it's owner's first_name + last_name. So I tried using slugrelated field but I am not sure how to get two values out of it. Here's what I tried: class AtableSOSerializer(serializers.ModelSerializer): owner = serializers.SlugRelatedField(read_only=True, slug_field='first_name'+' '+'last_name') class Meta: model = MaterialRequest fields = "__all__" class AtableFlowListSerializer(serializers.ModelSerializer): class Meta: model = AllotmentFlow fields = "__all__" class AllotmentTableSerializer(serializers.ModelSerializer): flows = AtableFlowListSerializer(many=True) sales_order = AtableSOSerializer(read_only=True) class Meta: model = Allotment fields = "__all__" But obvious error appeared: AttributeError: 'User' object has no attribute 'first_name last_name' How do I get the first_name + last_name in my JSON? -
Django Heroku Error: ModuleNotFoundError: No module named 'herokuapp'
I am trying to deploy my django app to heroku, everything goes fine till I run heroku run python manage.py migrate Which throws this: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main PS E:\Django\Songdew> pip freeze > requirements.txt PS E:\Django\Songdew> git push heroku master Everything up-to-date PS E:\Django\Songdew> heroku run python manage.py migrate Running python manage.py migrate on ⬢ pratyushassignment... up, run.9308 (Free) Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/app/.heroku/python/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) PS E:\Django\Songdew> heroku run python manage.py migrate Running python manage.py migrate on ⬢ pratyushassignment... up, run.3297 (Free) Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/app/.heroku/python/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, … -
How can I change datefield in django?
I have a problem with DateField. How to do so that after clicking the button the date will change to the selected one?I set the date in admin panel. What am i doing wrong? models.py class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateField() views.py def profileView(request): user = User.objects.get(username='szymon') birth_date = user.student.birth_date formatedDate = birth_date.strftime("%d-%m-%Y") if request.method == "POST": j = request.POST['birth-date'] j = user.student.birth_date return render(request, 'home/profile.html', {'birth_date': formatedDate}) profile.html <p>data urodzin: {{birth_date}}</p> <form class="birth-form" method="post"> {% csrf_token %} <label for="usr"><b>Data urodzin: </b></label> <input type="date" data-date-format="DD MMMM YYYY" value='' name="birth-date" id="birth-date" required> <button class="btn btn-light">Zmień</button> -
Filtering Annotations in Django
I am annotating a QuerySet with a Count, but i only want to count certain objects, so I'm using a filter: objects = Parent.objects.annotate(num_children=Count('child',filter=Q(deleted_at=None))) The Filter is not working, the count for every object seems to be ignoring the filter, i.e. it also counts the children which have deleted_at != None The model: class child(models.Model): parent = models.ForeignKey('project.Parent', on_delete=models.CASCADE) deleted_at = models.DateTimeField(blank=True, null=True) Does anybody have a solution? Thanks in adcance. -
Django error: 404 URL Page not found error
I am getting this 404 error when I am trying to access the website using the url https://127.0.0.1:7000/nba/ -
views.py files not recognised as Python files in Pycharm
I am encountering problems while coding Django using Pycharm... As you could see from the picture, for unknown reasons my Python file were recognised as text files... Even if there are coloring, the auto-fill for my code is definitely different from writting in other Python files. Here is the screenshot: Screenshot Pretty much appreciate it! -
Memcache not closing socket
I am in the process of upgrading Django from 1.10 to 1.11. I have run into a resource warning about an unclosed socket. Memcache is not explicitly used in the project and I am sure it is some library causing this warning. /home/user/venvs/projenv/lib/python3.5/site-packages/memcache.py:1113: ResourceWarning: unclosed <socket.socket fd=3, family=AddressFamily.AF_INET, type=2049, proto=0, laddr=('127.0.0.1', 37332)> if self._get_socket() Does anyone know how I can go about fixing this, or whether it is something to worry about? -
Docker build diverges between local and cloud
I'm running a dockerized django admin and locally it runs perfectly when I specify the workdir as /app But when I try to do it on the circleci it just fails to find the dockerfile. If then I specify the workdir as /app/backend it finds it correctly. I thought of having a workdir when user runs it locally and when it runs on the cloud but there are other troubles with path imports on the later. project │ └───.circleci │ │ config.yml │ └───backend │ │ Dockerfile │ │ manage.py │ │ requirements.txt │ └───frontend FROM python:3.6.4 # Set the working directory to /app WORKDIR /app # Copy the current directory contents into the container at /app COPY . /app RUN apt-get update RUN apt-get -y install apache2 \ && apt-get -y install apache2-dev RUN pip install mod_wsgi RUN pip install cython==0.29.10 numpy==1.16.4 RUN pip install -r requirements.txt RUN mod_wsgi-express module-config > /etc/apache2/mods-available/wsgi.load RUN a2enmod wsgi RUN cat config/apache-server.conf >> /etc/apache2/apache2.conf RUN echo yes | python manage.py collectstatic VOLUME ["/var/log/apache2"] EXPOSE 80 443 CMD ["apache2ctl", "-D", "FOREGROUND"] Anyone knows why this happens, or how could I fix it? -
Django: how to count inner `sub_comment_set`?
i want to count the inner sub_comment_set that nested in ManyToManyField. it would be great if anybody could help me what i am trying to solve. thank you so much in advance. models.py: class Comments(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) class SubComments(models.Model): comment = models.ManyToManyField(Comments) serializers.py: class CommentsSerializer(serializers.ModelSerializer): subcomments_set = SubCommentsSerializer(many=True) class Meta: model = Comments fields = [ "id", "post_title", "name", "cover", "email", "subject", "subcomments_set", ] API data: [ { "id": 2, "post_title": "chilika_photography_02", "name": "kimberly", "cover": "/media/author_cover/batman.jpg", "email": "kimberlypatino01@gmail.com", "subject": "kimberly messages...", "subcomments_set": [ { "id": 4, "name": "zatty", "email": "zatty@gmail.com", "subject": "zatty messages02....", "datetime": "08/05/2020" }, { "id": 6, "name": "zatty", "email": "zatty@gmail.com", "subject": "zatty messages04....", "datetime": "08/05/2020" } ] }, ] -
How do I provide static files using Nginx on Heroku?
I created Django project and deployed it on Heroku. Also I created server Nginx on YandexCloud. I want to serve static files via Nginx. But it doesn't work. It's config Nginx: server { listen 80; listen 8080; listen 443; listen 8000; listen 5000; server_name calm-lake-64776.herokuapp.com; access_log /var/log/nginx/example.log; location /static/ { root /home/cheg/; expires 30d; } } I listening a lot of ports, because I don't know port where Heroku run my project. How do I find out? -
Using if else in django models.py
I'm trying to create an admin interface in my django models.py, such that when the status variable is selected to be completed it should ask for the various fields. class Event(models.Model): poster = models.ImageField(upload_to='EventPosters') title = models.CharField(max_length=200) description = models.TextField(max_length=350) STATUS = (('upcoming', 'upcoming'), ('completed', 'completed')) status = models.CharField(max_length=10, choices=STATUS, default='upcoming') if status == 'completed': report = models.TextField() images_url = models.URLField() no_of_images = models.CharField(max_length=1, validators=[DecimalValidator]) images_list = {} for i in range(int(no_of_images)): images_list[i] = models.ImageField(upload_to='EventImages') def __str__(self): return self.title Above is the class for the model that I am trying to create, I would like if the user selects the event is completed it should ask for the remaining fields in the admin panel automatically. Thanks in advance for any answers. -
Django + AWS s3 for media with Nginx
In localhost my AWS configuration works and all media files are keeped in my s3 bucket. settings.py AWS_ACCESS_KEY_ID = 'some_key' AWS_SECRET_ACCESS_KEY = 'F' AWS_STORAGE_BUCKET_NAME = 'my_bucket' AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' That works and the src of an image looks like: I deploied it on my Nginx server And now the src path look like: So I need the AWS path, but it references to local media (and the image isn't shown) Nginx configuration: server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html; index index.html index.htm index.nginx-debian.html; server_name _; /* HERE THE PATH TO MY AWS BACKET ===============================*/ location /media { proxy_pass https://diasmart-media-static.s3.amazonaws.com/; } /* ============END============ */ location /static { alias /root/DiaStore/src/assets; } location / { proxy_pass http://127.0.0.1:8001; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; add_header Access-Control-Allow-Origin *; } } Please help me, how I can solve it? -
How to include and use swagger schemas in Django?
I have a swagger schema with api methods for my Django project, but I don't know how can I include it in my project and use it... I have read about some plugins for rendering swagger schemas, but which I should chouse and how to work with that? -
Django runserver webpage 127.0.0.1 is refused to connect
After installing django it is showing successful install but when I use command python manage.py runserver, link http://127.0.0.1:8000/ is not getting open it means django framework is not working.. please help to find solution for this issue...