Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a seperate file for Sitemap?
I am trying to craete sitemaop in my website, but I craeted seperate sitemap for eact App, Please let me know how I can merge all sitemap urls in a single sitemap.xml file... Here is my urls.py file... from django.contrib.sitemaps.views import sitemap sitemapblog = { 'blog': BlogSitemap, } sitemapproject = { 'project':ProjectListSitemap } sitemaplocation = { 'location':LocationListSitemap } sitemaplocality = { 'locality':LocalityListSitemap } urlpatterns = [ path('sitemap/sitemapblog.xml', sitemap, {'sitemaps': sitemapblog}), path('sitemap/sitemapproject.xml', sitemap, {'sitemaps': sitemapproject}), path('sitemap/sitemaplocation.xml', sitemap, {'sitemaps': sitemaplocation}), path('sitemap/sitemaplocality.xml', sitemap, {'sitemaps': sitemaplocality}), ] and here is my sitemap.py file... class BlogSitemap(Sitemap): changefreq = "daily" priority = 0.5 def items(self): return Blog.objects.all() def lastmod(self, obj): return obj.updated_at def location(self, item): return reverse('page:blogsingle', args=[item.slug]) class LocationListSitemap(Sitemap): changefreq = "daily" priority = 0.5 def items(self): return Location.objects.all() def lastmod(self, obj): return obj.updated_at def location(self, item): return reverse('page:locationproject', args=[item.slug]) class LocalityListSitemap(Sitemap): changefreq = "daily" priority = 0.5 def items(self): return Locality.objects.all() def lastmod(self, obj): return obj.updated_at def location(self, item): return reverse('page:localityproject', args=[item.slug]) class ProjectListSitemap(Sitemap): changefreq = "daily" priority = 0.5 def items(self): return Project.objects.all() def lastmod(self, obj): return obj.updated_at def location(self, item): return reverse('page:projectview', args=[item.slug]) Now my current website url is this 127.0.0.1:8000/sitemap/sitemapblog.xml, and same url for other sitemap, but I want these all … -
How to see data in json form from a 3rd party website after inserting data in a html form using django framework?
Suppose , owner will give you a 3rd party website link. you're given a task where you'll create a simple html form and submit your personal info. Then fetch data and see it in json form using python django rest framework. No need to create model for your project since you're using 3rd party's database. Need views.py ,serializers.py,urls.py file. Suppose given url link: https://jobs.xyz.com/api/v1/recruiting-entities/ here's my html code: {% 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"> <meta name="description" content="Colorlib Templates"> <meta name="author" content="Colorlib"> <meta name="keywords" content="Colorlib Templates"> <!-- Title Page--> <title>Job Application Form</title> <!-- Icons font CSS--> <link href="{% static 'vendor/mdi-font/css/material-design-iconic-font.min.css' %}" rel="stylesheet" media="all"> <link href="{% static 'vendor/font-awesome-4.7/css/font-awesome.min.css' %}" rel="stylesheet" media="all"> <!-- Font special for pages--> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i,800,800i" rel="stylesheet"> <!-- Vendor CSS--> <link href="{% static 'vendor/select2/select2.min.css' %}" rel="stylesheet" media="all"> <link href="{% static 'vendor/datepicker/daterangepicker.css' %}" rel="stylesheet" media="all"> <!-- Main CSS--> <link href="{% static 'css/main.css' %}" rel="stylesheet" media="all"> </head> <body> <div class="page-wrapper bg-gra-03 p-t-45 p-b-50"> <div class="wrapper wrapper--w790"> <div class="card card-5"> <div class="card-heading"> <h2 class="title">Job Application Form</h2> </div> <div class="card-body"> <form method="POST"> {% csrf_token %} <div class="form-row"> <div class="name">Name</div> <div class="value"> <div class="input-group"> <input class="input--style-5" type="text" name="name" value="{{ name }}" … -
Cke editor youtube embend
I am currently working on a blog and I'm using CKE editor to create articles. I've also downloaded external plugins like codesnipped or youtube. However, I'm experiencing some troubles with the last one, because it doesn't appear in the toolbar as you can see in this image: Here's the code for the CKE EDITOR: CKEDITOR_CONFIGS = { 'default': {'toolbar': 'Custom', 'toolbar_Custom': [ ['Styles', 'Format', 'Bold', 'Italic', 'Underline', 'Strike', 'SpellChecker', 'Undo', 'Redo'], ['Link', 'Unlink', 'Anchor'], ['Image', 'youtube','Flash', 'Table', 'HorizontalRule'], ['TextColor', 'BGColor'], ['Smiley', 'SpecialChar'], ['Source'], ['CodeSnippet',] , ], 'extraPlugins': ','.join(['codesnippet','youtube']), } } And the models.py in case you need it: lass Post(models.Model): title = models.CharField(max_length=100) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) content = RichTextUploadingField() author = models.ForeignKey(Author, on_delete=models.CASCADE) thumbnail = models.ImageField() categories = models.ManyToManyField(Category) -
Development of Django project, code exception, automatically locate the exception to the code segment after the project is overloaded
Question: This is the case, I use VsCode to develop Django projects, I haven't finished writing a piece of code, but due to my operating habits, I will often ctrl + s, or the automatic save function provided by Vscode will save my code. At this time, the running Django project will be automatically reloaded, and because my code is not finished, reloading Django will definitely throw an exception, and Vscode will automatically locate the page where I wrote the code at this time. Where is the code segment where the exception occurs. Originally, I was happily writing code, and suddenly the page jumped to another location, which was terrible and greatly affected my development. I just switched from pycharm to vscode. This problem has affected me for several days. If it can’t be solved, I can’t use vscode to develop happily. I hope that vscode will not help me locate in my editing interface, it is enough to throw an exception in the terminal below. Friends who know the solution, please feel free to enlighten me~~~ Thank you My troubleshooting process: I tried my best to find the various settings of vscode, but I couldn't find the corresponding configuration … -
fake.date_between return always the same date in a loop
I try to implement an algo to create Django objects with random date over the last 2 years I use Faker and it work when I use it in a python shell: each time I call fake.date_between(start_date='today', end_date='+2y') it retunr a new datetime object but I want to do the same in django data migration but don't nderstand why it always return the same value for order in range(0,total_orders + 1): Orders.objects.create( table = random.sample(tables,k=1)[0], customers = random.randrange(1,6), split_bill = random.randrange(1,3), delivered = True, paid = True, created_at = fake.date_between(start_date='today', end_date='+2y') ) save 2020-12-16 17:57:04.203858+01 in postgresql database -
Problem with save method overriding attribute value
I have a model called 'Trip' with a Foreign Key to 'Destination'. The Destination model specifies a maximum number of passengers in it's 'max_passengers' attribute. Trip class Trip(models.Model): destination = models.ForeignKey( Destination, null=True, blank=False, on_delete=models.SET_NULL, related_name="trips", ) date = models.DateTimeField() seats_available = models.IntegerField( null=False, blank=False, editable=False ) trip_ref = models.CharField( max_length=32, null=True, editable=True, blank=True ) Destination class Destination(Product): max_passengers = models.IntegerField(null=True, blank=True) duration = models.CharField(max_length=20, blank=True) addons = models.ManyToManyField(AddOn) min_medical_threshold = models.IntegerField( default=0, null=False, blank=False ) def __str__(self): return self.name Back in the Trip model, I am overriding the model save method, so that when a trip object is created, the 'seats_available' for that instance is set to the 'max_passengers' of the related destination: def save(self, *args, **kwargs): if not self.trip_ref: date = (self.date).strftime("%m%d-%y") self.trip_ref = self.destination.pk + "-" + date if not self.seats_available: self.seats_available = self.destination.max_passengers super().save(*args, **kwargs) I have additional models for Bookings and Passengers. When a booking is created, a post_save signal is sent, calling the model method on my Trips model, def update_seats_avaialable(): def update_seats_available(self): reservations = ( self.bookings.aggregate(num_passengers=Count("passengers")) ["num_passengers"] ) self.seats_available = self.destination.max_passengers - reservations self.save() <---- PROBLEM THe problem is when all seats are finally taken ie. the passenger count = max_passengers and seats … -
Django queryset Product table and Product images table
I am developing an ecommerce website with Django. I had Product and Product_images models as below: class Product(models.Model): tags = models.ManyToManyField(Tag, related_name='products') same_product = models.ManyToManyField('self', related_name='same_products', blank=True) category = models.ForeignKey('Category', on_delete=models.CASCADE, related_name='product_categories') who_like = models.ManyToManyField(User, related_name='liked_products', blank=True) title = models.CharField('Title', max_length=100, db_index=True) slug = models.SlugField('Slug', max_length=110, unique = True) sku = models.CharField('SKU', max_length=50, db_index=True) description = models.TextField('Description', null=True, blank=True) sale_count = models.IntegerField('Sale Count', default=0) is_new = models.BooleanField('is_new', default=True) is_featured = models.BooleanField('is_featured', default=False) is_discount = models.BooleanField('is_discount', default=False) price = models.DecimalField('Price', max_digits=7, decimal_places=2) discount_value = models.IntegerField('Discount Value', null=True, blank=True) def __str__(self): return self.title class Product_images(models.Model): # product-un butun sekilleri burda saxlanacaq # is_main true olan esas shekildi # is_second_main olan shekil coxlu product sehifesinde hover edende gelen sekildi # relations product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images') # informations image = models.ImageField('Image', upload_to='media/product_images') is_main = models.BooleanField('Main Image', default=False) is_second_main = models.BooleanField('Second Main Image', default=False) # moderations status = models.BooleanField('Status', default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'image' verbose_name = 'Image' verbose_name_plural = 'Images' ordering = ('created_at',) def __str__(self): return f'{self.image}' In my Product_images I store several images for one Product, in Product_images model I wrote boolean fields with names is_main and is_second_main. In my template I want to get these … -
Getting 'undefined' when accessing existing field in django admin change_form.html from custom js
I am trying to learn how to work with custom js in django admin pages. admin.py: class TestAdmin(nested_admin.nested.NestedModelAdmin, tabbed_admin.TabbedModelAdmin): class Media: js = ("admin/js/vendor/jquery/jquery.js", "admin/js/jquery.init.js", "js/testChangeForm.js") tab_overview = ( (None, { 'fields': ('name', 'domain', 'visible') }), QuestionAdminInline ) tabs = [ ('Test content', tab_overview), ] testChangeForm.js: window.addEventListener("load", function () { if (!$) { $ = django.jQuery; } console.log($("#domain").val()) }); change_form.html from django admin contains select/option element with name="domain", but when I try to access it, it gives me undifined. I tried various suggested things, but I still can't get it to work. -
Django Models How To Upload Multiple Files For One Field
I'm looking to upload multiple images from my front-end form (VueJS) to my 'photos' field. However, even with my foreign key, I can only link one image at a time. (I tried ArrayField too, but didn't work) I know with Django forms.Form there's a widget option for 'attr multiple = True', but I can't seem to find a solution for models. class Photos(models.Model): photos = models.ImageField(upload_to='uploads/', null=True, default="") class Actors(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, default="") Writing_Samples = models.FileField(upload_to='uploads/', null=True, default="no samples") photos = ForeignKey( Photos, on_delete=models.CASCADE, default="", null=True) gallery = ArrayField( models.CharField(max_length=100), blank=True, default="") Thanks for your time! -
How to login in Django Rest Auth using username or email
In my django project, I am using django rest auth for api authentication. The default is to use username and password for login. I can also use email and password. But I want my user to have the option of either using email or username and password for login authentication; which I believe is more user friendly. How do I do this in django rest auth? -
django.db.utils.OperationalError no such table
Good evening, I am wondering what may the cause of a 'no such table' error in django. I have three databases defined in settings: a 'default' sqlite3 one and two postgresql ones. Out of my models defined in models.py, only one is specifically routed to 'default'. The other models have no routing settings set since they are meant to exist in all postgresql databases, just with different data. I write Model.objects.using(DBname) everywhere to make the DB access explicit. Migrations to all three of my databases were initially successful and, based on DB Browser and phAdmin, they all have the correct fields and data. In the 'context' variable sent to each rendered template, I send only the queryset after Model.objects.using(DBname), but within the template Django cannot see the tables. What could be the reason for django not being able to see them? What I think may be happening is that because the 'table not found' relates to a ForeignKey field of one of my models (a through table), Django is attempting to look for that model in the 'default' database instead of the database chosen during .using(). Does anyone possibly have any experience with anything like this? -
How make fucntional for create form?
I need to create functional to create forms: Create name of form (Generator) Create steps of form Create fields for steps Then I need to use this forms on this site. How can i do this? from django.db import models from enum import Enum class Generator(models.Model): name = models.CharField(max_length=255, verbose_name='Название') cost = models.DecimalField(max_digits=7, decimal_places=2, null=True) class Step(models.Model): generator = models.ForeignKey(Generator, on_delete=models.CASCADE, related_name='steps', verbose_name='Генератор') name = models.CharField(max_length=255, verbose_name='Название') class FieldChoices(Enum): text = 'text' email = 'email' tel = 'tel' url = 'url' password = 'password' number = 'number' search = 'search' date = 'date' time = 'time' range = 'range' radio = 'radio' checkbox = 'checkbox' color = 'color' file = 'file' hidden = 'hidden' class Field(models.Model): step = models.ForeignKey(Step, on_delete=models.CASCADE, related_name='fields', verbose_name='Шаг') name = models.CharField(max_length=255, verbose_name='Название') type = models.CharField(max_length=255, choices=((choice.name, choice.value) for choice in FieldChoices)) -
a raw query set is not retrieving data from the backend
views.py imports.html Here it gives an error I checked it part by part - its not retrieving the data to c_id and t_id from the database. Please suggest me solution to this Thank you. -
Errno 13 Permission denied, when trying to save an image
I have hosted my python + django project on pythonanywhere.com and I have encountered a problem, when I want to save an item with an image. All other fields of item are saving, but the image isnt. Here's the whole error: PermissionError at /admin/core/bike/add/ [Errno 13] Permission denied: '/home/omega/resizedComm/media_root/bikes/xx.png' My settings: STATIC_URL = '/static/' MEDIA_URL = '/media/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_in_env')] STATIC_ROOT = os.path.join(BASE_DIR, 'static_root') MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root') What can be causing this error? -
Django Rest Framework AttributeError: Got AttributeError when attempting to get a value for field
I have been trying to add attributes to the UserProfile by creating a OneToOneField to User and adding different fields. Now I run this and call the api with the body below. The api is able to successfully get parsed. A user gets created in the user table and user profile table with the correct attributes. However, Django returns an error AttributeError: Got AttributeError when attempting to get a value for field first_name on serializer UserProfileSerializer. This makes sense since the model does not have these attributes, but what is the correct way to pass the json in the same manner and create the user in the User Table and UserProfile Table? { "first_name": "Jay", "last_name" : "Patel", "email": "tes1t@email.com", "password": "password", "tier": "Gold", "bkms_id": "12234" } model.py # Create your models here. class UserProfile(models.Model): MedalType: List[Tuple[str, str]] = [('Bronze', 'Bronze'), ('Silver', 'Silver'), ('Gold', 'Gold')] bkms_id = models.PositiveIntegerField() tier = models.CharField(choices=MedalType, max_length=100) user = models.OneToOneField(to=User, on_delete=models.CASCADE) def __str__(self): return self.user.username serializer.py from typing import Dict from django.contrib.auth.models import User from rest_framework import serializers from authentication.models import UserProfile class UserProfileSerializer(serializers.ModelSerializer): password = serializers.CharField(max_length=65, min_length=8, write_only=True, required=True, style={'input_type': 'password'}) email = serializers.EmailField(max_length=255, min_length=4, required=True) first_name = serializers.CharField(max_length=255, min_length=2, required=True) last_name = serializers.CharField(max_length=255, … -
How to Solve price error in Django when I am displaying Data in my template?
I am trying to convert price in Lac and crore in India currency, suppose value is store in minprice' in this format (10000000), then it will display on my homepage in this format (1 cr), but I am getting this error ('>=' not supported between instances of 'NoneType' and 'int' `) in my website whenever I open any project. This issue with some projects. Please let me know how I can Solve this issue. I am stuck in this from last 5 Hours. Here is my models.py file... class Project(models.Model): name=models.CharField(null=True, max_length=114, help_text=f"Type: string, Values: Enter Project Name.") slug=models.SlugField(null=True, unique=True, max_length=114, help_text=f"Type: string, Values: Enter Project Slug.") here is my related model name, project has OneToOne relation with details... class Detail(models.Model): project = models.OneToOneField(Project, related_name='project_details', on_delete=models.CASCADE) minprice = models.IntegerField(null=True, blank=True, verbose_name="Minimum Price", help_text=f"Type: Int, Values: Enter Minimum Price") maxprice = models.IntegerField(null=True, blank=True, verbose_name='Maximum Price', help_text=f"Type: Int, Values: Enter Maximum Price") @property def min_price_tag(self): if self.minprice >=1000 and self.minprice <=99999: self.minprice=self.minprice//1000 return f"{self.minprice} K" elif self.minprice>=100000 and self.minprice<=9999999: self.minprice=self.minprice//100000 return f"{self.minprice} Lac" else: self.minprice=self.minprice/10000000 return f'{self.minprice} Cr' return str(self.minprice) if self.minprice is not None else "" @property def max_price_tag(self): if self.maxprice >=1000 and self.maxprice <=99999: self.maxprice=self.maxprice//1000 return f"{self.maxprice} K" elif self.maxprice>=100000 … -
Issue with Django recognizing URL passed parameter
I am learning Django and am having an issue with some simple testing and passing URL parameters. Here is my urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('custnames', views.custnames, name='custnames'), path('custdetail/<int:cust_id>/', views.cust_detail, name='cust_detail'), ] And here is my views.py def cust_detail(request, cust_id): return HttpResponse('<p>Cust Detail View with cust_id {cust_id}</p>') When I put this for my URL in my browser: http://localhost:8000/custdetail/1/ My output is: Cust Detail View with cust_id {cust_id} The "home" and "custnames" sections seem to work fine. Any ideas on what I'm doing wrong here? ~Ed -
How to get single item in Django Rest Framework
I have a database with cars, and each car has an id. To get all cars I would go at this route api/cars/, now I am trying to implement getting a single car which has id 1 and this is my urls: urlpatterns = [ path('api/cars/', CarsAPI.as_view()), path('api/cars/:id/', CarAPI.as_view()), path('api/tours/ongoing/', CarListOngoingAPI.as_view()) ] And this is my views for first path and second, class CarsAPI(generics.ListCreateAPIView): queryset = Car.objects.all() serializer_class = CarsSerializer # GET single car with id class CarAPI(generics.RetrieveAPIView): queryset = Car.objects.all() serializer_class = CarsSerializer class CarListOngoingAPI(generics.ListAPIView): queryset = Car.objects.all() serializer_class = CarsSerializer And here is my Car model: class Car(models.Model): make = models.CharField(max_length=100, blank=True) description = models.CharField(max_length=500, blank=True) ongoing = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) First class returs a list of all car models. Now I need to find a way to implement two other types, one where an argument is passed in, in my case id api/cars/:id/ and the second api/cars/ongoing/, I should say that these are just hypothethetical cases, just for learning purposes and any help is greatly appreciated. -
SynchronousOnlyOperation from celery task using gevent execution pool
Given celery running with these options: celery -A openwisp2 worker -l info --pool=gevent --concurrency=15 -Ofair Given this celery task from openwisp-monitoring: @shared_task def perform_check(uuid): """ Retrieves check according to the passed UUID and calls ``check.perform_check()`` """ try: check = get_check_model().objects.get(pk=uuid) except ObjectDoesNotExist: logger.warning(f'The check with uuid {uuid} has been deleted') return result = check.perform_check() if settings.DEBUG: # pragma: nocover print(json.dumps(result, indent=4, sort_keys=True)) Most of the time the task works, but some times (usually with bursts), the following exception is generated: SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. Full stack trace: SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. File "celery/app/trace.py", line 412, in trace_task R = retval = fun(*args, **kwargs) File "celery/app/trace.py", line 704, in __protected_call__ return self.run(*args, **kwargs) File "openwisp_monitoring/check/tasks.py", line 44, in perform_check check = get_check_model().objects.get(pk=uuid) File "django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "django/db/models/query.py", line 425, in get num = len(clone) File "django/db/models/query.py", line 269, in __len__ self._fetch_all() File "django/db/models/query.py", line 1308, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "django/db/models/query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "django/db/models/sql/compiler.py", line 1154, in execute_sql cursor = self.connection.cursor() File "django/utils/asyncio.py", line … -
Django - How to get a list of items with the latest element of some ID
For example I have these objects in my DB: [ Item(id: 1, created_at: 01/12/2020), Item(id: 1, created_at: 02/12/2020), Item(id: 2, created_at: 01/12/2020), Item(id: 2, created_at: 02/12/2020), Item(id: 2, created_at: 03/12/2020), ] What I want is latest items from that ID, like these in this example [ Item(id: 1, created_at: 02/12/2020), Item(id: 2, created_at: 03/12/2020), ] How can I filter these out? Thanks and regards -
Django: reference model fields from another model
I have two models. What i need is to reference the name and the email field from the Users model to the Customer model fields. Is the following way correct? class Users(AbstractBaseUser): name = models.CharField(max_length=200) email = models.CharField(max_length=200) from users.models import Users class Customer(models.Model): user = models.OneToOneField( Users, on_delete=models.CASCADE, null=True, blank=True) name = models.OneToOneField( Users.name, on_delete=models.CASCADE, null=True, blank=True) email = models.OneToOneField( Users.email, on_delete=models.CASCADE, null=True, blank=True) -
Creating custom filter for django-groups-manager
I have my own custom account model and installed django-groups-manager for handling members and groups and roles. So in views.py I have: from groups_manager.models import Group, GroupMemberRole, Member def clerks_view(request): accounts = Member.objects.all().reverse() account_filter = AccountFilter(request.GET, queryset=accounts) # I created AccountFilter in forms.py for account in accounts: # Do Something like: accounts_info[account].update({'joined_on': account.django_user.joined_on}) accounts_roles = GroupMemberRole.objects.filter(groupmember__member=account) for role in accounts_roles: roles['roles'].append(role) accounts_info[account].update(roles) context = {'accounts_info': accounts_info, 'account_filter': account_filter} return render(...) And in my template I have to do: <tbody> {% for account, fields in accounts_info.items %} <tr> <td><span class="text-primary">{{forloop.counter}}</td></span> <td class="td-actions"> <li><span class="text-primary">{{fields.joined_on.year}}/{{fields.joined_on.month}}/{{fields.joined_on.day}}</span></li> <li><span class="text-primary">{{fields.joined_on.hour}}:{{fields.joined_on.minute}}:{{fields.joined_on.second}}</span></li> </td> td><span class="text-primary">{{account.django_user.username}}</span></td> <td><span class="text-primary">{{account.django_user.first_name}} {{account.django_user.last_name}}</span></td> <td><span class="text-primary">{{account.django_user.team}}</span></td> <td class="td-actions"> {% for role in fields.roles %} <li><span class="text-primary">{{role.label}}</span></li> {% endfor %} </td> <td><span class="text-primary">{{account.django_user.description}}</span></td> </tr> {% endfor %} </tbody> I want to ask if we have a solution to make a filter.py for searching through these fields in my template. When I use {{account_filter.form}} in my template I can't filter above fields. Finally this is the way I made my filters.py: import django_filters from django_filters import DateFilter, CharFilter from groups_manager.models import Group, GroupMemberRole, Member class AccountFilter(django_filters.FilterSet): start_date = DateFilter(field_name="joined_on_p", lookup_expr="gte") end_date = DateFilter(field_name="joined_on_p", lookup_expr="lte") class Meta: model = Member fields = '__all__' -
Auto display the form's data in other view (django)
I'm using django forms to get some data from the user. It works well with the DB. How can I display that data (in a different page) right after submitting? The flow should be: The user fills the form Clicks submit (creates an object and saves to DB) The user is redirected to another page in which the data he just submitted is presented. Basically I need to pass the object's PK (the one the user just created) from one view to another. It's supposed to be fairly simple yet I couldn't find a decent solution for that issue. Thanks! -
Image is not editing after click on update button
I am going through a Django tutorial and My blog post image is not editing for edit post in my blog app. I use Django==3.1.2. views.py def edit_post(request, post_id): post = BlogPost.objects.get(id=post_id) if request.method != 'POST': form = UpdatePost(request.POST or None, request.FILES or None, instance=post) else: form = UpdatePost(instance=post, data=request.POST) if form.is_valid(): form.save() return redirect('mains:posts') context = {'post':post,'form':form} return render(request, 'mains/edit_post.html', context) forms.py class UpdatePost(forms.ModelForm): class Meta: model = BlogPost fields = ['blog_post_title','blog_description','image'] edit_post.html {% block content %} <div class="container"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <table> {{ form.as_table }} </table> <button type="submit">Save Changes</button> </form> </div> {% endblock content %} The Problem I am trying to edit my post in my blog app, Everything is working fine ( Blog title and Blog description is changing ) - when i change image it returns ( redirect ) fine BUT image not changing. I am stuck with this problem and have no idea what is wrong. What have i tried. 1). When i first create the view then i didn't add (request.POST or None, request.FILES or None), BUT when i notice that, this may be effecting from editing then i added and it still not editing the image. 2). I have also … -
Django BinanceSocketManager works on local machine but doesn't work on Nginx server
Recently I’m working on a Django project in which I need to get the price of some cryptocurrencies like BTC, ETH, and … So I used BinanceSocketManager in a class that uses multiprocessing. I used the tutorial from this link: https://livedataframe.com/live-cryptocurrency-data-python-tutorial/ It works fine on my local machine but when I started to deploy it to Centos 7 server, faced some problems. The problem is that the BinanceSocketManager doesn’t call the trade_prices function to pass the received message to it and get the prices. (I’m using Nginx webserver with Python version 3.6.8 and pip and gunicorn and daphne) Here is my code: import multiprocessing from binance.client import Client from binance.websockets import BinanceSocketManager global PRICES PRICES = {} PUBLIC = 'My-Public-key' SECRET = 'My-Private-key' # This method works on development mode but doesn't work on deploy mode! def trade_prices(msg): # I can see these print statements on my local machine terminal but not on the server! print("msg : ", msg) if msg['s'] == 'BTCUSDT': PRICES['BTCUSDT'] = [msg['c'], msg['P']] print("PRICES : ", PRICES) class Process(multiprocessing.Process): __instance = None @staticmethod def getInstance(): if Process.__instance is None: Process() return Process.__instance def __init__(self): super().__init__() if Process.__instance is not None: # raise Exception("This class is a …