Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filtering posts from yesterday, last week and last month doesn't work
I am using a simple form to filter posts based on yesterday, last week, last month and last year. And this is the view, how I wanted it to be handled: def search(request): # filter by date added list_date = request.GET.get('list_date') today = timezone.now() if list_date: if list_date == 'yesterday': yesterday = today - timedelta(days=1) print(yesterday, 'yesterday') queryset = queryset.filter(listing_date__lt=yesterday) print(queryset) elif list_date == 'lastweek': lastweek = today - timedelta(weeks=1) queryset = queryset.filter(listing_date__lt=lastweek) elif list_date == 'lastmonth': lastmonth = today - timedelta(days=30) queryset = queryset.filter(listing_date__lt=lastmonth) elif list_date == 'lastyear': lastyear = today - timedelta(days=365) queryset = queryset.filter(listing_date__lt=lastyear) context = { 'listings': queryset, } return render(request, 'listing/listings.html', context) and in model: listing_date = models.DateTimeField(auto_now_add=True). I printed yesterday and queryset above and it returns this in console: 2020-05-26 03:54:45.107533+00:00 yesterday <QuerySet []> I filtered posts by yesterday, but why the queryset is empty, although I am sure posts were created yesterday? -
How to get data from other table in django with Foreign Key(New to Django)
I have Two table MeterDetail,EnergyData class MeterDetail(models.Model): metername = models.CharField(max_length=20) meter_id = models.IntegerField() meter_type = models.CharField(max_length=20) meter_purpose = models.CharField(max_length=20)#auto_now_add=True meter_location = models.CharField(max_length=20) class Meta: db_table = 'meterdetails' def __str__(self): return str(self.meter_id) class EnergyData(models.Model): last_kwh = models.FloatField() date_time_recorded = models.DateTimeField(default=timezone.now)#auto_now_add=True meter_id = models.ForeignKey(MeterDetail,on_delete=models.CASCADE,related_name="meter_details") class Meta: db_table = 'energydata' get_latest_by = "date_time_recorded" def __str__(self): return str(self.last_kwh) I want to get data from second table using first object. I tried in shell t= MeterDetail.objects.get(meter_id=1) am unable to read this below one t.energydata_set.all() -
Pass dynamic form values in defaults attribute of update_or_create method in django
I want to create a post using foreign key if the post is not existed and i want it to be updated using the same foreign key if it already existed using the identical form. I had used create_or_update method of django but I had not got insight about it. What should we used in the default attribute of create_or_update method of django. I want the form data to be posted what user enters into the form. models.py class EventDetail(models.Model): event = models.ForeignKey(Event,default=None,on_delete=models.CASCADE) event_summary = models.CharField(max_length=255,null=True) event_details = RichTextUploadingField(null=True) timestamps = models.DateTimeField(auto_now_add=True,auto_now=False) updated = models.DateTimeField(auto_now_add=False,auto_now=True) I have Event model and EventDetail Model. The Event Detail Model consists of event as foreign key. After creating event, the url redirects to eventdetail where the form for posting event summary and event details are available. I want the form to be created and posted dynamically by user's input if the summary and details are not posted before and I want the form to be updated if the data are already available before i.e The data should be updated. I also want the foreign key to be stored automatically after the event details has been created. -
How to get instagram (profile pic & total followers number) by webscraping(python) Using username?
I am trying to get instagram-followers count and profile pic by using web-scraping python but can't do this, someone help me please for this task by sharing a bit of code Thanks in advance -
Is there a way to allow different templates to cross-read content in Django?
I'm working on a project, that pulls data from local database and organizes it into a directory, then calls a API to display the price of each item, this is how I implemented it in Views.py class MarketgroupsListView(generic.ListView): model = Marketgroups context_object_name = 'marketgroups' template_name = 'sde/marketgroups_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) pk = self.kwargs['pk'] context['marketgroups'] = Marketgroups.objects.filter(parentgroupid=pk).order_by('marketgroupid') #get marketgroups list context['invtypes'] = Invtypes.objects.filter(marketgroupid=pk).order_by('typeid') #get items list return context class InvtypeDetailView(generic.DetailView): model = Invtypes def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) pk = self.kwargs['pk'] url = '/api/typeid={0}'.format(pk) response = requests.get(url) context['data'] = xmltodict.parse(response.content)['price'] return context This works, but the price data can only be showed in the InvtypeDetailView. I want MarketgroupsListView can read and display the price data too so people can check the price data for entire list of items at once. But I don't know how to do that. I tried putting the API calling code into class MarketgroupsListView, but it only gets the pk of the current URL which is a marketgroups' not a invtypes So is there a way to cross-read content between different views or different templates? Or are there other solutions? -
Is it safe to reuse multiple models with the same generic view?
I have a project with around 60 models so creating a unique Detail, Create, Update, Delete APIView for each would be a lot of wasted resources (or so it feels like). Would it be better performance-wise (or safe?) to simply create a generic view that could cycle between each model like so? _CLASSES = <Dictionary of my classes> class GenericModelView(APIView): def get(self, request, model_name): # model_name would be a required part of the URL. model_class = _CLASSES[model_name] serializer_class = model_class.serializer_class # I would instantiate a serializer for each model_class return Response(serializer_class(model_class.objects.all()).data) -
Django unable to resolve the import type
Iam a newbie learning django iam struck here can someone help on this. i followed this tutorial https://www.youtube.com/watch?v=RMTVAIVrdtM Iam using pycharm IDE, created on the similar lines but still iam getting the error. from poll import view as poll_views ### Getting error in this line .....----<<<<<<< urlpatterns = [ path('admin/', admin.site.urls), path(''.poll_views.home,name='home'), path('create/'.poll_views.create, name='create'), path('vote/<poll_id>'.poll_views.vote, name='vote'), path('results/<poll_id>'.poll_views.results, name='results'), ] On terminal (test) C:\Users\Learner\projects\poll_project>python manage.py migrate Traceback (most recent call last): File "C:\Users\Learner\projects\poll_project\manage.py", line 21, in <module> main() File "C:\Users\Learner\projects\poll_project\manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\management\base.py", line 366, in execute self.check() File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\management\commands\migrate.py", line 64, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Learner\Envs\test\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Learner\Envs\test\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\Learner\Envs\test\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Learner\Envs\test\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Learner\Envs\test\lib\site-packages\django\utils\functional.py", line 48, in __get__ … -
Django lock media url with login
I am writing a django website and using the media url function and login logout function. Currently, all the users with and without login can view the media via http://127.0.0.1:8000/media/image1.jpg but what I want is that if the user is not login, they cannot view the pictures in the media with hardcoding the URL. I dont know if django can do this function because I cannot find related question in the internet. -
How to create a filter on the ForeignKey Field in a Django Model?
I have a Detail Model which has a ForeignKey of the default User Model of Django. It works fine, but I want the ForeignKey to be attached to only those users which are neither staff nor superuser. My Detail model is below: class Detail(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(max_length=50) skype_session_attendance = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(20)], verbose_name="Skype Session Attendances (of this subject, in numbers)", help_text="Enter the numbers of skype sessions of this subject, the student attended out of 20.") internal_course_marks = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(40)], verbose_name="Internal Course Marks (of this subject, in numbers)", help_text="Enter the total internal course marks of this subject, the student obtained out of 40.") programming_lab_activity = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(25)], verbose_name="Programming Lab Activities (of this subject, in numbers)", help_text="Enter the total numbers of programming lab activities of this subject, the student participated in, out of 25.") mid_term_marks = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(45)], verbose_name="Mid_Term Marks (of this subject, in numbers)", help_text="Enter the total mid-term marks of this subject, the student obtained out of 45.") final_term_marks = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(90)], verbose_name="Final_Term Marks (of this subject, in numbers)", help_text="Enter the total final-term marks of this subject, the student obtained out of 90.") def __str__(self): return f'{self.user.username}-{self.subject}' I want something like below: user = models.ForeignKey(User, on_delete=models.CASCADE, filter(not user.is_superuser, … -
Django - maximum recursion depth exceeded while calling a Python object
Error Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0.6 Python Version: 3.8.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', 'leads'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /home/radu/Documents/work/ProtocolV6/protocol/core/templates/base_generic.html, error at line 57 maximum recursion depth exceeded while calling a Python object 47 : href="plugins/owl.carousel/dist/assets/owl.carousel.min.css" 48 : /> 49 : <link 50 : rel="stylesheet" 51 : href="plugins/owl.carousel/dist/assets/owl.theme.default.min.css" 52 : /> 53 : <link rel="stylesheet" href="dist/css/theme.min.css" /> 54 : </head> 55 : 56 : <body> 57 : {% include "header.html" %} {% include "header.html" %} {% block content %} 58 : {% endblock %} 59 : </body> 60 : </html> 61 : Traceback (most recent call last): File "/home/radu/.local/share/virtualenvs/ProtocolV6-LVs3tHy5/lib/python3.8/site-packages/django/template/base.py", line 765, in __init__ self.literal = float(var) During handling of the above exception (could not convert string to float: '"header.html"'), another exception occurred: File "/home/radu/.local/share/virtualenvs/ProtocolV6-LVs3tHy5/lib/python3.8/site-packages/django/template/base.py", line 903, in render_annotated return self.render(context) File "/home/radu/.local/share/virtualenvs/ProtocolV6-LVs3tHy5/lib/python3.8/site-packages/django/template/loader_tags.py", line 127, in render compiled_parent = self.get_parent(context) File "/home/radu/.local/share/virtualenvs/ProtocolV6-LVs3tHy5/lib/python3.8/site-packages/django/template/loader_tags.py", line 124, in get_parent return self.find_template(parent, context) File "/home/radu/.local/share/virtualenvs/ProtocolV6-LVs3tHy5/lib/python3.8/site-packages/django/template/loader_tags.py", line 103, in find_template template, origin = context.template.engine.find_template( File "/home/radu/.local/share/virtualenvs/ProtocolV6-LVs3tHy5/lib/python3.8/site-packages/django/template/engine.py", line 125, in find_template template = loader.get_template(name, skip=skip) File "/home/radu/.local/share/virtualenvs/ProtocolV6-LVs3tHy5/lib/python3.8/site-packages/django/template/loaders/base.py", line 29, in get_template return Template( File "/home/radu/.local/share/virtualenvs/ProtocolV6-LVs3tHy5/lib/python3.8/site-packages/django/template/base.py", line 156, in … -
i can't login with my users in django admin interface
i have problems with the django rest framework, im using a custom user and i try to authenticate when i create a superuser with d shell i can easily login to my django admin interface and the rest login interface , i create a normal user but i cant login and even if i changed is_admin,is_superuser and is_staff to true , i still cant login to both interfaces ,idk what is d problem , plz any suggestion to solve this . i didn't put any code, i have no idea what is related with d prob . thanks. -
django orm categorize by some field
class Model(models.Model): types = models.CharField(choices=Choice('A', 'B', 'C', max_length=4) and I want to get a result like this { 'A' : [ModelObject(1), ModelObject(3), ModelObject(4)], 'B' : [ModelObject(2), ModelObject(6)], 'C' : [ModelObject(5), ModelObject(7), ModelObject(8)] } Are there any neat orm functions without using too many functions? -
Do you need a view when working with Page model in Wagtail?
I'm using Wagtail, I've 2 pages: a) Ministerios Internacionales Elim b) Doctrina Elim I want to set a as homepage, and b to: http://127.0.0.1:8000/doctrina-elim/ I've this model in doctrina/models.py: class DoctrinaIndexPage(Page): template = 'doctrina/doctrina_index_page.html' nivel = models.CharField(max_length=255, default='Básico') subtitle = models.CharField(max_length=255, default='Publicación reciente') body = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('subtitle', classname="full"), FieldPanel('body', classname="full") ] The view has this (doctrina/views.py): from django.shortcuts import render # Create your views here. def home_page(response): return render(response, "home/home_page.html") # Create your views here. def doctrina_index_page(response): return render(response, "doctrina/doctrina_index_page.html") In promote tab, it has this url: doctrina-elim But entering that after the hostname gives 404, why? Structure: -doctrina |__pycache.py_ |__migrations.py |__templates |___init__.py |_admin.py |_apps.py |_models.py |_test.py |_urls.py |_views.py -elim |__pycache_.py |_settings.py |_static |_templates |___init__.py |_urls.py |_wsgi.py -home |__pycache_.py |_migrations.py |_static |_templates \ home |_home_page.html |_welcome_page.html |___init__.py |_models.py |_urls.py |_views.py I can only access my Page models when setting them as sites, and visit the "/" home. -
Customize default message djangorestframeworksimple-jwt retrieved when the user/password is incorrect?
I'm using django 3.0.5 ,djangorestframework 3.11.0 and djangorestframework-simplejwt 4.4.0 I have used drf simple-jwt to authenticate, and all works fine. When the password is incorrect, the response is {"detail":"No active account found with the given credentials"} I need to customize this response. I have checked this message inside a dictionary in the class TokenObtainSerializer default_error_messages = { 'no_active_account': _('No active account found with the given credentials') } I have tried to override this class with no success. Any ideas? Thanks in advance. -
Django: translating URLS patterns not working
I'm working with Django 2.2, and it's the first time I use it in a real project. I'm trying to translate my site between two languages (english and spanish) and everything was going well. Text inside templates translates fine, and I even created a button to switch languages, but I can't translate URL patterns. I followed the django docs for Translating URL patterns but they don't get translated. I don't know if I'm missing something. I would really appreciate your help. Here's my main urls.py file: from django.conf.urls.i18n import i18n_patterns from django.contrib import admin from django.urls import include, path urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), path('admin/', admin.site.urls), ] urlpatterns += i18n_patterns( path('',include('landing_page.urls')), ) Landing page urls.py file: from django.urls import include, path from django.utils.translation import gettext_lazy as _ from . import views urlpatterns = [ path('', views.index, name='index'), path(_('about'), views.about, name='about'), path(_('contact'), views.contact, name='contact'), ] Of course I already created entries for these translations on my locale files. It doesn't throw me any error, I just get the URL with the prefix, but the "page name" on it doesn't change. -
Celery Setting Up Multiple Queues/Workers on Heroku
New to celery here and I have a project that uses it to run periodic tasks. Some tasks take some time and are lower priority so I'd like to move them to a slow queue. However, when I setup two Queues, I notice only one is active - inspect().active_queues() shows the slow queue is running all of the tasks. Now this is strange to me because I am only defining @app.task(queue=Queues.BACKGROUND_CRAWL) on a couple of tasks and tasks without that queue seem to be getting processed on that queue. I've looked through the heroku docs and celery docs and was surprised it was so hard to figure out what was going wrong with the setup. Part of me thinks it's how I am setting up the queues in my procfile. Do I need two workers, or can one worker leverage two queues? I also thought without defining -Q on the first worker it would setup the default celery queue. My procfile - worker: celery worker -A workers.celery.app worker: celery worker -A workers.celery.app -Q background_crawl_queue beat: celery --app=workers.celery.app beat My Celery App looks like - app = Celery( "app", broker=config("REDIS_URL"), backend=config("REDIS_URL"), redbeat_redis_url=config("REDIS_URL"), ) class Queues: DEFAULT = app.conf.task_default_queue BACKGROUND_CRAWLS = "background_crawl_queue" … -
Django RelatedManager: Get currently selected element's value
I have a model that has a duration value, and a durations object, which in turn has multiple duration_mins values inside. The root-level duration acts as a fallback if the durations object is empty. Endpoint response is something like this: { "id": 1, "name": "Track Name X", "duration": 10, "durations": [ { "id": 218, "duration_mins": 10 }, { "id": 219, "duration_mins": 15 }, { "id": 220, "duration_mins": 20 } ] } The main idea is to have a sum of "Minutes listened". Right now, we are doing self.total_sec += single.duration Which correctly adds the fallback, root-level duration. What I want to do is add the current duration value (sent by the client). ie: if the user selected the 20 min. duration. I tried the following: if single.durations: self.total_sec += single.durations.get().duration_mins else: self.total_sec += single.duration Which obviously doesn't work, but explains what I'm trying to accomplish. The error I'm getting is either: AttributeError: 'RelatedManager' object has no attribute 'duration_in_minutes' or, if I append .get() [...]MultipleObjectsReturned: get() returned more than one Duration -- it returned 3! Can anybody tell me how to get the currently selected duration? (Assuming the client is sending the corresponding duration id) Thanks! -
Heroku/Django: Project isn't migrating, throws error about missing tables when you run manage.py migrate
I've got some issues with a project I made. Everything tests good locally but after I got it onto Heroku, it doesn't work. It's complaining about missing tables which, I thought, would be created when I migrated it but that isn't working. The database is currently empty. I'm using dj_database_url for the setup on Heroku. Error: Running bash on ⬢ fcf-demo... up, run.6802 (Free) ~ $ python FatCatFish/manage.py migrate Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "temperatures_sourcemap" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "temperatures_sourcemap" W... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "FatCatFish/manage.py", line 21, in <module> main() File "FatCatFish/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 366, in execute self.check() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 64, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/checks/urls.py", line … -
Django query list to template - display items by category
I'm trying to create an array to pass to the template page which should group my items based its categories. I don't know how to do it with a single query in Django so I though to defining a function which should get and array which is similar to the result I would like to print Here it is how I thought he dictionary [{ 'sandwich': { (Menu.objects.get(owner=owner_id), { ('options', MenuOptionItem.objects.get(menu=menu_id) ('extra', MenuExtraItem.objects.get(menu=menu_id) }), (Menu.objects.get(owner=owner_id), { ('options', MenuOptionItem.objects.get(menu=menu_id) ('extra', MenuExtraItem.objects.get(menu=menu_id) }), 'dessert': { (Menu.objects.get(owner=owner_id), { ('options', MenuOptionItem.objects.get(menu=menu_id) ('extra', MenuExtraItem.objects.get(menu=menu_id) }), } }] This is my function but it doesn't work... def get_menu_list(self): menu = [] # defining the categories categories = ( Menu.objects.filter(owner=self.id) .order_by("category") .values("category") .distinct() ) for category in categories: # create main group menu.append(category) # select the items present in the category items = Menu.objects.filter(owner=self.id, category=category) for item in items: # add items and options to the category menu[category] = [ Menu.objects.get(menu_id=item.id), ( ("options", MenuOptionItem.objects.get(menu=item.id)), ("extra", MenuExtraItem.Objects.get(menu=item.id)), ), ] return menu I'm also adding the model class, this may help further Model.py class Menu(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) menu_title = models.CharField(max_length=500, blank=False) short_description = models.CharField(max_length=500, blank=False) image = models.ImageField(upload_to="menu_images/", blank=False) price = models.DecimalField(max_digits=14, decimal_places=2, default=0) category = models.CharField(max_length=500, … -
DRF- Creating new objects from nested representation raises TypeError
I have the following two models: class User(models.Model): user_id = models.CharField( max_length=129, unique=True, ) user_article = models.ManyToManyField( Article, through="UserArticle", ) occupation = models.CharField(max_length=100, default='null') def __str__(self): return self.user_id and class Article(models.Model): uuid = models.UUIDField(editable=False, unique=True) company = models.ForeignKey( Company, on_delete=models.PROTECT, related_name='article_company_id', ) articleType = models.ForeignKey( ArticleType, on_delete=models.PROTECT, related_name='type', ) date_inserted = models.DateField() def __str__(self): return self.uuid which are modeled with a many-to-many relationship, using this through model: class UserArticle(models.Model): user = models.ForeignKey(User, to_field='user_id', on_delete=models.PROTECT,) article = models.ForeignKey(Article, to_field='uuid', on_delete=models.PROTECT,) posted_as = ArrayField( models.CharField(max_length=100, blank=True),) post_date = models.DateField() class Meta: db_table = "core_user_articles" Here's my view: class BatchUserArticleList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): queryset = UserArticle.objects.all() serializer_class = BatchUserArticleSerializer def create(self, request, *args, **kwargs): serializer = BatchUserArticleSerializer(data=request.data) if not serializer.is_valid(): return response.Response({'Message': 'POST failed', 'Errors': serializer.errors}, status.HTTP_400_BAD_REQUEST) self.perform_create(serializer) # equal to serializer.save() return response.Response(serializer.data, status.HTTP_201_CREATED) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) The problem I'm facing is when I want to POST data, of the following format, in the M2M table: { "posted_as": ["news"], "post_date": "2020-05-26", "user": "jhtpo9jkj4WVQc0000GXk0zkkhv7u", "article": [ "11111111", "22222222" ] } As I'm not passing an exact mapping of a user or article entity (I'm only passing the uids and not the rest of the model fields), my serializer … -
Django admin TabularInline "502 Bad Gateway” nginx prematurely closed connection
I have seen lot of discussion on this but nothing has helped. Below is the error I am getting *9 upstream prematurely closed connection while reading response header from upstream It is happening with my Django TabularInline admin view. Everything else working absolutely fine. I have this setup on google cloud. Please advise what I am doing wrong. admin.py class TargetTabularInline(admin.TabularInline): model = Target class VideoAdmin(admin.ModelAdmin): inlines = [TargetTabularInline] list_display = ['title', 'source', 'reviewed', 'category', 'sfw'] search_fields = ('title', 'category', 'source__name', 'reviewed', ) class Meta: model = Video admin.site.register(Video, VideoAdmin) models.py class Video(DFModel): source = models.ForeignKey(Source, models.DO_NOTHING) creator = models.ForeignKey( Creator, models.DO_NOTHING, blank=True, null=True) title = models.CharField(max_length=500) views = models.IntegerField(blank=True, null=True) likes = models.IntegerField(blank=True, null=True) dislikes = models.IntegerField(blank=True, null=True) tags = models.TextField(blank=True, null=True) upload_date = models.DateTimeField(blank=True, null=True) page_url = models.TextField(blank=True, null=True) video_url = models.TextField(blank=True, null=True) thumb_url = models.TextField(blank=True, null=True) sfw = models.BooleanField(blank=True, null=True) category = models.CharField(max_length=20, blank=True, null=True) reviewed = models.TextField(blank=True, null=True) severity = models.CharField(max_length=10, blank=True, null=True) origin = models.CharField(max_length=20, blank=True, null=True) organization_id = models.IntegerField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) class Target(DFModel): person = models.ForeignKey( Person, models.DO_NOTHING, blank=True, null=True) video = models.ForeignKey( 'Video', models.DO_NOTHING, blank=True, null=True) reviewed = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) class Meta: db_table = … -
Pictures Showing on Heroku site but not Local Host
The users profile pictures are loading fine on https://rossdjangoawesomeapp2.herokuapp.com/ but when I use http://localhost:8000/ none of them are loading. The problem only occurred when I uploaded my site to Heroku / AWS. I tried un doing some of the changes to the code. I tried getting it back to a state where localhost was working fine. But then I ended up coming into more error messages. And my difficulty now is I don't really know where to begin looking for advice on how to fix the issue. Settings.py """ Django settings for django_project3 project. Generated by 'django-admin startproject' using Django 2.2.6. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') #SECRET_KEY = 'SECRET_KEY' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True #DEBUG = (os.environ.get('DEBUG_VALUE')=='True') ALLOWED_HOSTS = ['rossdjangoawesomeapp.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', … -
Looking to create a video streaming app in django
Iam looking to create a video streaming app in django. The app doesnt involve user uploads, only streaming. I upload the video, and the user views it, more like netflix, but for 5 to 10 secs videos. Please help me with the basics and the requirements. I know how django works but iam totally new with the videos part. Please help me. -
How to provide image path in "main.css" in Django?
I am trying to build an app in Django, I have created a home page, the statics paths I have set for the project working fine. I am able to render HTML(index.html) associated CSS (main.css) and images perfectly except an image "banner.jpg". For other images, I have set path as we usually do in Django, <img src="{% static 'images/image1.jpg' %}" alt="" /> For the banner of the home page, I tried to set a path in CSS something like given below. main.css #banner { background-color: #e5474b; color: #f2a3a5; padding: 13em 0 11em 0; background-color: #0c0c0c; background-image: url("../images/banner.jpg"); background-size: cover; background-repeat: no-repeat; background-position: 15% left; text-align: left; position: relative; z-index: 9999; } or #banner { background-color: #e5474b; color: #f2a3a5; padding: 13em 0 11em 0; background-color: #0c0c0c; background-image: url("{% static 'images/banner.jpg' %}"); background-size: cover; background-repeat: no-repeat; background-position: 15% left; text-align: left; position: relative; z-index: 9999; } but both the methods never work, however when I set path "url("../images/banner.jpg")" without Django it works perfectly and renders the image in the background. Where should I make the changes to correct this problem? Thank you. -
Django oscar api overwrite child serializer
How can i overwrite oscar api ChildProductserializer. I followed oscar api guide how to overwrite serializers but i cant overwrite this one serializer Oscar api Child Serializer class ChildProductserializer(PublicProductSerializer): "Serializer for child products" parent = serializers.HyperlinkedRelatedField( view_name="product-detail", queryset=Product.objects.filter(structure=Product.PARENT), ) # the below fields can be filled from the parent product if enabled. images = ProductImageSerializer(many=True, required=False, source="parent.images") description = serializers.CharField(source="parent.description") class Meta(PublicProductSerializer.Meta): fields = overridable( "OSCARAPI_CHILDPRODUCTDETAIL_FIELDS", default=( "url", "upc", "id", "title", "structure", # 'parent', 'description', 'images', are not included by default, but # easily enabled by overriding OSCARAPI_CHILDPRODUCTDETAIL_FIELDS # in your settings file "date_created", "date_updated", "recommended_products", "attributes", "categories", "product_class", "price", "availability", "options", ), ) My overwrite child Serializer class ChildProductSerializer(product.ChildProductserializer): price = serializers.SerializerMethodField() availability = serializers.SerializerMethodField() class Meta(product.ChildProductserializer.Meta): fields=('url','parent','price','availability') # 'price','availability','parent') def get_price(self, instance): request = self.context.get("request") strategy = Selector().strategy(request=request, user=request.user) ser = checkout.PriceSerializer( strategy.fetch_for_product(instance).price, context={'request': request}) return ser.data def get_availability(self,instance): request = self.context.get("request") strategy = Selector().strategy(request=request, user=request.user) ser = product.AvailabilitySerializer( strategy.fetch_for_product(instance).availability, context={'request': request} ) return ser.data class ProductLinkSerializer(product.ProductLinkSerializer): price = serializers.SerializerMethodField() availability = serializers.SerializerMethodField() class Meta(product.ProductLinkSerializer.Meta): fields = ('url','children') # ,'id','children','price','title','images','description','children','structure','availability') def get_price(self, instance): request = self.context.get("request") strategy = Selector().strategy(request=request, user=request.user) ser = checkout.PriceSerializer( strategy.fetch_for_product(instance).price, context={'request': request}) return ser.data def get_availability(self,instance): request = self.context.get("request") strategy = Selector().strategy(request=request, user=request.user) ser …