Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does this docker compose file build the same image four times?
When I run docker-compose build on the following docker-compose file, which is for a django server with celery, it builds an identical image four times (for the web service, celeryworker, celerybeat and flower). The entire process is repeated four times I thought the point of inheriting from other service descriptions in docker-compose was so that you could reuse the same image for different services? How can I reuse the web image in the other services, to reduce my build time by 75%? version: '3' services: web: &django image: myorganisation/myapp container_name: myapp_web build: context: . dockerfile: ./compose/local/django/Dockerfile # This is a multistage build installing private dependencies, hence this arg is needed args: PERSONAL_ACCESS_TOKEN_GITHUB: ${PERSONAL_ACCESS_TOKEN_GITHUB} command: /start volumes: - .:/app ports: - 8000:8000 depends_on: - db - redis environment: - DJANGO_SETTINGS_MODULE=backend.settings.local - DATABASE_URL=postgres://postgres_user:postgres_password@db/postgres_db - REDIS_URL=redis://:redis_password@redis:6379 - CELERY_FLOWER_USER=flower_user - CELERY_FLOWER_PASSWORD=flower_password env_file: - ./.env celeryworker: <<: *django container_name: myapp_celeryworker depends_on: - redis - db ports: [] command: /start-celeryworker celerybeat: <<: *django container_name: myapp_celerybeat depends_on: - redis - db ports: [] command: /start-celerybeat flower: <<: *django container_name: myapp_flower ports: - 5555:5555 command: /start-flower volumes: postgres_data: driver: local pgadmin_data: driver: local -
Django/Python : Many to Many Nesting Serializer with Unique Validation Not Working
I'm having an issue posting/serializing m2m data. I've tried the below code out but I'm getting a grant type already exists issue. I understand this is because I set the type field to unique. When I try to override the create method I get the same issue. I tried to delete the grant_type and post the call again but I get the following error: \django\db\models\fields\related_descriptors.py", line 545, in set raise TypeError( TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use region.set() instead. ->My goal is to create with the grant type object, and also retrieve grants with the grant type object Request Body I was using { "name": "GrantName 1", "amount": "5000", "grant_type": [ {"type": "Hiring"} ], "deadlines": "Open Until Filled", "region": ["2"] } Models class Grant(models.Model): name = models.CharField(max_length=250, unique=True) amount = models.IntegerField() grant_type = models.ManyToManyField(GrantType) deadlines = models.CharField(max_length=250) region = models.ManyToManyField(Region) class Meta: db_table = "grants" def __str__(self): return self.name class GrantType(models.Model): type = models.CharField(max_length=250, choices=GRANT_TYPE_CHOICES, unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.type class Meta: db_table = "granttypes" class Region(models.Model): abbreviation = models.CharField(max_length=150, choices=REGION_CHOICES, unique=True) name = models.CharField(max_length=250, unique=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.abbreviation … -
How to build a multi object ORM model
I'm trying to build models for a Django app. But I'm not sure what is the correct way to build a multi object link, I'll explain what I mean by that. So let's say I have a 'main' model, for example a post on a news website, and I want the post to be either a text, a video or an image. My question is what is the best way to implement that, is it to have an abstract model and have every types of articles inherit it, or to have a One To One relation with a 'post item' for example. Here a quick code in Python used for the Django ORM to demonstrate what I mean: The 'inheritance' way of doing things: class Category(models.Model): title = models.CharField(max_length=100) class PostAbstract(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="%(class)s_posts") title = models.CharField(max_length=100) [...] class Meta: abstract = True class Video(PostAbstract): duration = models.DurationField() [...] class Article(PostAbstract): text = models.TextField() [...] Or the 'One To One' relation to a 'base' model: class Category(models.Model): title = models.CharField(max_length=100) class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="posts") title = models.CharField(max_length=100) [...] class Video(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) duration = models.DurationField() [...] class Article(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) text … -
how to force column dtype prior to loading data with django ORM
We are using pandas (v0.25.3) to run analysis and data manipulation from large data sets from our postgres database accessed via the Django ORM (django v2.2.6). The situation we have is that the table we are importing to a DataFrame includes a foreign key ID column which is stored as a models.BigIntegerField. This foreign key field is typically a large number but can also be null in those rows where the foreign key is not set. When we import the list of records from the Django query set into a new pandas DataFrame, pandas sets the dtype of the ID column to np.float64 since the data includes some null values. But, for those rows where the ID is not null, the conversion from BigInteger to np.float64 causes the least significant digits to change such that if we subsequently try to re-cast the column dtype to np.int64 (using DataFrame.astype()), we end up with a different value. The following a simplified example of the problem we are seeing: import numpy as np import pandas as pd data = [{'id': 144123525091332019}, {'id': None}] df = pd.DataFrame(data) df Out[6]: id 0 1.441235e+17 1 NaN df.fillna(0, inplace=True) df.astype({'id': np.int64}) Out[8]: id 0 144123525091332032 1 0 … -
Implementing select2 in form to query existing users, ModelMultipleChoiceField is always invalid on form
I inherited a project where we wanted to use django's native User model but also give users some additional fields. So I made a model called UserProfiles, which has a foreignkey to each User instance. I made a template to update these UserProfiles called settings-userprofile.html. Previously, we only had the field api_key for people to modify, so things were basic. We want every User to have their own list of "assistant" Users, a label relevant for an API we'll be implementing. So I added the field assistants and updated settings-userprofile.html to include a <select multiple> element that lists out all the existing users on our site. We're using a theme/template that is able to implement the select2 pillbox/tokenization element (like the rightmost screencap in this picture) user_profile/models.py class UserProfile(models.Model): phone_number = models.CharField(max_length=15, verbose_name='Phone Number') user = models.OneToOneField(User, on_delete = models.CASCADE) api_key = models.CharField(max_length=200, default='12345678',) assistants = models.ManyToManyField(User, related_name="assistants") settings-userprofile.html <form class='form-horizontal' method="post" action="{% url 'profileUpdate' %}"> {% csrf_token %} <div class="form-group row mb-4"> <label for="api_key" class="col-sm-3 col-form-label"><b>Profile Api Key:</b></label> <div class="col-sm-9"> <input type="text" name="api_key" class="form-control" id="horizontal-apikey-input" value="{{ request.user.userprofile.api_key }}"> </div> </div> <div class="form-group"> <label class="control-label">User list</label> <select name="assistants" class="select2 form-control select2-multiple" multiple="multiple" data-placeholder="Choose ..."> <optgroup label="Existing users"> {% for u … -
Django: Annotating Sum() of two columns in different tables
assuming I have the following models - How can I annotate the total posting and total story reach of each influencer in my queryset? class Influencer(models.Model): name = models.CharField(max_length=100) class Posting(models.Model): influencer = models.ForeignKey(Influencer, on_delete=models.CASCADE) reach = models.IntegerField() class Story(models.Model): influencer = models.ForeignKey(Influencer, on_delete=models.CASCADE) reach = models.IntegerField() I have tried this: queryset = Influencer.objects.all() queryset = queryset.annotate(posting_reach=Sum("posting__reach")) queryset = queryset.annotate(story_reach=Sum("story__reach")) However, the values are not calculated correctly using this approach (I assume because of the LEFT OUTER JOIN which is made by Sum()). How would I do this in Django? -
How to update a django moodel value from a button click in a class based view
i currently have a model that looks like: class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) is_best_answer = models.BooleanField(default=False) def set_best_answer(self): self.is_best_answer = True self.save() def get_absolute_url(self): return reverse('question-detail', kwargs={'pk': self.question.pk}) def __str__(self): return f"Answer by {self.author} with text: {self.content}" I have a Class based Listview which lists all of the answers above. I want to add a button in the template that would update the value in the model of is_best_answer to True e.g. <a class="btn btn-outline-dark " href="{% url '' answer.id %}">Set Best Answer</a> Is there a clean way to do this within the class based view? Dango version 3.1 -
How can i access choices of the model in the serializers and obtain a json view
models.py MSI_OPTIONS = ( (ANC1, 'AN1'), (ANC2, 'AN2'), (ANC3, 'AN3'), (ANC4, 'AN4'), (DELIVERY, 'Delivery'), (FAMILY_PLANNING, 'Family Planning'), ) class MSIService(models.Model): girl = models.ForeignKey(Girl, on_delete=models.CASCADE) option = models.CharField(choices=MSI_OPTIONS, default=ANC1, max_length=250) Am trying to obtain a JSON object counting how many time each MSI_OPTIONS is used like { "ANC1": 3, "ANC2": 4, "ANC3": 4, "ANC4": 10 } Note: each girl has one of MSI_OPTIONS. -
how to auto add multiple models in a single model form auto instanced
so i already have a modelform that has 2 models inline inside it, but only the main model instances appear at start, and to start editing the other two models i have to click add like below : so i want it to be displayed automatically at the page without me starting it. here is a snippet of my code: class Transaction(models.Model): income_period_choices = (('Weekly', 'Weekly'), ('Fortnightly', 'Fortnightly')) chp_reference = models.CharField(max_length=50, unique=True) rent_effective_date = models.DateField(null=True, blank=True) income_period = models.CharField(max_length=11, choices=income_period_choices, null=True, blank=True, default='Weekly') property_market_rent = models.DecimalField(help_text='Weekly', max_digits=7, decimal_places=2, null=True, blank=True) class FamilyGroup(models.Model): name_choices = (('FG_1', 'FG_1'), ('FG_2', 'FG_2'), ('FG_3', 'FG_3'), ('FG_4', 'FG_4'), ('FG_5', 'FG_5')) name = models.CharField(max_length=10, choices=name_choices) transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) family_type = models.ForeignKey(FamilySituation, on_delete=models.PROTECT, null=True, blank=True) class FamilyMember(models.Model): transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) family_group = models.ForeignKey(FamilyGroup, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100, null=True, blank=True) date_of_birth = models.DateField(null=True, blank=True) relationship = models.ForeignKey(Relationship, on_delete=m odels.PROTECT) admin.py @admin.register(Transaction) class TransactionAdmin(admin.ModelAdmin): search_fields = ['chp_reference', 'familymember__name'] inlines = [FamilyGroupInline, FamilyMemberInline] -
AH00035: access to / denied 403 Forbidden Django mod-wsgi
I am trying to configure apache with Django using mod-wsgi. But I am getting the following error AH00035: access to / denied (filesystem path '/home/ec2-user/ezvoice') because search permissions are missing on a component of the path URL is showing 403 forbidden Here is the conf file LoadModule wsgi_module "/home/ec2-user/venv/lib/python3.7/site-packages/mod_wsgi/server/mod_wsgi-py37.cpython-37m-x86_64-linux-gnu.so" <VirtualHost *:80> DocumentRoot /home/ec2-user/ Alias /static /home/ec2-user/ezvoice/sub_app/static <Directory /home/ec2-user/ezvoice/sub_app/static> Options FollowSymLinks Order allow,deny Require all granted </Directory> WSGIDaemonProcess ezvoice python-path=/home/ec2-user/ezvoice:/home/ec2-user/venv/lib/python3.7/site-packages WSGIProcessGroup ezvoice WSGIScriptAlias / /home/ec2-user/ezvoice/main_app/wsgi.py ErrorLog /home/ec2-user/ezvoice/log-error.log CustomLog /home/ec2-user/ezvoice/custom-error.log combined <Directory /home/ec2-user/ezvoice/main_app> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> The directory structure is as follow home -ec2-user --ezvoice ---main_app ----asgi.py ----settings.py ---sub_app ----views.py --venv ---bin ---include ---lib -
Trouble loading static files from Digital Ocean Spaces in my Django project
During the development of my project I could display video files through my templates like this: <video width="200" controls> <source src='{{ MEDIA_URL }}{{ post.video }}' type='video/mp4'> Your browser does not support the video tag. </video> MEDIA_URL was directed to a media folder in settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Now I am in production and using Digital Ocean Spaces, my static and media files are both served by STATIC_URL. When a user creates a post that contains a video file I can see it uploaded in Spaces, I can also view it through the Django admin. But I cannot find the code I need to make it playable on the site anymore. I just see a grey box telling me the file is not supported. I have tried changing {{ MEDIA_URL}} to {{ STATIC_URL }}, I have also tried <source src='{% static "post.video" %}' type='video/mp4' but neither of these have worked. I cannot find the answer to this anywhere online. Hope somebody can help. -
Multi Column Table in Django Template from List
I have a list following list = {a,1,b,2,c,3,d,4,.....} I want to show it in Django template with 4 column like below <table> <tr> <td>a</td> <td>1</td> <td>b</td> <td>2</td> </tr> <tr> <td>c</td> <td>3</td> <td>d</td> <td>4</td> </tr> </table> How can I do that in Django Template -
How to translate this query into django orm
select user_id, count(*) from e_order group by 1 having count(*) > 1 How I can translate this query in Django ORM? -
Easy way to develop private messaging on django?
What are the possible ways to introduce messaging functionality between two users on a django website? Does anyone have any good resources or advice on learning how to do this -
How to serialize nested objects with related models?
i am really new to DRM and i have to following problem I have three related models. Now i want to for each sensor values to the related patient. My models look like: class Sensor(models.Model): sensor_name = models.CharField(max_length=200, primary_key=True) sensor_refreshRate = models.FloatField() sensor_prio = models.IntegerField(choices=[ (1, 1), (2, 2), (3, 3), (4, 4), ], default='1') sensor_typ = models.CharField(max_length=200, choices=[ ('bar', 'bar'), ('pie', 'pie'), ('line', 'line'), ('text', 'text'), ], default='bar') class Patient(models.Model): firstName = models.CharField(max_length=200) lastName = models.CharField(max_length=200) age = models.IntegerField() doctor = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) sensor = models.ManyToManyField(Sensor) class Value(models.Model): value_date = models.DateTimeField(auto_now_add=True) value = models.FloatField() sensor = models.ForeignKey(Sensor, on_delete=models.CASCADE) Now i would like to send a JSON file which looks like: [ { "value": 445.0, "sensor": "Pressure", "patient": 3 }, { "value": 478.0, "sensor": "Temperature", "patient": 3 } ] Now i am not sure how to serialize my JSON. Thanks in advance -
Multi user-type Django DRF authentication
I'm using Django DRF for a personal project. I'm trying to customize authentication with 2 types of users, and also use email for validation (not username). My approach was to have an "Account" model (with account_type on it), and then "Bar" and "RegularUser" on 2 separeted models, inheriting from "Account". I don't want to use is_admin and is_superuser flags. I don't understand if I need to add "BaseUserManager" classes to every model or only on "RegularUser" and "Bar". Also I don't know if I need a serializer for Account model or don't. Here is my account model: class AccountManager(BaseUserManager): def create_user(self, account_type, email, password): account = self.model( account_type=account_type, email=self.normalize_email(email), ) account.set_password(password) account.save(using=self._db) return account class Account(AbstractBaseUser): email = models.EmailField(max_length=60, unique=True) account_type = models.SmallIntegerField() objects = AccountManager() USERNAME_FIELD = 'email' And here is my Bar model: class BarManager(BaseUserManager): def create_user(self, email, name, password, city, **extra_fields): if not email: raise ValueError("Missing Email") if not name: raise ValueError("Missing Name") bar = self.model( account_type=1, city=city, email=self.normalize_email(email), name=name, **extra_fields, ) bar.set_password(password) bar.save(using=self._db) return bar def create_superuser(self, email, password, name, city, **extra_fields): bar = self.create_user( city=city, email=self.normalize_email(email), name=name, password=password, **extra_fields, ) bar.is_admin = False bar.is_staff = True bar.is_superuser = False bar.save(using=self._db) return bar class Bar(Account, AbstractBaseUser): … -
Django REST Framework. How do I create two identical tags with different values?
Another Django REST Framework problem that I don't understand how to solve? There are two objects image_1 and image_2. In serializers.py: class someClass(serializers.ModelSerializer): image_1 = serializers.ImageField(source='image_1') image_2 = serializers.ImageField(source='image_2') class Meta: model = onlyimage fields = ['image_1', 'image_2'] In the output, I get: <image_1>https://domain-name.com/media/image_1</image_1> <image_2>https://domain-name.com/media/image_2</image_2> I want the tag not to be numbered like in the example below: <image>https://domain-name.com/media/image_1</image> <image>https://domain-name.com/media/image_2</image> But if you change in serializers.py, of course, an error occurs: class someClass(serializers.ModelSerializer): image = serializers.ImageField(source='image_1') image = serializers.ImageField(source='image_2') class Meta: model = onlyimage fields = ['image', 'image'] -
Database Error at BackEnd no Exception message supplied
I am creating a website using Django as BackEnd and MongoDB as my DataBase but I am experiencing an error while trying to add data into my Patient model using the admin dashboard, 1st entry doesn't trigger any exception however when I try to add 2nd patient my app crashes, and here are the screenshots of my model and my traceback My Patient Model This model is inherited from the base model and also holds a self reference. The TraceBack can be found here: https://dpaste.com/GB2REDLGA However I tried to change my database and upon shifting to SQLite the error was gone. I don't know what is causing this error. Little help would be awesome. -
Django - CSS file not working. Getting error 404 . "Failed to load resource: the server responded with a status of 404 (Not Found)"
I know this question has been asked many times and I have seen all the answers given, but none of them worked for me. I am a newbie and trying to get access to CSS files in my Django template but it is not working, I have tried many options but none of them worked for me. Here I am using Django 2.2 in my project. Can you please help me to find out the mistake? settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/images/' STAICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns = [] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns = [ path('admin/', admin.site.urls), path('', include('GalaxyOffset.urls')), ] basic.css body{ background: url('{% static "../images/photo1.jpg" %}') no-repeat center center fixed; -webkit-background-size: cover; -moj-background-size: cover; -o-background-size: cover; background-size: cover; background-color: #f5fbff; } basic.html <!doctype html> <html lang="en"> <head> {% load static %} <link rel="stylesheet" type="text/css" href="{% static '/css/basic.css' %}"> <title>{% block title%} {% endblock %} | Galaxy Offset</title> </head> <body> <div class="container"> <h1>Welcome to the first page </h1> {% block body %} … -
django - how do i use an input from a select form to compare data in my database and output it on another page?
<form method = "POST"> {% csrf_token %} <div class = "lookback" <label for = "time"></label> <select name = "time" id = "time"> <option value = "today">Today</option> <option value = "yesterday">Yesterday</option> <option value = "lastweek">Last Week</option> <option value = "lastmonth">Last Month</option> <option value = "lastyear">Last Year</option> <option value = "forever">Forever</option> </select> <button><a type= "button" class = "Look" id = "look" href = "">Look Back?!</a></button> </form> ** Above is the portion of HTML page i am using to get the select value so that I can use it in my views.py to filter out the data and output it on another page. ** def retro(request): if request.method == "POST": time = ThoughtForm(request.POST) today = timezone.now().date() if time == "Yesterday": yesterday = timezone.now().date() - timedelta(days=1) data = Thought.objects.filter(date__gte=yesterday, date__lt=today) elif time == "Last Week": week = timezone.now().date() - timedelta(days=7) data = Thought.objects.filter(date__gte=week, date__lt=today) elif time == "Last Month": month = timezone.now().date() - timedelta(days=30) data = Thought.objects.filter(date__gte=month, date__lt=today) elif time == "Last Year": year = timezone.now().date() - timedelta(days=365) data = Thought.objects.filter(date__gte=year, date__lt=today) elif time == "Forever": data = Thought.objects.all else: data = Thought.objects.filter(date__gte=today, date__lt=today) return render(request,'look.html', {'data' : data}) else: return render(request, 'retro.html') When I use the submit button of the retro.html (the one … -
Auto Delete a Django object from the database based on DateTimeField
Let's imagine a simple Food model with a name and an expiration date, my goal is to auto delete the object after the expiration date is reached. I want to delete objects from the database (postgresql in my case) just after exp_date is reached, not filter by exp_date__gt=datetime.datetime.now() in my code then cron/celery once a while a script that filter by exp_date__lt=datetime.datetime.now() and then delete Food(models.Model): name = models.CharField(max_length=200) exp_date = models.DateTimeField() *I could do it with a vanilla view when the object is accessed via an endpoint or even with the DRF like so : class GetFood(APIView): def check_date(self, food): """ checking expiration date """ if food.exp_date <= datetime.datetime.now(): food.delete() return False def get(self, request, *args, **kwargs): id = self.kwargs["id"] if Food.objects.filter(pk=id).exists(): food = Food.objects.get(pk=id) if self.check_date(food) == False: return Response({"error": "not found"}, status.HTTP_404_NOT_FOUND) else: name = food.name return Response({"food":name}, status.HTTP_200_OK) else: return Response({"error":"not found"},status.HTTP_404_NOT_FOUND) but it would not delete the object if no one try to access it via an endpoint. *I could also set cronjob with a script that query the database for every Food object which has an expiration date smaller than today and then delete themor even setup Celery. It would indeed just need to … -
Django app on heroku, ModuleNotFoundError: No module named 'spread'
I am strugling with running my app on heroku. Everything works fine on a local machine. Ive deployed a django app to heroku with no issues (git push heroku master is working properly) however whenever I am trying to heroku open heroku logs are pointing out an error ModuleNotFoundError: No module named 'spread' I've researched most of the stackoverflow related questions and google articules and tutorials but with no sucess. I hope this is just some simple issue that I cant figure out. Any help will be much appriciated. Thanks heroku logs --tail error presented at the bottom 2020-12-18T12:55:21.766372+00:00 heroku[web.1]: State changed from crashed to starting 2020-12-18T12:55:29.108110+00:00 heroku[web.1]: Starting process with command `gunicorn spread.wsgi` 2020-12-18T12:55:32.531785+00:00 app[web.1]: [2020-12-18 12:55:32 +0000] [4] [INFO] Starting gunicorn 20.0.4 2020-12-18T12:55:32.532683+00:00 app[web.1]: [2020-12-18 12:55:32 +0000] [4] [INFO] Listening at: http://0.0.0.0:48488 (4) 2020-12-18T12:55:32.532859+00:00 app[web.1]: [2020-12-18 12:55:32 +0000] [4] [INFO] Using worker: sync 2020-12-18T12:55:32.542317+00:00 app[web.1]: [2020-12-18 12:55:32 +0000] [10] [INFO] Booting worker with pid: 10 2020-12-18T12:55:32.562471+00:00 app[web.1]: [2020-12-18 12:55:32 +0000] [10] [ERROR] Exception in worker process 2020-12-18T12:55:32.562473+00:00 app[web.1]: Traceback (most recent call last): 2020-12-18T12:55:32.562473+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2020-12-18T12:55:32.562474+00:00 app[web.1]: worker.init_process() 2020-12-18T12:55:32.562475+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/base.py", line 119, in init_process 2020-12-18T12:55:32.562475+00:00 app[web.1]: self.load_wsgi() 2020-12-18T12:55:32.562475+00:00 app[web.1]: File … -
Django Instagram no longer shows feed (429 Client error)
I use Django_instagram app to put the media feed onto a website, I use local memory cache to save the media and so a request is made once every 288880 seconds. This was working fine for ages, but a week ago it stopped working on both Production and Development servers. ERROR:root:user profile "###########" not found Traceback (most recent call last): File "C:\Program Files\Python38\lib\site-packages\django_instagram\scraper.py", line 28, in instagram_scrap_profile page.raise_for_status() File "C:\Program Files\Python38\lib\site-packages\requests\models.py", line 941, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 429 Client Error: - for url: https://www.instagram.com/accounts/login/ ERROR:root:scripts not found Traceback (most recent call last): File "C:\Program Files\Python38\lib\site-packages\django_instagram\scraper.py", line 44, in instagram_profile_js return tree.xpath('//script') AttributeError: 'NoneType' object has no attribute 'xpath' please note that the username of the profile is definitely correct, I've changed it too ######## just for security and privacy concern. also something worth noting is that there is an open issue since April for a similar issue: https://github.com/marcopompili/django-instagram/issues/26 But it has been working fine for me. I've tried clearing browser and server caches and cookies. I've tried to check all code again for any errors. Any help or clarification would be appreciated. Is there any good alternatives perhaps? thank you! -
How to do counts into get_queryset() functions, using Django Rest Framework and viewsets?
I want to do a query inside the get_queryset() function and retorn some totals. But this function just return an QS object. I have the following code into my views.py. serializer_class = omrActionQueueItemSerializer def get_queryset(self): omr_action_queue = self.request.query_params.get('omr_action_queue', None) status = self.request.query_params.get('status', None) queryset = OmrActionQueueItem.objects.all() queryset = queryset.filter(omr_action_queue=omr_action_queue) queryset = queryset.filter(status=status) return queryset This works for filtering, but if I count I get an error message saying that my answer is a value, not a QS. This is my serializer.py: class omrActionQueueItemSerializer(serializers.ModelSerializer): class Meta: model = OmrActionQueueItem fields = "__all__" My final goal is to summarize my table in something like this: { 'total_pending': 19 'total_complete': 5 'total_processing': 2 } And this is my models.py: class OmrActionQueueItem(models.Model): # id created by default omr_action_queue = models.ForeignKey(OmrActionQueue, on_delete=models.DO_NOTHING) params_content = models.TextField() process_content = models.TextField(default=None) created_at = models.DateTimeField(default=datetime.now()) updated_at = models.DateTimeField(null=True) status = models.CharField(max_length=50, default="pending") enabled = models.BooleanField(default=1) deleted = models.BooleanField(default=1) -
Adding a UniqueConstraint to a ManyToMany field
I want to add a constraint to my database so that an application can only ever be associated with one vacancy. I don't want to be able to go in from the shell or django admin page, go into a vacancy and select an application that is already associated with a vacancy. I would like some kind of validation error to be raised. But I am a little unsure how I should go about this? models.py class Vacancy(models.Model): CATEGORY_CHOICES = [ ('ADMINISTRATION', 'Administration'), ('CONSULTING', 'Consulting'), ('ENGINEERING', 'Engineering'), ('FINANCE', 'Finance'), ('RETAIL', 'Retail'), ('SALES', 'Sales'), ] employer = models.ForeignKey('Employer', on_delete=models.CASCADE) job_title = models.CharField(max_length=35, default=None) main_duties = models.TextField(default=None, validators=[ MinLengthValidator(650), MaxLengthValidator(2000) ]) person_spec = models.TextField(default=None, validators=[ MinLengthValidator(650), MaxLengthValidator(2000) ]) salary = models.PositiveIntegerField(default=None, validators=[ MinValueValidator(20000), MaxValueValidator(99000) ]) city = models.CharField(choices=CITY_CHOICES, max_length=11, default=None) category = models.CharField(choices=CATEGORY_CHOICES, max_length=15, default=None) max_applications = models.PositiveSmallIntegerField(blank=True, null=True) deadline = models.DateField(default=None) applications = models.ManyToManyField('Application', blank=True, related_name='submissions') class Meta: verbose_name_plural = 'vacancies' constraints = [ models.UniqueConstraint(fields=['id', 'applications'], name="unique_application") ] class Application(models.Model): STAGES = [ ('pre-selection', 'PRE-SELECTION'), ('shortlisted', 'SHORTLISTED'), ('rejected pre-interview', 'REJECTED PRE-INTERVIEW'), ('rejected post-interview', 'REJECTED POST-INTERVIEW'), ('successful', 'SUCCESSFUL') ] candidate = models.ForeignKey('Candidate', on_delete=models.CASCADE) job = models.ForeignKey('Vacancy', on_delete=models.CASCADE) cv = models.CharField(max_length=60, default=None) cover_letter = models.TextField(default=None, validators=[ MinLengthValidator(0), MaxLengthValidator(2000) ]) submitted = models.DateTimeField(auto_now_add=True) stage …