Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
ModuleNotFoundError: No module named 'my_site': when AWS CodePipeline (GitHub) deploy to Elastic Beanstalk (Django)
I've been stuck on this problem for 3 weeks. I've connected my GitHub to AWS CodePipeline and AWS CodePipeline is trying to deploy the code to AWS Elastic Beanstalk, but I keep getting the same error and can't figure out the solution. My ProcFile: web: gunicorn my_site.wsgi:application My file structure: -- .ebextensions -- django.config -- ProcFile -- tq_django -- my_site -- wsgi.py My wsgi.py import os import sys sys.path.insert(0, '/var/app/current/tq_django/my_site') from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_site.settings') application = get_wsgi_application() My django.config within .ebextensions option_settings: aws:elasticbeanstalk:container:python: WSGIPath: my_site.wsgi:application aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: my_site.settings aws:elasticbeanstalk:environment:proxy:staticfiles: /tq: static -
Use original template under admin directory
I have django script with administration page /admin Now I want to make another page /customdata for administration purpose. However in this page , customdata is not related to specific model, it just shows the system overview data. It is just the normal template. Now I have two ideas. Making independent www.myexample.com/customdata page and set authentication. Linking this under www.myexample.com/admin/customdata and treat it as admin page 2 sounds usefule to me, because pages for administration purpose should be togetter. However is it possible? or is it not good behaivor? -
Django (django-rest-framework) with Bootstrap Autocomplete. Filed Nameing
I want to autocomplate a field. But i can't figure out how i can accomplish properly because i don't know yet what is the industry standard. Seems to be the Bootstrap Autocomplete expect an particular field naming like this. I think this is hardcoded. (the "text" at least): [ { "value": 1, "text": "Google Cloud Platform" }, { "value": 2, "text": "Amazon AWS" }, { "value": 3, "text": "Docker" }, { "value": 4, "text": "Digital Ocean" } ] How i can alter/mask the filed names from ['id','provider'] to ['value','text'] in Django side? Let say i have: #modell class CloudProviders(models.Model): provider = models.CharField(max_length=255, blank=True, null=True) #id come by default ... #Serializer class CloudProvidersAutocompleteSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = CloudProviders fields = ['id','provider'] #view class CloudProvidersAutocomplete(viewsets.ModelViewSet): model = CloudProviders serializer_class = CloudProvidersAutocompleteSerializer def get_queryset(self): query= self.request.query_params.get('search') if query : data = CloudProviders.objects.filter(provider__contains=query) return data UPDATE I have a solution but the question still open, because i don't know if this is a proper solution: #modell class CloudProviders(models.Model): provider = models.CharField(max_length=255, blank=True, null=True) #id come by default def _getProvider (self): return self.provider text = property(_getProvider ) ... -
Django Rest Framework Serializers causing errors while Creating Serializers for circular dependent Models
I have these models in my app class Social_Data(models.Model): sdid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) youtube = models.CharField(max_length = 400) twitter = models.CharField(max_length = 400) github = models.CharField(max_length = 400) class Company(models.Model): name = models.CharField(max_length = 100) logo = models.FileField(upload_to = "media/") summary = models.CharField(max_length = 400, default="") advocates = models.ManyToManyField('Advocate', related_name="advocates", default="", blank=True) href = models.CharField(max_length = 100,default = "", blank = True, null=True) class Advocate(models.Model): name = models.CharField(max_length = 200) profile_pic = models.FileField(upload_to = "media/") short_bio = models.CharField(max_length = 300, blank=True) long_bio = models.CharField(max_length = 400, null=True, blank=True) advocate_years_exp = models.IntegerField(default = 0) company = models.ForeignKey(Company, null = True, on_delete=models.SET_NULL) links = models.OneToOneField(Social_Data, null = True, on_delete=models.SET_NULL) and these are my serializers.py from rest_framework import serializers from .models import * class SocialDataSerializer(serializers.ModelSerializer): class Meta: model = Social_Data # fields = "__all__" exclude = ["sdid"] class AdvocateSerializer(serializers.ModelSerializer): company = CompanySerializer() links = SocialDataSerializer() class Meta: model = Advocate fields = "__all__" class CompanySerializer(serializers.ModelSerializer): advocates = AdvocateSerializer(many=True) class Meta: model = Company fields = "__all__" How could I solve the issue regarding the lazy reference of advocates in company model while serializing data in serializers ? and for now my serializers shows the error "name Company is not defined" -
Is it possible to store aware datetime objects in django with different timezones for the values?
I've seen many different posts across SO about aware timezones in django (i.e. datetimes with a timezone value). Even converting naive datetime to aware I've read online that many applications that deal with timezones usually store everything in UTC to avoid any Day light savings conversions and then use frontend to handle the conversions. I'd like to know if it's possible to store an aware datetime with the actual timezone in my database. If so, how would I go about it? So instead of storing something like: 2022-10-13 13:56:00+00:00 I'd like to store: 2022-10-13 13:56:00+04:30 (US/Eastern) -
Related Field got invalid lookup: icontains - Django
Admin.py @admin.register(models.Student) class StudentAdmin(admin.ModelAdmin): list_display = ['first_name', 'last_name', 'city'] @admin.register(models.CourseTake) class CourseTakeAdmin(admin.ModelAdmin): list_display = ['student', 'course', 'grade', 'performance'] list_editable = ['grade'] search_fields = ['student'] def student(self, student): return student.first_name models.py class Student(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) date_adimitted = models.DateField(auto_now=True) address = models.CharField(max_length=255) city = models.CharField(max_length=255) state = models.CharField(max_length=255) def __str__(self) -> str: return f'{self.first_name} {self.last_name}' class CourseTake(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='coursetake') #similar to reviews in the product class course = models.ForeignKey(Course, on_delete=models.CASCADE) grade = models.DecimalField(max_digits=5, decimal_places=2) class Meta: unique_together = [['student', 'course']] def __str__(self) -> str: return f'{self.student.first_name} {self.student.last_name}' Admin panel where I tried searching for the names I have a search bar which I want to use to search for student names, but it keeps saying "Related Field got invalid lookup: icontains". However, student in the search_fields is a foreign key and I don't know how to manipulate it so I can search for any name. 'Request URL: http://127.0.0.1:8000/admin/student/coursetake/?q=kj' -
Error 403 on Heroku when deploying a Django project
I want to delete the repository inside my Heroku app by typing: -heroku plugins:install heroku-repo -heroku repo:reset -a appname after that i get the error: -Expected response to be successful, got 403 -
ProgrammingError at / after depploying my django project to heroku but wotking well on local host
I have made all the migrations as recommended in previous posts. I have also updated my settings.py as recommended inj previous posts. here is my console message; 2022-10-13T22:36:21.289647+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute 2022-10-13T22:36:21.289648+00:00 app[web.1]: with self.db.wrap_database_errors: 2022-10-13T22:36:21.289648+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__ 2022-10-13T22:36:21.289648+00:00 app[web.1]: raise dj_exc_value.with_traceback(traceback) from exc_value 2022-10-13T22:36:21.289648+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute 2022-10-13T22:36:21.289648+00:00 app[web.1]: return self.cursor.execute(sql, params) 2022-10-13T22:36:21.289648+00:00 app[web.1]: django.db.utils.ProgrammingError: relation "freelanceapp_post" does not exist 2022-10-13T22:36:21.289648+00:00 app[web.1]: LINE 1: ...t"."slug", "freelanceapp_post"."category_id" FROM "freelance... 2022-10-13T22:36:21.289648+00:00 app[web.1]: ^ 2022-10-13T22:36:21.289649+00:00 app[web.1]: 2022-10-13T22:36:21.290265+00:00 app[web.1]: 10.1.23.15 - - [13/Oct/2022:22:36:21 +0000] "GET / HTTP/1.1" 500 196793 "https://dashboard.heroku.com/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36" 2022-10-13T22:36:21.289879+00:00 heroku[router]: at=info method=GET path="/" host=victorkiprono.herokuapp.com request_id=b9f45047-6c65-44e5-975d-b0f71a4c023b fwd="105.161.25.118" dyno=web.1 connect=0ms service=133ms status=500 bytes=197110 protocol=https