Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Image is not Editing when i select it
I am going through a Django Tutorial. I am building a feature of Image Crop in my Blog App. BUT my selected image is not Editing. Here is my Code :- views.py def edit_photo(request): if request.method == 'POST': photo_form = EditProfilePhoto(request.POST, request.FILES, instance=request.user.profile) if photo_form.is_valid(): custom_form = photo_form.save(False) custom_form.save() return redirect('/') else: photo_form = EditProfilePhoto(instance=request.user.profile) args = {} args['photo_form'] = photo_form return render(request, 'edit_photo.html' , args) models.py class Profile(models.Model): name = models.CharField(max_length=22) user = models.ForeignKey(User,on_delete=models.CASCADE) image = models.ImageField(upload_to='images') forms.py class EditProfilePhoto(forms.ModelForm): class Meta: model = Profile fields = ['image',] widgets = {'image' : forms.FileInput} base.html {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- favicon --> <link rel="shortcut icon" type="image/jpg" href="{% static 'favicon.ico' %}"/> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384- TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <!-- jquery --> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <!-- cropper --> <script src="https://cdnjs.cloudflare.com/ajax/libs/cropper/4.1.0/cropper.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropper/4.1.0/cropper.min.css"> <!-- custom css & js--> <link rel="stylesheet" href={% static 'style.css' %}> <script src={% static 'main.js' %} defer></script> <title>image cropper</title> </head> <body> <div class="container mt-3"> </div> </body> </html> <p> main.js ( File in static folder in Project Directory ) const alertBox = document.getElementById('alert-box') const imageBox = document.getElementById('image-box') const editProfilePhoto = document.getElementById('editProfilePhoto-form') … -
Heroku error: filename.whl is not a supported wheel on this platform
I know this question has been posted many a time, but I am facing this error during Heroku Deployment for my Django Project. I have placed GDAL-3.1.4-cp38-cp38-win_amd64.whl in the root directory of the project. The .whl file installs successfully locally, but the mentioned error still persists during deployment. The GDAL_LIBRARY_PATH is set as: GDAL_LIBRARY_PATH = 'env/Lib/site-packages/osgeo/gdal301.dll' GEOS_LIBRARY_PATH = 'env/Lib/site-packages/osgeo/geos_c.dll' When I try: git push heroku master I get the following error: Enumerating objects: 14, done. Counting objects: 100% (14/14), done. Delta compression using up to 4 threads Compressing objects: 100% (10/10), done. Writing objects: 100% (10/10), 24.68 MiB | 1.57 MiB/s, done. Total 10 (delta 6), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Python has released a security update! Please consider upgrading to python-3.8.7 remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Requirements file has been changed, clearing cached dependencies remote: -----> Installing python-3.8.2 remote: -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 remote: ERROR: GDAL-3.1.4-cp38-cp38-win_amd64.whl is not a supported wheel on this platform. #This is the error remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: … -
Django Form does not load MultipleChoiceField data from POST request
I ve a weird issue with a MultipleChoiceField that does not return the items that are in the POST QueryDict here is the Form class TranslationLanguagesForm(forms.Form): languages = forms.MultipleChoiceField( widget=forms.SelectMultiple(attrs={"novalidate": "",}), choices=languages, required=False, ) the View is something like (shortened): class AjaxSpotlerCreateView(View): def post(self,request): # ... # some code before # translation_form = TranslationLanguagesForm( self.request.POST, prefix="translation" ) if translation_form.is_valid(): translation_languages = translation_form.cleaned_data.get( "languages" ) # # some code after # the issue is that the form is never "filled" by the data of request.POST and translation_languages receives always an empty list. ...but self.request.POST.getlist("translation-languages[]") returns the correct values It only happened on MultipleChoiceField whereas ChoiceField returns the correct value here are the POST data (you see more data than needed by the form with the issue because there are 4 forms and 1 formset in the view) : <QueryDict: {'csrfmiddlewaretoken': ['bQQzHTR4JDFZFnmO1ExlPZhqURHswXTmXA9RGC2c05pBM63ns2gnVwUnbnwGzor1'], 'transcription-language': ['en-us'], 'translation-languages[]': ['fr', 'es'], 'spotlers-TOTAL_FORMS': ['1'], 'spotlers-INITIAL_FORMS': ['1'], 'spotlers-MIN_NUM_FORMS': ['0'], 'spotlers-MAX_NUM_FORMS': ['1000'], 'spotlers-0-url': ['https://test-dev-s.storage.googleapis.com/uploads/FR/5e24512/2021/1/9fccac26/9fc37a26-2545-434f-8bd2-0afc3df839aa_full.mp4?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=storage%40funky-tower-264412.iam.gserviceaccount.com%2F20210108%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20210108T125533Z&X-Goog-Expires=3600&X-Goog-SignedHeaders=host&x-goog-signature=8e737cbc384fab5e11002cbc5e6308'], 'spotlers-0-id': ['9fc37a26-1893-434f-8bd2-0afc3df839ef'], 'spotlers-0-name': ['ultraclimb'], 'spotlers-0-duration': ['00:02:43'], 'spotlers-0-is_postedited': ['true'], 'keywords-keywords': [''], 'glossary-glossary': ['']}> -
Why my exclude filter remove different objects from the "same" django query applied to a foreign key?
The following queries and classes are simplified. The final objective is to look for the best selling products, providers, categories and other types of infos that would be useful in reports. Let's start by (trying) to find the sum of all products that have been sold, i.e, where the sales note is not None: >>> Product.objects.exclude( ... orderitem__order__salesnote__isnull=True ... ).aggregate(quantity_sum=Sum("orderitem__quantity"))["quantity_sum"] 9507578 Now, let's look for the providers: >>> Provider.objects.exclude( ... product__orderitem__order__salesnote__isnull=True ... ).aggregate(quantity_sum=Sum("product__orderitem__quantity"))["quantity_sum"] 8849003 If I remove the exclude filter, both queries returns the same amount: 9835691 Right now the db only have one order without a sales note: >>> for order in Order.objects.filter(salesnote__isnull=True): ... for item in order.orderitem_set.all(): ... print(item.product, item.quantity) ... Drum kit 3 What is causing this discrepancy? What am I doing wrong? models.py class AbstractSimplifiedModel(models.Model): name = models.CharField(max_length=150) def __str__(self): return str(self.name) class Meta: abstract = True class Provider(AbstractSimplifiedModel): pass class Category(AbstractSimplifiedModel): pass class Product(AbstractSimplifiedModel): price = models.DecimalField(max_digits=7, decimal_places=2) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) provider = models.ForeignKey(Provider, on_delete=models.CASCADE) class Store(AbstractSimplifiedModel): products = models.ManyToManyField(Product) class Customer(AbstractSimplifiedModel): pass class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) store = models.ForeignKey(Store, on_delete=models.SET_NULL, null=True) requested_at = models.DateTimeField() class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.PositiveSmallIntegerField(default=0) … -
Django FileField unable to save file
I'm currently trying to upload a file to my Django backend using the model InteractorFile, which has a FileField. This is the view I have written to do so: class FileView(APIView): parser_class = (FileUploadParser,) def post(self, request, format=None): # Get bytes from received file receivedFile = request.FILES['fileField'] my_bytes = receivedFile.file.read() f = open('./example.jpg', 'wb+') f.write(my_bytes) f.close() f = open('./example.jpg', 'rb') myFile = File(f) interactorFile = InteractorFile.objects.create(name='pepe', owner=request.user, fileField=myFile) return Response(status=status.HTTP_201_CREATED, data=FileSerializer(interactorFile).data) This is working correctly and saving the received content in a file called 'example.jpg'. However, I want to avoid creating a file and writing to it, because this is very slow. This is why I wanted to use the Django ContentFile class, given that it supposedly does the same as the File class, but can be supplied directly with bytes from the HTTP request. def post(self, request, format=None): # Get bytes from received file receivedFile = request.FILES['fileField'] my_bytes = receivedFile.file.read() myFile = ContentFile(my_bytes, name="example.jpg") interactorFile = InteractorFile.objects.create(name='pepe', owner=request.user) interactorFile.fileField.save(name="example.jpg", content=myFile) return Response(status=status.HTTP_201_CREATED, data=FileSerializer(interactorFile).data) This is saving the data in a file called 'None'. This should mean that I'm not passing the name to the FileField correctly. This has been driving me crazy and I would appreciate any help. It … -
psycopg2.errors.UndefinedTable: relation "functie" does not exist (table DOES exist)
I'm practicing on creating an API with Django and a Postgres DB. I'm trying to do a raw query (as this is a requirement) but I keep getting an error saying the table doesn't exist. I've set up an APIView for this, which for 1 table actually does work, but the same thing doesn't work for the other. Here's my code: class RetrieveEmployee(APIView): def get(self, request): data = user.objects.raw("SELECT 1 as id FROM user", []) print(data.query) serializer = serializers.EmployeeSerializer(data, many=True) return Response({"employee": serializer.data}) ^ This one does work. class RetrieveRole(APIView): def get(self, request): data = functie.objects.raw("SELECT 1 as id FROM functie", []) print(data.query) serializer = serializers.RoleSerializer(data, many=True) return Response({"role": serializer.data}) ^ This one doesn't. However, both tables 'user' and 'functie' do exist in my Postgres DB. Why does psycopg2 keep saying the relation doesn't exist? I've checked everywhere on spelling mistakes. Image: tables overview in Postgres -
Not able to get list of ManytoMany field using filter
views create = Create.objects.filter(campaign_id=campaign_id).values() print (create) saved = create.produces.filter(active=True).values() print(saved) models class Create(models.Model): user = models.ForeignKey(User,on_delete= models.CASCADE,blank=True) campaign = models.ForeignKey(Campaign,on_delete=models.CASCADE,blank=True) produces = models.ManyToManyField(Saved,blank=True) class Saved(models.Model): user = models.ForeignKey(User,on_delete= models.CASCADE,blank=True) unique_key = models.CharField(max_length=2000,default='') text = models.CharField(max_length=2000,default='') active = models.BooleanField(default=False,blank=True) How to get all saved with active=True It is giving error of saved = create.produces.filter(active=True).values() AttributeError: 'QuerySet' object has no attribute 'produces' in the output of print(create) their is no produce field -
Django : Media Images not displayed in templates
I am trying to create a blog and to display image for each post. i am trying to display user-uploaded images on a webpage. When I upload the image files using the Django admin interface (I made a model for Post images with an ImageField), the image is stored in /media/images correctly. But I can't display the image on my webpage. However, when I inspect my template with GoogleChrome, the path of my files are ok but there is a 500 error (about-us-2.jpg:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error). Media Settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'core/static'), ) Project urls.py: from django.conf.urls import include, url from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin' , admin.site.urls), path("", include("authentication.urls")), path("", include("app.urls")), ]+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) App urls.py: rom django.urls import path, re_path from django.conf.urls import include, url from app import views from . import views urlpatterns = [ path('', views.index, name='home'), url(r'^blog$', views.blog_view, name ='blog'), url(r'^blog/(?P<id>[0-9]+)$', views.post_view, name ='blog_post'), re_path(r'^.*\.*', views.pages, name='pages'), ] Views.py … -
Django Rest Api, Nested Serializers, OneToOne and ManyToMany relantions
I started to creating simple pizza ordering rest api for learning purpose. Creating simple model works perfertly fine, but when i trying to use model with relantions like oneToOne or ManyToMany post method stop working. My goal is to create new Order with always new OrderCredentials(OneToOne) and use existing dishes(ManyToMany) with one request my models: class Dish(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, unique=True) ingredients = models.JSONField(blank=True, null=True) price = models.FloatField() description = models.TextField(blank=True, null=True) def get_absolute_url(self): return reverse('dish_detail', args=[self.id]) class OrderCredentials(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) surname = models.CharField(max_length=255) street = models.CharField(max_length=255) houseNumber = models.CharField(max_length=255) flatNumber = models.CharField(max_length=255) phoneNumber = models.CharField(max_length=255) email = models.CharField(max_length=255) def get_absolute_url(self): return reverse('order_credentials_detail', args=[self.id]) class Order(models.Model): id = models.AutoField(primary_key=True) realized = models.IntegerField() dishes = models.ManyToManyField(Dish) credentials = models.OneToOneField(OrderCredentials, on_delete=models.CASCADE, blank=True, null=True) def get_absolute_url(self): return reverse('order_detail', args=[self.id]) OrderSerializer: class OrderSerializer(serializers.ModelSerializer): credentials = OrderCredentialsSerializer() # dishes = DishSerializer(many=True) class Meta: model = Order fields = ('id', 'realized', 'dishes', 'credentials') def create(self, validated_data): credentials_data = validated_data.pop('credentials') dishes_data = validated_data.pop('dishes') order = Order.objects.create(**validated_data) for dish_data in dishes_data: dish = Dish.objects.get_or_create(order=order, **dish_data) order.dishes.add(dish) credentials = OrderCredentials.objects.create(order=order, **credentials_data) order.credentials = credentials print(order) return order I tried to get dishes by id like this: Dish.objects.get(id = dish_data.id) but dish_data doesn't … -
Sending asynchronous email with celery in django project
have a good day. I watched how to install celery to my django project. From start to this step there is no problem actually. My purpose is when i submit a form from my web site, that request takes too much time with sending email and submitting. I installed celery for asynchronous tasks to send email seperately. My email sending function works fine without a delay. But i want to add a delay to it. Celery logs says the task is succeeded in bla-bla seconds but i got nothing in my email. this is my celery.py file import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_project.settings') os.environ.setdefault('FORKED_BY_MULTIPROCESSING', '1') app = Celery('django_project') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') this is my views.py def kaiserdicke(request): successful_submit = check_newsletter_submission(request) if request.method == "POST": send_email_task.delay( 'Information about Kaiser&Dicke', 'Hello there!', 'info @ xn - -denkmalgeschtztelofts - kic.de', [request.POST['email']] ) … -
how to drag and drop Django ManyToManyField using sortable.js?
how can i use sortable.min.js with django ManyToManyField form save. my code drag & drop table1 to table2 is working fine but when i press submit button the data is not saved in database. Because the (articles field) is not working fine. i don't understand how can i define javaScript function to save drag and drop data using sortable.min.js. my form is not post data because articles Field is not getting the drag & drop data. please can anybody tell me how can i use sortable.min.js with django form? models.py class SetRundown(models.Model): pool_title = models.CharField(max_length=200) articles = models.ManyToManyField(Article) index.html <form action="." method="POST"> <input class="form-control name="pool_title" id="id_pool_title"> <table class="table"> <thead> <tr> <th>ID</th> <th>Story</th> </tr> </thead> <tbody id="drop" name="articles"> {% for object in form.articles.field.queryset %} <tr> <td>{{ object.id }}</td> <td><a href="">{{ object.title|slice:":30" }}</a></td> </tr> {% endfor %} </tbody> </table> <table class="table"> <thead> <tr> <th>ID</th> <th>Story</th> </tr> </thead> <tbody id="drag" name="articles"> </tbody> </table> <button type="submit" class="btn btn-success">Submit</button> </form> <script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script> script.js new Sortable(drag, { group: '#id_articles', // set both lists to same group }); new Sortable(id_articles, { group: '#id_articles', // set both lists to same group animation: 150, }); -
how can i post the data "added_by"(in model.py) in APIVIEW which has a foreignkey relationship
In my models.py i have a field called "added_by" and it has a foreignkey relationship. Now i want to post the data in the ApiView through post method and i dont have idea how can i post it. can anyone help me with this.And the added by have a foreignkey relationship with User models.py '''from django.db import models # Create your models here. class RatingRates(models.Model): Rating = models.IntegerField() class UserMovie(models.Model): Movie = models.CharField(max_length=64) Title = models.CharField(max_length=128) #rates = models.OneToOneField(RatingRates, on_delete=models.CASCADE, null=True) def __str__(self): return self.Movie class JoinModel(models.Model): Movie=models.CharField(max_length=64) Title=models.CharField(max_length=128) Rating=models.IntegerField() ''' from django.db import models from django.contrib.auth.models import User from django.core.validators import MinValueValidator, MaxValueValidator class Movie(models.Model): title = models.CharField(max_length=128) director = models.CharField(max_length=128) added_by = models.ForeignKey(User, related_name="movie", on_delete=models.CASCADE, null=True) added_at = models.DateTimeField(auto_now_add=True) # rating=models.IntegerField() class Meta: db_table = "Movie" class Rating(models.Model): movie = models.ForeignKey(Movie, on_delete=models.CASCADE) rating = models.IntegerField(validators=[MinValueValidator(0),MaxValueValidator(5)]) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_rating') class Meta: db_table = "Rating" serializer.py class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = ['id', 'title', 'director'] class RatingSerializer(serializers.ModelSerializer): class Meta: model = Rating fields = ['id', 'movie','rating'] views.py class ListUsers(APIView): permission_classes = [IsAuthenticated] def get(self, request, format=None): movie=Movie.objects.all() serializer=MovieSerializer(movie,many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): movie_data = request.data new_movie = Movie.objects.create(title=movie_data["title"], director=movie_data[ "director"]) new_movie.save() serializer … -
Python generate a message with number between each word
I have coded something that allows me to generate a text. My message is my input and it returns me a new message with numbers instead of spaces. Here is an example : The problem is that some words like "goal" are cut at the end of the line (it's a website so the size is never the same). Is there a way to adjust the number of numbers between each word so that it displays correctly? Here is the code : def generate_grid(message): final_message = [] message_split = message.split(" ") words = [] for word in message_split: words.append(list(word)) # if I want to use letter insstead of numbers upper_case_alphabet = string.ascii_uppercase lower_case_alphabet = string.ascii_lowercase for word in words: final_message.append('<strong>') for i in range(len(word)): final_message.append(word[i].upper()) final_message.append('</strong>') random_number = random.randint(1, 3) for _ in range(random_number): random_char = random.randint(0, 9) final_message.append(str(random_char)) return mark_safe(" ".join(final_message)) -
Cannot import Javascript file in other Javascript file
For a project, I'm using Django for my backend, HTML/CSS/JS for frontend. For one HTML page, I use two JS files: dom_creator.js and console_page.js. I would like to use the functions of dom_creator in console_page, but whatever I try, I cannot find the right statement to import (and many of the ES6 import statements even make my console_page.js to stop working). I also have a module imported to my HTML (console_module.js). In that file, I have no issue importing dom_creator.js with import {function1, function2} from "./dom_creator.js" How would I be able to import functions from dom_creator in console_page.js (which is not a module)? I've tried all suggestions on Stack Overflow, but none of them seem to work. -
Earnings from websites?
My question is that I had created a dynamic website using HTML5 CSS3 Javascript Bootstrap Django sqlite3 Now my question is, I want to host the website and earn money but I don't know how to do this , what kind of technologies use for hosting these website and what is Best platform for hosting website. If i miss any kind of thing on these web development roadmap please guide me what can i do. One more thing how to host website on Google and how google paid for these. -
Unable to connect Django container and Spark Container
In my project there are a Django container, running well, and a Spark master container. I try to run a script in django with the call findspark.init(), but it raises an error: ValueError: Couldn't find Spark, make sure SPARK_HOME env is set or Spark is in an expected location (e.g. from homebrew installation). in Django requirements there are findspark, pyspark, pyspark-stubs & py4j, container has jdk installed so. Spark is working on another container, sure, Django can't find Spark because there is not... What is the configuration that allows Django container to connect with Spark container? or where must i set that spark is not local, is on another docker container? How could i set this "expected location" Thanks! my docker-compose: version: '3' services: web: build: . command: bash -c " python manage.py runserver 0.0.0.0:8000 & python manage.py migrate & python manage.py process_tasks" volumes: - .:/code ports: - "8000:8000" - "5556:5556" spark: image: docker.io/bitnami/spark:3-debian-10 environment: - SPARK_MODE=master - SPARK_RPC_AUTHENTICATION_ENABLED=no - SPARK_RPC_ENCRYPTION_ENABLED=no - SPARK_LOCAL_STORAGE_ENCRYPTION_ENABLED=no - SPARK_SSL_ENABLED=no ports: - '8080:8080' -
how to get ManyToMany field data in model save method
class Product(models.Model): varient_property = models.ManyToManyField(to='store.AttributeValue', blank=True) def save(self, *args, **kwargs): super(Product, self).save(*args, **kwargs) # here varient_propery is manytomany field # here i am saving this from django admin panel print(self.varient_property.all()) many to many class class AttributeValue(models.Model): value = models.CharField(max_length=30) available = models.BooleanField(default=True) def __str__(self): return self.value the print statement returns none how can I get many to many data after my model gets save? I want all set many-to-many relations. thanks in advance. -
How to append queried objects from Django database?
I have a model with 2 fields for numbers. I am trying to query those numbers and append them to each others. How do I do that? How do I work with queried objects? This is Model class Post(models.Model): title = models.CharField(max_length=100) num1 = models.IntegerField(blank=True,default=0) num2 = models.IntegerField(blank=True,default=0) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('diary:post-detail', kwargs={'pk': self.pk}) This is view (here I am trying to query and work with queried objects) def home(request): a = Post.objects.values('num1') b = Post.objects.values('num2') result = a + b context = { 'result': result, } return render(request, 'diary/home.html', context) This is a working part of my template {% for x in result %} <p> {{ x }} </p> {% endfor %} This is the error I get TypeError at / unsupported operand type(s) for +: 'QuerySet' and 'QuerySet' C:\Users\detal\Coding\Trading Diary3\TradingDiary\diary\views.py, line 11, in home result = a + b -
Django: How To Only Show Items From One User
I am trying to make a list of posts only from one user so that i can loop through them in the template to display them. How would i write this as a filter? or is that even the best way to do this? views: def collection(request): staff_picks = Collection.objects.filter(author="Staff") context = { 'collections': Collection.objects.all(), 'staff_picks': staff_picks, } return render(request, 'collections.html', context) templates: {% for item in staff_picks %} <div class="collection"> <div class="collection_container"> <div class="collection_image_container"> <a href="{% url 'collectiondetail' item.id %}"><img src="{{ item.collection_image.url }}"></a> </div> <div class="collection_name_container"> {{ item.collection_name }} </div> </div> </div> {% endfor %} </div> -
Django views - can't create object with existing ForeignKey that is an empty string
I have a model that allows having an empty string as a primary key: class District(models.Model): district = models.CharField(max_length=4, primary_key=True, blank=True) I have created one and it exists in the database as an empty string district = '', but when I test a POST request with django views to another model where district is a foreign key I get the below error: This is weird because the view dropdown is clearly referencing the empty string choice. The model where district is foreign key: class OutwardCode(models.Model): area = models.ForeignKey(Area, models.DO_NOTHING) district = models.ForeignKey(District, models.DO_NOTHING) -
Subprocess and os.Popen in django not running under apache with mod_wsgi at Linux Fedora30
I have problem to run Os.Popen and subprocess in django under apache server of linux fedora30 when I run apache I can not run below command with that: command3 = "[ -f /home/mohammad/jointodomain.txt ] || echo 'Username : '%s'\n\nPassword:'%s'\n\nDomain_name:'%s'\n\nDomain_ip:'%s > /home/mohammad/jointodomain.txt " %(username,password,domain_name , domain_ip ) o = os.popen(command3) command4 = "[ -f /home/mohammad/jointodomain.txt ] && echo 'Username : '%s'\n\nPassword:'%s'\n\nDomain_name:'%s'\n\nDomain_ip:'%s > /home/mohammad/jointodomain.txt " %(username,password,domain_name , domain_ip ) o1 = os.popen(command4) These are all jobs that are do : 1. I use Fedora30 2. Then install and update yum and other packeges such below command: yum update sudo systemctl stop firewalld.service yum install python-pip python-devel python3-pip python3-devel pip3 install --upgrade pip pip3 install virtualenv dnf install httpd yum install python3-mod_wsgi.x86_64 3. Then make a directory and install Django on virtual env: mkdir /home/mohammad/myweb1 cd myweb1 virtualenv venv source venv/bin/activate 4. Then pip install below packages: asgiref==3.3.1 Django==3.1.5 psycopg2-binary==2.8.6 python-pam==1.8.4 pytz==2020.5 sqlparse==0.4.1 5. Then config other settings of django : django-admin startproject myproject cd myproject python manage.py startapp main python manage.py collectstatic python manage.py makemigrations python manage.py migrate 6. now config settings.py After these 3 steps I configure settings.py in django: ALLOWED_HOSTS = ['*'] STATIC_ROOT ='/home/mohammad/myweb1/myproject/main/static/' 7. apache config which make django.conf … -
DRF , adding serilizer
Here take a look at my code class GetFollowers(ListAPIView): """ Returns the users who follw user,along with weather the visiter — the one who sent api request — follows them or they follow him/her """ permission_classes = [IsAuthenticated,] pagination_classes = PageNumberPagination serializer_class = FollowersSerilizer def get_queryset(self,*args,**kwargs): print('Error') user = self.request.data.get('user',None) if user is None: raise ValidationError(detail={'user':'This field is required — send as a query_param'}) user, created = User.objects.get_or_create(username=user) if created: raise ValidationError(detail={'user':'Invalid username'}) visiter = self.request.user if user.profile.private: followers_obj, created = Follow.objects.get_or_create(user=user.profile) if not followers_obj.followers.filter(username=user).exists(): raise ValidationError(detail={'Private account':'This account is private , follow the user to access the followers'}) qs = {} #queryset _all_ = [] followers_obj, created = Follow.objects.get_or_create(user=user.profile) all_followers = followers_obj.followers.all() # FOllowers are User instances for follower in all_followers: user_info = [] follower_username = follower.username follower_profile_picture = follower.profile.profile_picture if len(follower.first_name) == 0 and len(follower.slast_name) == 0 : follower_name = follower_username else: follower_name = follower.get_full_name() follower_follows_me = follows(follower,visiter) i_follow_follower = follows(visiter,follower) follower_ispublic = not follower.profile.private user_info.append(follower_username,follower_profile_picture,follower_name,follower_follows_me,i_follow_follower,follower_ispublic) _all_.append(user_info) qs['followers'] = _all_ return qs Now see my serilizer class FollowersSerilizer(serializers.ModelSerializer): class Meta: model = Follow fields = ['followers'] The fields in my queryset , I've got a lot of fields belonging from two serilizers. How do I add a serilizer … -
New Django website on DigitalOcean droplet
I am having a Django website on a DigitalOcean droplet which I uploaded using Nginx Server but I don't know how can I add more Django website on the same droplet and even I can't find any tutorial for the same. Please Help Me! -
Why is the port not being mapped correctly?
I have a Github Action to run some tests in Python. Those tests need a postgressql service, so I create it and map the necessary port. To save time installing some dependencies, I use a docker container to run the action, with the following Dockerfile: FROM ubuntu:16.04 RUN apt update && \ apt install -y gdal-bin python2.7 python-pip git && \ pip install --upgrade pip==9.0.1 EXPOSE 5432 WORKDIR /usr/src/app And for the Github Action, I have the following workflow file: name: Run python tests on: [push] jobs: test: runs-on: ubuntu-16.04 container: image: ghcr.io/myorg/python-unit-tests credentials: username: ${{ github.repository_owner }} password: ${{ secrets.BOT_GITHUB_REGISTRY_TOKEN }} strategy: matrix: group: [1] services: postgres: image: cheewai/postgis:postgres-10.1 env: PG_USER: postgres PG_PASSWORD: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: test ports: - 5432:5432 options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 steps: - uses: actions/checkout@v2 - name: Install dependencies run: | pip install -r requirements.txt pip install -r requirements_dev.txt - name: Prepare database run: | python manage.py migrate --noinput --settings=<somesettings> - name: Running tests (page ${{ matrix.group }}) run: echo 'Run tests¡ With this configuration, it should be working nicely, but when I run it I get the following error: django.db.utils.OperationalError: could not connect to server: Connection refused … -
Django - After overriding the base_site.html, i was unable to publish my post and causing CSRF error
Here is my code for base_site.html {% extends "admin/base.html" %} {% load static %} {% block title %}{% if subtitle %}{{ subtitle }} | {% endif %}{{ title }} | {{ site_title|default:_('Admin') }} {% endblock %} {% block extrastyle %} <style type="text/css"> #branding h1{ color: #fff !important; } #branding h1 a:link, #branding h1 a:visited { color: #fff !important; } .submit-row input{ background-color: #00b388; } #header { background-color: #000000; color: #fff !important; } .module caption{ background-color: #00b388; } div.breadcrumbs { background: #00b388; } .object-tools a.addlink{ background-color: #00b388; } input[type=submit].default, .submit-row input.default{ background-color: #00b388; } </style> {% endblock %} {% block branding %} <form method="post">{% csrf_token %} <h1 id="site-name"><a href="{% url 'admin:index' %}"><img src="{% static 'img/logo.PNG' %}" height="30px" /></a></h1> {% endblock %} {% block nav-global %} {% endblock %} unfortunately i have added the <form> tag in the above code, just to over come with CSRF issue and it does. unfortunately, this approach gives me another error, i.e, i have 3 file fields in my Model, and even though, i have mentioned the files during the upload and when i hit submit, it is not working and keep showing me This field is required error. I am new to Django and your …