Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery executes the task but not reflects them in the celery logs. Why?
For eg it runs perfect the first time but if we try to run the same thing again so if it ran 3 tasks at first it will show only 1 of them (first or last of the three). But will execute all of them. The command use to run celery here is celery -A project worker -B -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler The logs in the celery looks like for the first time task received 1 task received 2 task received 3 For the second time it may be task received 3 or task recevied 1 #either of these 2 But will still execute all three of them. So what may be the thing preventing them -
Why this signal is not working as expected?
I would appreciate some help. Does anyone know why this signal is only being triggered only when the "xp value" is different from the one that already exist ? so eg. if a UserLeaderboardTracking objects already exist for that user with the value 10 the it won't create it otherwise it will . def create_user_leaderboard_tracking(sender, instance, *args, **kwargs): if instance.xp_collected == 0: pass else: UserLeaderboardTracking.objects.get_or_create(user=instance.user, xp_value=instance.xp_collected) -
Is `python_paths` a correct parameter for pytest.ini
I'm working on an undocumented Django application, as a new team (all previous developper went away , so no help is available) The pytest.ini looks like this : [pytest] python_paths = my_app According to pytest documentation, there is no python_paths option, only pythonpath. The tests are working fine by now, and I don't know what to do : Keep that option, it may somehow be used Rename to pythonpath, like it should always has been Delete, as it is unused anyway (I tested, it works fine without) I know StackOverflow isn't meant for opinions, I'll try to find a lead dev at my company for that. I'm just looking for confirmation that i'm not missing an usage -
I am having problem with installing SSL Certificate on my ubuntu server running on apache2
I have SSL Certificate, namecheap enabled it, and now I am trying to install it on my ubuntu server running on Apache2. I have my django project setup, and logs are showing that is django/Python side problem. logs. When I am running apache2 on port 80 it works completely fine. sites-available SSL config: ssl-config sites-available http config: http-config -
Django: how to override textarea globally with custom class?
I'm trying to override widgets (like textarea) globally in Django. For this, I defined my own django/form/widgets/textarea.html file. First, I wanted to modify the default number of rows. The textarea.html file will looked like this: <textarea rows="3" name="{{ widget.name }}" {% include "django/forms/widgets/attrs.html" %} >{% if widget.value %}{{ widget.value }}{% endif %}</textarea> This example above works perfectly. But what if I want to add a custom class now? <textarea rows="3" class="my-custom-class" name="{{ widget.name }}" {% include "django/forms/widgets/attrs.html" %} >{% if widget.value %}{{ widget.value }}{% endif %}</textarea> This won't work as expected because the attrs.html is supposed to handle extra attributes like class. Hence, defining a class attribute directly in textarea would break this behaviour and would erase existing classes. What is the "clean" way to add extra classes globally? I'd like to do it in HTML, not in Python. For example, I don't want to define a new Widget which would inherit from the base widget when I'm defining my forms, as I think this is pure markup topic, and should not interfere with form definition itself. Thanks. -
Django Meta class abstract changing from True to False
I understand that when a class inherits from an Abstract Django Model, it will not inherit the meta attribute abstract = True, which makes sense. However in the below example nothing has inherited from it, but yet it's Meta.abstract is False even though its defined to be True: from django.db import models from django.db.models.base import ModelBase class MyMeta(ModelBase): def __new__(cls, name, bases, attrs, **kwargs): Class = super().__new__(cls, name, bases, attrs, **kwargs) if not Class.Meta.abstract: print(Class) print('Class.Meta.ordering:', Class.Meta.ordering) # Sanity check print('Class.Meta.abstract:', Class.Meta.abstract) if not hasattr(Class, 'foo'): raise NotImplementedError('Please add a foo attribute') return Class class MyAbstractModel(models.Model, metaclass=MyMeta): name = models.CharField(max_length=250) class Meta: abstract = True Prints: <class 'myapp.models.base.MyAbstractModel'> Class.Meta.ordering: -name Class.Meta.abstract: False -
Django & Authorization Bearer Token
I'm working on Django for an app refrencial on job. I want to get data from an API Pole Emploi. I'm register on the web site, I got a client_id, client_secret etc. I do a get request to get my access_token. def login_explo_metier_pole_emploi(): params = { 'grant_type': 'client_credentials', 'client_id': 'XXX', 'client_secret': 'XXX', 'scope': 'api_explorateurmetiersv1 explojob' } header = { 'Content-Type': 'application/x-www-form-urlencoded' } url_co = 'https://entreprise.pole-emploi.fr/connexion/oauth2/access_token?realm=%2Fpartenaire' req_co = requests.post(url_co, params, header) wb = req_co.json() access_token = wb['access_token'] print('reponse: ', wb) return access_token That's working. After, I want on my view, get datas, but here, it's not working : def get_rome(param): access = login_explo_metier_pole_emploi() print('acces avec: ', access) params = request.META.get('HTTP_AUTHORIZATION', f"Bearer {access}") url = f"https://api.emploi-store.fr/partenaire/explorateurmetiers/v1/explorateurmetiers?libelle={param}&nombre=20&type=metier" req = requests.get(url, params) return req It's returned an 401 error (Unauthorized). Can someone help me please? -
Django how to create a tmp excel file and return it to the browser within the response
I have a process to build a tmp file and then return it to the browser in csv. Now i want to do the same but return a excel file. So what i have for the csv is a view in django that does: def export_wallet_view(request): tmp = tempfile.NamedTemporaryFile(delete=False) with open(tmp.name, 'w', encoding="utf-8-sig") as fi: csv_headers = [ 'Id', 'Name' ] fi.write(';'.join(csv_headers)) fi.write('\n') //here also i save the rows into the file response = FileResponse(open(tmp.name, 'rb')) response['Content-Disposition'] = 'attachment; filename="wallet.csv"' return response So to convert it to excel i try to do something like this using pandas: df = pd.read_csv(tmp.name) df.to_excel('pandas_to_excel.xlsx', sheet_name='new_sheet_name') The problem is that this creates the excel in the server, and i would like to do something like: df = pd.read_csv(tmp.name) df.to_excel('pandas_to_excel.xlsx', sheet_name='new_sheet_name') //this being a tmp file response = FileResponse(open(tmp.name, 'rb')) //this should be the new excel tmp file response['Content-Disposition'] = 'attachment; filename="wallet.csv"' return response Thanks -
Active class on first element of nav-tab with pagination
I have a project where I have a paginated nav-tab with bootstrap. The problem is that, anytime I refresh the page or I change the page with my pagination buttons, the active element is always the element n° 1 of the list. This is probably due to the fact that I need to activate it upon opening the page with an if condition within the forloop. Let me post some code to be more clear template <input type="hidden" id="quizProfileId" value="{{pk}}"> <div class="card"> <div class="card-body"> <h4 class="card-title ms-3">New {{quiz_attempt.question.question_subject}} Quiz</h4> <div class="row"> <div class="col-md-9"> <div class="tab-content text-muted mt-4 mt-md-0" id="v-pills-tabContent"> {% for quiz in quizzes %} <div class="tab-pane {% if forloop.counter == 1 %}active{% endif %} ms-3 questionsObj" id="question{{quiz.question_draft.question.id}}" value="{{quiz.question_draft.question.id}}"> <h5 class="text-dark">{{quiz.question_draft.question.text}}</h5> <div class="list-group mt-3"> {% for image in quiz.question_draft.question.questionimage_set.all %} <a href="{{image.image.url}}" target="_blank"> <img src="{{image.image.url}}" alt="" width="100px" height="100px"> </a> <br> {% endfor %} {% for answer in quiz.question_draft.answerdraft_set.all|shuffle %} <a href="#" data-pk="{{quiz.question_draft.question.id}}" id="answer{{answer.answer.id}}" data-answerId="{{answer.answer.id}}" class=" list-group-item answer question{{quiz.question_draft.question.id}} list-group-item-action {% if quiz.question_draft.is_answered == True and answer.answer.is_correct == True %}bg-success{% endif %} {% if answer.is_answered == True and answer.is_correct == True %}bg-success disabled {% elif answer.is_answered == True and answer.is_correct == False %}bg-danger disabled {% elif quiz.question_draft.is_answered == True %} disabled … -
Is it good database design?
I have this task to create api: City district - name, id Category - name, id Organization Network - name, id Organization Belongs to one of the organization networks id, name, description belongs to several districts, can be represented in several of them at the same time have list of products with prices Product id, name, category can be sold in one or several organizations in network price can be different depending on the organization This is my try to design this database, am I missing something? And also in Django: from django.db import models class District(models.Model): name = models.CharField(max_length=100, unique=True) class Category(models.Model): name = models.CharField(max_length=100, unique=True) class OrganizationNetwork(models.Model): name = models.CharField(max_length=100, unique=True) class Organization(models.Model): name = models.CharField(max_length=100, unique=True) description = models.TextField() organization_network = models.ForeignKey( OrganizationNetwork, on_delete=models.CASCADE, related_name="organizations", ) district = models.ManyToManyField( "District", through="DistrictOrganization", through_fields=("organization", "district"), related_name="organizations", ) products = models.ManyToManyField( "Product", through="OrganizationProduct", through_fields=("organization", "product"), related_name="organizations", ) class Product(models.Model): name = models.CharField(max_length=100, unique=True) category = models.ForeignKey( Category, on_delete=models.CASCADE, related_name="products" ) class DistrictOrganization(models.Model): district = models.ForeignKey(District, on_delete=models.CASCADE) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) class OrganizationProduct(models.Model): price = models.DecimalField(max_digits=10, decimal_places=2) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) -
Accessing sqlite database running on server
I am new to Django and I have a problem, I developed an application using SQLite database in my project with django and I published this project on a server using docker and this project is now used by people and data is saved by entering it. I am doing an update now and when I want to publish this update, the data entered by the users is not in the SQLite file, but when I log in to the application, I see that this data exists. I don't know how I can do this update before this data is lost or how can I get this data and return my database to PostgreSQL, can you help with this? -
Django `TimeField` and timezone
Django documents says "Timezone withoud date no make sence" but I think it does. For example: DB store time of day start. User from Chicago saved start time as 05:00 am. System need to generate report for every day and use this start time with date (datetime field). So for summer days it will 10:00 by UTC, but for winter it will 11:00 by UTC. The question is: how to generate datetime from frimefield and current date? Store timezone in special separate field? https://docs.djangoproject.com/en/3.2/topics/i18n/timezones/#concepts -
queryset get data of the foreign key
I have 2 models ( Users and Posts ) class Users(models.Model): email = models.CharField(max_length=225) class Posts(models.Model): user = models.ForeignKey(Users, on_delete=models.CASCADE, default=1) type = models.TextField() I want to include the user email when getting all posts. I have done the following but am only getting the user id. class PostsViewSet(viewsets.ModelViewSet): serializer_class = PostsSerializer def get_queryset(self): queryset = Posts.objects.all() return queryset How can I achieve to get the user email within the queryset ? -
Django views query output mixup when multiple users are using, how to prevent that
Hi am trying to select an option in html page and after running and doing some operations am trying to print those data For single user it is working fine but when multiple users are running at almost same time The data s getting mixed up and showing duplicate data and some time it is showing half data Could any one tell me how to saparate each user session and prevent output mixup Any leads would be very helpful, thanks -
pipenv - ERROR: Couldn't install package: psycopg2
I am running pipenv on macOS Monterey 12.4. I have the following Pipfile: url = "https://pypi.python.org/simple" verify_ssl = true name = "pypi" [packages] django = "<4.1" pyparsing = "*" pydot = "*" django-extensions = "*" coverage = "*" djangorestframework = "~=3.13" Markdown = "*" django-nested-admin = "*" drf-nested-routers = "*" drf-access-policy = "~=1.0" drf-yasg = "*" drf-social-oauth2 = "*" django-cors-headers = "*" black = "*" django-stubs = "*" djangorestframework-stubs = "*" dj-database-url = "*" gunicorn = "*" whitenoise = "*" psycopg2-binary = "*" psycopg2 = "*" sentry-sdk = "*" django-filter = "*" django-hashid-field = "*" channels = "~=3.0" djangochannelsrestframework = "*" celery = "==5.2.2" django-celery-results = "==2.2.0" channels-redis = "*" requests = "*" django-silk = "*" django-auto-prefetching = "*" drf-viewset-profiler = "*" django-lifecycle = "*" django-notifications-rest = "*" django-notifications-hq = "*" django-postgrespool2 = "*" [dev-packages] mypy = "*" [requires] python_version = "3.8" This has always worked fine up to now. I tried running the command: pipenv update sentry-sdk, and this is the output: (backend) samuelebonini@Samueles-MacBook-Pro-2 backend % pipenv update sentry-sdk Locking [dev-packages] dependencies... Building requirements... Resolving dependencies... ✔ Success! Locking [packages] dependencies... Building requirements... Resolving dependencies... ✔ Success! Updated Pipfile.lock (a39560)! Installing dependencies from Pipfile.lock (a39560)... An error occurred while … -
GitHub for Django on Azure: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt'
I am trying to deploy my Django code to Azure with GitHub actions. On GitHub actions I keep receiving the following error message: However, I have included a requirements.txt file in my project. I have tried moving the file to different folders, since GitHub actions does not seem to be able to find the file, but that does not resolve my issue. How can I see where Github actions is looking for my requirements, or does anyone have a suggestion on how to solve this? -
Django forms: rendering different data in forms per users login
Hello i'm currently making a webiste in Django, is it possible to render different select fields by querying the objects atributed in user via request.user.id to obtain and get the datas inputted by the user instead of all data gathered on all users? thank you so much class clientforms(forms.Form): projectfield = forms.ModelChoiceField(queryset= Project.objects.all(), widget=forms.Select(attrs={ 'class' : 'form-control', }) ) -
AttributeError: 'User_groups' object has no attribute '_delete'
Whenever I am trying to delete a usr from django-admin I am getting the following error '''AttributeError: 'User_groups' object has no attribute '_delete''' . When I am debugging it ,i am getting that '_delete' is there in the inbuilt libraries but it is not getting called , I am not understanding why it is happening .. Also i am using django-admin-honeypot latest version and django 2.2 -
How to get choices to work with Django REST framework
I have a model: class Film(models.Model): title = models.CharField(max_length=250) starring = models.CharField(max_length=250) description = models.CharField(max_length=500) rating = models.CharField(max_length=2, choices=(('1','U'),('2','PG'),('3','12A'),('4','12'),('5','15'),('6','18')),default='18') length = models.IntegerField() def __str__(self): return f"{self.title}, {self.rating}" and a serialiser: class FilmSerializer(serializers.ModelSerializer): class Meta: model = Film fields = ('title','description','starring','rating','length') def to_representation(self, instance): data = super().to_representation(instance) hours = math.floor(int(data['length']) / 60) minutes = int(data['length']) % 60 data['length'] = f"{hours}h {minutes}m" return data and an api view: class FilmList(ListAPIView): queryset = Film.objects.all() serializer_class = FilmSerializer filter_backends = (DjangoFilterBackend,) filterset_fields = ('rating',) When i use the Django Rest frame work I can filter by the rating, but only if i remove the choices definition from the model. When the choices definition is present on the 'rating' then the filter returns nothing at all. I would actually like to use that to filter on the 'rating.' Is there a way round this? thanks -
Set default value input tag Django
IN HTML : <div class="input-group" style="margin-top: 1vh;"> <input name="gen_down" type="number" class="form-control" /> <span class="input-group-text">%</span> </div> IN VIWES.py: gen_down = int(request.POST.get('gen_down', 0)) Run in Terminal: gen_down = int(request.POST.get('gen_down', 0)) ValueError: invalid literal for int() with base 10: '' -
How to allow switching to (nullable) infrastructure stubs in Django
Question - What approach or design pattern would make it easy in Django to use stubs for external integrations when running tests? With 'external integrations' I mean a couple of external REST APIs, and NAS file system. The external integrations are already separate modules/classes. What I do now - Currently, I disable external dependencies in tests mainly by sprinkling mock.path() statements across my test code. But this is getting unpractical (needs to be applied per test; also easy to forget especially in more high-level tests), and links too much to the internals of certain modules. Some details of what I am looking for I like the concept of 'nullable infrastructure' described at https://www.jamesshore.com/v2/blog/2018/testing-without-mocks#nullable-infrastructure. I am especially looking for an approach that integrates well with Django, i.e. considering the settings.py file approach, and running tests via python manage.py test. I would like to be able to easily: state that all tests should use the nullable counterpart of an infrastructure class or function override that behaviour per test, or test class, when needed (e.g. when testing the actual external infrastructure). I tried the approach outlined in https://medium.com/analytics-vidhya/mocking-external-apis-in-django-4a2b1c9e3025, which basically says to create an interface implementation, a real implementation and a stub implementation. … -
How to select multiple items with multiple quantities in django rest framework?
Models.py class BaseModel(models.Model): branch = models.ForeignKey(Branch, on_delete=models.PROTECT, blank=True, null=True) company = models.ForeignKey(Company, on_delete=models.PROTECT, blank=True, null=True) class Meta: abstract = True class MealMenu(BaseModel): employee = models.ForeignKey(Employee, on_delete=models.PROTECT, null=True, blank=True) item_name = models.CharField(max_length=50, null=True, blank=True) quantity = models.PositiveIntegerField() price = models.FloatField() def __str__(self): return f"{self.item_name} {self.price}" class MealOrder(BaseModel): RECEIVED = 'Received' PENDING = 'Pending' REJECTED = 'Rejected' MEAL_CHOICES = ( ('Breakfast', 'Breakfast'), ('Lunch', 'Lunch'), ('Dinner', 'Dinner'), ) STATUS_CHOICES = ( (RECEIVED, 'Received'), (PENDING, 'Pending'), (REJECTED, 'Rejected'), ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, null=False) total_items = models.IntegerField(null=True, default=0) total_amounts = models.FloatField(default=0.0) menu = models.ForeignKey(MealMenu, on_delete=models.PROTECT) quantity = models.PositiveIntegerField(default=1, blank=False) meal_time = models.CharField(max_length=25, choices=MEAL_CHOICES) employee = models.ForeignKey(Employee, on_delete=models.PROTECT) date = models.DateField(auto_now=True) status = models.CharField(max_length=25, choices=STATUS_CHOICES, default=PENDING) I have two models. In First Model i have created a menu item_name,price and quantity. In MealOrder i have foreign key MealMenu Model and created quantity field separately. I want to select multiple items with their multiple quantities. But i can't understand the scenario. -
How to run a docker image from within a docker image?
I run a dockerized Django-celery app which takes some user input/data from a webpage and (is supposed to) run a unix binary on the host system for subsequent data analysis. The data analysis takes a bit of time, so I use celery to run it asynchronously. The data analysis software is dockerized as well, so my django-celery worker should do os.system('docker run ...'). However, celery says docker: command not found, obviously because docker is not installed within my Django docker image. What is the best solution to this problem? I don't want to run docker within docker, because my analysis software should be allowed to use all system resources and not just the resources assigned to the Django image. -
How to make django-better-admin-arrayfield work with wagtail?
I am working with wagtail cms and want to use ArrayField. The default form for it is very inconvenient. I found a python package that has a better form field that is developed for Django admin. Also in the wagtail repository, I found an issue where an author states that he was able to make django-better-admin-arrayfield work with wagtail. I made several attempts but failed. Can anyone help me do it? -
unable to install django-allauth
When trying to install django-all auth with pip i get this error: Collecting django-allauth Using cached django-allauth-0.51.0.tar.gz (709 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [20 lines of output] Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 14, in <module> File "/usr/lib/python3/dist-packages/setuptools/__init__.py", line 12, in <module> import setuptools.version File "/usr/lib/python3/dist-packages/setuptools/version.py", line 1, in <module> import pkg_resources File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 77, in <module> __import__('pkg_resources.extern.packaging.requirements') File "/usr/lib/python3/dist-packages/pkg_resources/_vendor/packaging/requirements.py", line 9, in <module> from pkg_resources.extern.pyparsing import stringStart, stringEnd, originalTextFor, ParseException File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 672, in _load_unlocked File "<frozen importlib._bootstrap>", line 632, in _load_backward_compatible File "/usr/lib/python3/dist-packages/pkg_resources/extern/__init__.py", line 43, in load_module __import__(extant) File "/usr/lib/python3/dist-packages/pkg_resources/_vendor/pyparsing.py", line 943, in <module> collections.MutableMapping.register(ParseResults) AttributeError: module 'collections' has no attribute 'MutableMapping' [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. I'm on Ubuntu 18.04.6 LTS and using python3.10. I've tried updating pip. installing setuptools, build-essential, g++. With no result.