Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
OSMnx I want to get the time distance of the routes in minutes
Right now I have in meters, how do I convert them to minutes? orig_node = ox.nearest_nodes(G, X=fromLatLng[1], Y=fromLatLng[0]) dest_node = ox.nearest_nodes(G, X=toLatLng[1], Y=toLatLng[0]) # gets route in meters pathDistance = nx.shortest_path_length(G, orig_node, dest_node, weight='length') print('pathDistance: ', pathDistance) Here is an example of what it printed from one of my route distances. pathDistance: 3192.146999999999 Here are some more information: I don't know how much 3192.146999999999 Meters are in minutes. It would be hard to know when roads got different speed limits and also traffic lights. The vehicle type I'm using is Motorcycle or car, but I think I will mostly use Motorcycles, I don't even think I will use car, but maybe I will. I'm also doing this in Django, so not sure if Django would make this any easier. -
How to display category and subcategory in post serializer django-rest-framework
I need to extract categories and subcategories in Post serializer, because I need to put pagination, if I put pagination in category view, different amount of posts will come, so I need to put pagination in Post view, I need to return response so that it looks like this and I want to create rest api to return nested json like this [ { "id": 1, "title": "Taomlar", "subcat": [ { id: 2, title: "Milliy", post: [ { id: 1, title: 'Palov', summa: 300000, ... }, { id: 2, title: 'Palov', summa: 300000, ... }, ] }, ] } ] models.py class Category(Base): title = models.CharField(max_length=200) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') def __str__(self): return self.title class Post(Base): title = models.CharField(max_length=225) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='post') serializers.py class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = '__all__' class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' Can anyone please give me the solution for this problem -
model doesn't have migrations
I am working on the Django model. I migrate all the files of the app, but it is showing me the model doesn't have migrations and also no migration file in the folder, but init.py file exists in the folder. Please give me suggestions. admin [X] 0001_initial [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length [X] 0009_alter_user_last_name_max_length [X] 0010_alter_group_name_max_length [X] 0011_update_proxy_permissions [X] 0012_alter_user_first_name_max_length contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial -
Refresh a page when something new appears in Django
I'm creating a website for a local establishment that uses Ifood. Ifood provides an API that allows you to check information, both regarding establishments and incoming orders. The code is ready, but I can only show a new order update when manually refreshing the page. Which is a bit shippable. I thought about putting an automatic update with JavaScript at the given time, but it would be an ugly workaround. In this case, I'm getting JSON data, but in a more general context. How could I refresh the page as soon as new data appears? -
Filter serialized data with SerializerMethodField value in ModelSerializer in Django
There is SerializerMethodField 'schedule_name' in ModelSerializer in Django. schedule_name = serializers.SerializerMethodField() def get_schedule_name(self, obj): schedule_name = obj.name if obj.department is not None: schedule_name = obj.department.name + '-' + obj.name return schedule_name I want to filter by passing value for this 'schedule_name' in the serialized data. -
Is there a way to add the date field in models in a "from to" pattern for billing periods - Django
I am trying to add a billing period in the invoices that I am generating. Currently my model contains two seperate date fields, one that stores the start date of the billing period and the other stores the end date of the billing period. The model looks as below class Bill(models.Model): billing_period_start = models.DateField(null=True, blank=True) billing_period_end = models.DateField(null=True, blank=True) Question : Is there a way to add the two seperate date fields in a same model field so that I can get a from "DateField" to "DateField" pattern in the admin pannel and have the billing period in a single field. -
Cannot do axios PUT request in Django REST+ React framework - Request failed with status code 400
When i try to update data in my Django SQLite database through reactJS it shows an error like this, but it works the last day fine even though I didn't change any code here now it's now working and it shows error that I had mentioned below PUT http://127.0.0.1:8000/employee/1 400 (Bad Request) AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …} // Update Employee const updateEmployee = (id) => { Axios.put("http://127.0.0.1:8000/employee/"+id, { name: name, age: age, email: email, designation: designation }); console.log(Axios.put); Swal.fire("Updated!", "", "success"); // window.location.reload(); }; return( <> <h1 className="text-left text-danger">Update Employee</h1> <div className="container"> <div className="row"> <div className="col-md-12"> <div className="form-group"> <label>Name</label> <input type="text" className="form-control" placeholder="Enter Name" defaultValue={data.name} onChange={(e) => setName(e.target.value)} /> </div> <div className="form-group"> <label>Age</label> <input type="text" className="form-control" placeholder="Enter Age" defaultValue={data.age} onChange={(e) => setAge(e.target.value)} /> </div> <div className="form-group"> <label>Email</label> <input type="text" className="form-control" placeholder="Enter Email" defaultValue={data.email} onChange={(e) => setEmail(e.target.value)} /> </div> <div className="form-group"> <label>Designation</label> <input type="text" className="form-control" placeholder="Enter Designation" defaultValue={data.designation} onChange={(e) => setDesignation(e.target.value)} /> </div> <div className="mt-2"> <button className="btn btn-primary" onClick={() => updateEmployee(data.id)}>Update</button> <Link className="btn btn-danger mx-2" to="/">Cancel</Link> </div> </div> </div> </div> </> ) -
Django, relating model to another app models field
First off this may not be the best way to set this up, however, I'm learning as I go and struggling to find the correct answer. I have an Account app which handles the user signup, I added the couple_choice option which I'm trying to get in another app's model. ACCOUNT model class Account(AbstractBaseUser): COUPLE_CHOICE = Choices('single', 'couple') email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) profile_image = models.ImageField(max_length=255, upload_to=get_profile_image_filepath, null=True, blank=True, default=get_default_profile_image) hide_email = models.BooleanField(default=True) couple_choice = models.CharField(choices=COUPLE_CHOICE, default='single', max_length=20) I then have another app Profile, which I want to make the couple = to the Account.account.couple_choice, or if the Account.couple.choice is 'couple' then Profile.couple = True from account.models import Account class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,blank=True, null=True, related_name="swinger") couple = models.ManyToManyField(Account, to_field="couple_choice", blank=True, null=True,related_name="is_couple", on_delete=models.CASCADE) PLease let me know the best way to do this? Thanks