Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use model method as default for field in django model?
I want to use instance method of my model as default value for a new field. How can I do this? The value should be calculated based on other fields and third-party library, so I have to use callable as default with arg of current instance or its fields. Is it ever possible? -
Remove the micro seconds from model method datetime objects
I have this method, it returns the time_left hence the name. My problem is the additional microseconds appended at the end. from django.utils.timezone import now class ModelClass(models.Model): .... due_date = models.DateTimeField() @property def time_left(self): data = {"in_negative": False} remaining = self.due_date - now() data["remaining"] = remaining if remaining.days < 0: data["in_negative"] = True return data This is what I get on my template 3 days, 10:38:53.070894 What I want 3 days, 10:38:53 -
Serializing a model in GeoDjango where the geo_field is in a related field
I have a model which is related to another model by a ManyToMany Relationship that contains the location data. I am trying to serialize this model, but am getting extra fields in my geojson file: Models.py class Historicalfile(models.Model): dmsesite = models.ManyToManyField(Dmsesite) name = models.CharField(verbose_name='Job Name', max_length=250) ... class Dmsesite(models.Model): ptgeom = models.PointField(srid=4326, blank=True, null=True) plgeom = models.PolygonField(srid=4326, blank=True, null=True) Serializers.py class DmsesitePtSerializer(serializers.ModelSerializer): class Meta: model = Dmsesite fields = ("ptgeom",) class HistoricalFileSerializer(serializers.GeoFeatureModelSerializer): dmsesite = DmsesitePtSerializer(many=True) class Meta: model = Historicalfile geo_field = "dmsesite" fields = ("company", "name",) Viewsets.py class DmsesitePtSerializer(serializers.ModelSerializer): class Meta: model = Dmsesite fields = ("ptgeom",) class HistoricalFileSerializer(serializers.GeoFeatureModelSerializer): dmsesite = DmsesitePtSerializer(many=True) class Meta: model = Historicalfile geo_field = "dmsesite" fields = ("company", "name",) This mostly works, except that I get an "extra" field in my GeoJson output: "properties": { "company": { "name": "Don-More Surveys" }, "name": "51938" } }, { "type": "Feature", "geometry": [ { "ptgeom": { "type": "Point", "coordinates": [ -65.66314398960121, 45.65473652218946 ] } } ], I am expecting something like: { "type": "Feature", "geometry": { "type": "Point", "coordinates": [ -65.09304726799569, 45.90454322923145 ] }, "properties": { "company": { "name": "Don-More Surveys" }, "name": "51938" } }, I belive my issue is related to this being a many-to-many … -
Python Django3 - Register form issue after deployment on VPS
I have problem with Register form for project deployed here: http://donation.rogalowski.uk:2052/ . Domain name from cloudflare. VPS host: www.mikr.us with reverse proxy to port 2052 unsecured. Dockerized. After click Załóż konto (Sign up) and filling the form it should send a mail verification, shows error: enter image description here For tests, debugging turned on. Registration works fine on localhost. How can I fix this? Github project: https://github.com/Rogalowski/Portfolio_oddam_w_dobre_rece views.py def send_activation_email(user, request): current_site = get_current_site(request) email_subject = 'Aktywacja konta na stronie ODDAM W DOBRE RĘCE' email_body = render_to_string('auth/activate.html', { 'user': user, # 'domain': 'donation.rogalowski.uk:30157', 'domain': current_site, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) email = EmailMessage( subject=email_subject, body=email_body, from_email=settings.EMAIL_FROM_USER, to=[user.email] ) email.send() def activate_user(request, uidb64, token): uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) if user and account_activation_token.check_token(user, token): user.is_email_verified = True user.is_active = True user.save() messages.add_message( request, messages.ERROR, 'Email zweryfikowany poprawnie, możesz się zalogować :)') return redirect('login_view') messages.add_message(request, messages.ERROR, f'Użytkownik źle zweryfikowany, prawdopodobnie aktywny!') return redirect('register_view') class RegisterView(View): def get(self, request): return render(request, 'register.html') def post(self, request, *args, **kwargs): name = request.POST.get('name') surname = request.POST.get('surname') email = request.POST.get('email') password = request.POST.get('password') password2 = request.POST.get('password2') if password == password2: password2 = make_password(password) else: messages.add_message( request, messages.ERROR, f'Podane hasła różnią się od siebie, spróbuj jeszcze raz!') … -
amadeus api giving 400 error in Hroku app
I have hosted django app that calls amadeus api to get some details. The issue is when running it on heroku it gives [400] but when I run application locally it is working fine, does any one have any idea what might be the issue. log snapshot for ref. -
obj argument returns with the "None" value when deploying the project on the cloud
I deployed my website on namecheap.com and when I'm trying to upload any image I meet this error: UnicodeEncodeError: 'ascii' codec can't encode characters in position 38-43: ordinal not in range(128) I took a few hours until I found the issue and the problem in this code: class MultipleImageManaged(admin.ModelAdmin): list_display = ('id', 'images') def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj=None, **kwargs) form.base_fields['images'].widget.attrs = { 'multiple': 'multiple' } return form def save_model(self, request, obj, form, change): for data in request.FILES.getlist('images'): cat_name = Category.objects.get(name=obj.category) if obj.album: album_name = Album.objects.filter(category__name=cat_name).get(name=obj.album) else: album_name = None Gallery.objects.create(images=data, category=cat_name, album=album_name) when I print out "obj" argument in get_form() method I figured out that this arg returns the "None" value knowing that, this argument is working in my localhost. actually, I don't know why it is working like that but now I'm trying to stick with another approach, I'm not sure if this approach will work properly but I need help with that. so, I'm trying right now to use signals instead and there's my new approach: from django.contrib import admin from .models import Gallery, Album, Category from django.db.models.signals import pre_save from django.dispatch import receiver class MultipleImageManaged(admin.ModelAdmin): list_display = ('id', 'images') def get_form(self, request, obj=None, … -
How to populate field with model method as default?
I want a migration created populate new field with calculated value which calculates as model instance method class Migration(migrations.Migration): dependencies = [ ('appname', '0001_initial'), ] operations = [ migrations.AddField( model_name='modelname', name='new_field', # model method to calculate a value for a new field based on existing data. # with the below I, as expected, get "... missing 1 required positional argument: 'self'" field=models.TextField(default=ModelName.calc_new_field), preserve_default=False, ), ] -
Django - How to set ForeignKey relation in forms.ModelForm
My task is to implement a form in which the choice of the value of the second field depends on the value of the first field. (For example, if the value of the first field is Cars, then the second field should show sedan/SUV, etc., if the value of the first field is Commercial vehicles, then the second box should show truck/bus, etc.) Code models.py: class TypeTransport(models.Model): transport_name = models.CharField(max_length=100, verbose_name='kind of transport') class TypeBodyTransport(models.Model): transport = models.ForeignKey(TypeTransport, on_delete=models.CASCADE, blank=True, null=True, verbose_name='kind of transport') body_name = models.CharField(max_length=100, verbose_name='transport body type') class Advertisement(models.Model): transport = models.ForeignKey(TypeTransport, on_delete=models.SET_NULL, blank=True, null=True, verbose_name='kind of transport') body = models.ForeignKey(TypeBodyTransport, on_delete=models.SET_NULL, blank=True, null=True, verbose_name='transport body type ') Code forms.py: class CreateAdvertisementForm(forms.ModelForm): transport = forms.ModelChoiceField(queryset=TypeTransport.objects.all(), to_field_name="transport_name") body = forms.ModelChoiceField(queryset=TypeBodyTransport.objects.filter(transport=transport), to_field_name="body_name") class Meta: model = Advertisement fields = ('transport', 'body') I thought it could be done with filter(transport=transport), but this error is returned: TypeError: Field 'id' expected a number but got <django.forms.models.ModelChoiceField object at 0x7f40d7af5ac0>. Can you please tell me how to implement the feature I need? -
Django show list of strings in textarea, each string from new line
I have a list lst=['apple', 'pear', 'peach']. I want to show each item in textarea from new line (removing redundant subspaces). <textarea> {% for item in lst %} {{ item }} {% if not forloop.last %}<br/>{% endif %} {% endfor %} </textarea> This code doesn't work. <br/>s are shown as they are. And there are redundant whitespaces at the beginning of the textarea and between the items. -
I got the error code trying to install django
Traceback (most recent call last): File "C:\Users\HP\myproject\lib\site-packages\pip_vendor\urllib3\response.py", line 438, in _error_catcher yield File "C:\Users\HP\myproject\lib\site-packages\pip_vendor\urllib3\response.py", line 519, in read data = self._fp.read(amt) if not fp_closed else b"" File "C:\Users\HP\myproject\lib\site-packages\pip_vendor\cachecontrol\filewrapper.py", line 62, in read data = self.__fp.read(amt) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\http\client.py", line 465, in read s = self.fp.read(amt) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\socket.py", line 705, in readinto return self._sock.recv_into(b) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 1273, in recv_into return self.read(nbytes, buffer) File "C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\ssl.py", line 1129, in read return self._sslobj.read(len, buffer) TimeoutError: The read operation timed out During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\HP\myproject\lib\site-packages\pip_internal\cli\base_command.py", line 173, in _main status = self.run(options, args) File "C:\Users\HP\myproject\lib\site-packages\pip_internal\cli\req_command.py", line 203, in wrapper return func(self, options, args) File "C:\Users\HP\myproject\lib\site-packages\pip_internal\commands\install.py", line 315, in run requirement_set = resolver.resolve( File "C:\Users\HP\myproject\lib\site-packages\pip_internal\resolution\resolvelib\resolver.py", line 94, in resolve result = self._result = resolver.resolve( File "C:\Users\HP\myproject\lib\site-packages\pip_vendor\resolvelib\resolvers.py", line 472, in resolve state = resolution.resolve(requirements, max_rounds=max_rounds) File "C:\Users\HP\myproject\lib\site-packages\pip_vendor\resolvelib\resolvers.py", line 341, in resolve self._add_to_criteria(self.state.criteria, r, parent=None) File "C:\Users\HP\myproject\lib\site-packages\pip_vendor\resolvelib\resolvers.py", line 172, in _add_to_criteria if not criterion.candidates: File "C:\Users\HP\myproject\lib\site-packages\pip_vendor\resolvelib\structs.py", line 151, in bool return bool(self._sequence) File "C:\Users\HP\myproject\lib\site-packages\pip_internal\resolution\resolvelib\found_candidates.py", line 140, in bool return any(self) File "C:\Users\HP\myproject\lib\site-packages\pip_internal\resolution\resolvelib\found_candidates.py", line 128, in return (c for c in iterator if id(c) not in self._incompatible_ids) File "C:\Users\HP\myproject\lib\site-packages\pip_internal\resolution\resolvelib\found_candidates.py", line 32, in _iter_built candidate = func() File … -
Django ccbv.co.uk
Is there something simillar to https://ccbv.co.uk site which is offline now? There was descriptions of all class and methods, with source code, in django class-based view on the site. -
How to add asyncio in django
I am trying to convert my code to asyncio and after watching many tutorials I wasn't able to convert to asyncio, Is there any way to convert this code to asyncio ? def get_sites(request): session = requests.Session() if request.method == 'GET': name = request.GET['name'] with open('sites-data.json') as f: data = json.load(f) mod_data = json.loads(json.dumps(data).replace("{}",name)) search_term = SearchTerm( user = request.user, name = name ) search_term.save() for item in mod_data: if mod_data[item]['errorType'] == "status_code": url = mod_data[item]['url'] urlMain = mod_data[item]['urlMain'] response = session.get(url) status_code = response.status_code if status_code == 200: site_data = SearchResult( url = urlMain, search_status = 'CLAIMED', ) site_data.save() else: site_data = SearchResult( url = urlMain, search_status = 'AVAILABLE', ) site_data.save() return render(request, 'main/search.html' ) -
django + nginx custom location block not working
I want to deploy django as backend server with nginx. I use daphne as asgi server due to django channel location /api { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://127.0.0.1:10131; } as you can see, http://127.0.0.1:10131 is django which should be connected to http://my_domain.com/api but django can't recognize requested uri. surely, I set FORCE_SCRIPT_NAME to /api What should I do further? please help. -
insert parent child data from a single form using api call Reactjs how?
One table is master table and second table is child table . One table has many child data. I have created an api which is working fine by postman. Now i want to create a form which will take master child data together and send jason data to the api . is there anyone expert please . Django/reactjs. -
Django: share local server with multiple laptops
is there a way to share my Django local server with multiple laptops. I wanted to build an exam web app to be done offline and to be later upload to online server. -
Django google kubernetes client not running exe inside the job
I have a docker image that I want to run inside my django code. Inside that image there is an executable that I have written using c++ that writes it's output to google cloud storage. Normally when I run the django code like this: container = client.V1Container(name=container_name, command=["//usr//bin//sleep"], args=["3600"], image=container_image, env=env_list, security_context=security) And manually go inside the container to run this: gcloud container clusters get-credentials my-cluster --region us-central1 --project proj_name && kubectl exec pod-id -c jobcontainer -- xvfb-run -a "path/to/exe" It works as intended and gives off the output to cloud storage. (I need to use a virtual monitor so I'm using xvfb first). However I must call this through django like this: container = client.V1Container(name=container_name, command=["xvfb-run"], args=["-a","\"path/to/exe\""], image=container_image, env=env_list, security_context=security) But when I do this, the job gets created but never finishes and does not give off an output to the storage. When I go inside my container to run ps aux I get this output: USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.0 2888 1836 ? Ss 07:34 0:00 /bin/sh /usr/bin/xvfb-run -a "path/to/exe" root 16 0.0 1.6 196196 66256 ? S 07:34 0:00 Xvfb :99 -screen 0 1280x1024x24 -nolisten tcp -auth … -
Why is my django project not working after I have shut down my pc
when I start a new django Project it works perfectly well but after I shutdown or restart my pc it does not work again. even though I have activated my virtual environment it keeps giving me errors. -
Django: Errors when switching DateTimeField into DateField
I'm working on a project with Django. I used DateTimeField() when I first created some Model. I also created hundreds of instances. Then I decided that DateField was more appropriate and changed it. when I migrate, It was migrated well without any warning messages. But when I try to access original instances made with DateTimeField, I received the following error. invalid literal for int() with base 10: b'13 00:00:00' The Error seems to have occured because datetimefield data remains even though format has changed. But I don't know how to resolve it since I get this errors even when I try to delete existing instances. I also wonder why this error appears. -
In django rest; i'm tying to POST an artiste with a ForeignKey relation
I would like to add data to table which having a foreignkey relatonship with user model through django rest api. models.py class Artiste(models.Model): slug = models.SlugField(unique=True) name = models.CharField(max_length=200) name_vo = models.CharField(max_length=200, blank=True, null=True) name_vo_romanji = models.CharField(max_length=200, blank=True, null=True) biographie = models.TextField(blank=True, null=True) image = models.ImageField(upload_to=artiste_get_upload_to, blank=True, null=True) date_birth = models.DateTimeField(blank=True, null=True) date_death = models.DateTimeField(blank=True, null=True) nationnality = models.ForeignKey(Countrie, related_name='Artiste_countrie', on_delete=models.CASCADE, null=True) profession = models.ManyToManyField(Profession, related_name='Artiste_profession', blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Countrie(models.Model): slug = models.SlugField(unique=True) code = models.CharField(unique=True, max_length=2) name = models.CharField(unique=True, max_length=200) nationnality = models.CharField(unique=True, max_length=200) image = models.ImageField(upload_to=countrie_get_upload_to, null=True) serialiser class ArtisteSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) slug = serializers.SlugField(required=False) name = serializers.CharField() name_vo = serializers.CharField(required=False) name_vo_romanji = serializers.CharField(required=False) biographie = serializers.CharField(style={'base_template': 'textarea.html'}, required=False) image = serializers.ImageField(required=False) date_birth = serializers.DateTimeField(required=False) date_death = serializers.DateTimeField(required=False) nationnality = CountrieSerializer(required=False) profession = ProfessionSerializer(many=True, required=False) created_at = serializers.DateTimeField(read_only=True) updated_at = serializers.DateTimeField(read_only=True) def create(self, validated_data): print(validated_data) return Artiste.objects.create(**validated_data) def update(self, instance, validated_data): instance.slug = validated_data.get('slug', instance.code) instance.name = validated_data.get('name', instance.name) instance.name_vo = validated_data.get('name_vo', instance.name_vo) instance.name_vo_romanji = validated_data.get('name_vo_romanji', instance.name_vo_romanji) instance.biographie = validated_data.get('biographie', instance.biographie) instance.image = validated_data.get('image', instance.image) instance.date_birth = validated_data.get('date_birth', instance.date_birth) instance.date_death = validated_data.get('date_death', instance.date_death) instance.nationnality = validated_data.get('nationnality', instance.nationnality) instance.save() return instance class CountrieSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) slug = serializers.SlugField(required=False) code = serializers.CharField() name … -
I got an error while trying to install psycopg2-binary
Error I want to learn to develop websites with python and Django. I bought a tutorial and made everything like the teacher. But while trying to install psycopg2-binary on my Mac to work with PostgreSQL 14, I got this error. Can anyone help me please. -
Custom actions in nested Django model
I currently have a model Thing that has User model as foreign key: class Thing(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) If I use Thing as standalone in admin, I can override deletion as follows: class ThingAdmin(admin.ModelAdmin): actions = ['delete_model'] def delete_model(self, request, obj): for o in obj.all(): # Do stuff o.delete() This works: if I go into admin, I click on 'Things', select which ones I wish to delete and the custom part runs (I wish there was a way to create a button instead of using a dropdown, but this is good enough). I do not, however, wish to have things as standalone in admin. I want them in a nested view from User model so that I could delete them directly from user view. For that reason, I use django-nested-admin: class ThingInline(nested_admin.NestedStackedInline): actions = ['delete_model'] def delete_model(self, request, obj): for o in obj.all(): # Do stuff o.delete() The things are displayed fine, but I am not getting a 'delete model' button anywhere. Question: how do i created custom actions for nested models? -
django-storages (azure) - accessing data without defining my azure container as the default file storage
So I have my azure storage which looks like this: class PublicAzureStorage(AzureStorage): account_name = 'myaccount' account_key = 'mykey' azure_container = 'mypublic_container' expiration_secs = None I want to get all the files that this container has and display them in my app - but my default file storage & static file storage are still local. From Azure I only want to get some .CSVs. How can I access this container as I said? In the docs it seems that I need to set Azure as the DEFAULT_FILE_STORAGE/STATICFILES_STORAGE in order to work. -
You are seeing this page because DEBUG=True is in your settings file and you have not configured any URLs
Getting the error: You are seeing this page because DEBUG=True is in your settings file and you have not configured any URLs. meetups/urls.py from django.urls import path from . import views urlpatterns = [ path('meetups/', views.index) #domain_name.com/meetups/ ] urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('meetups.urls')) ] views.py from django.shortcuts import render # Create your views here. def index(request): return render(request,'templates/meetups/index.html') -
How to upgrade my AWS ebs Platform from running Python 3.8 to python 3.10?
More specifically I am currently running Python 3.8 running on 64bit Amazon Linux 2/3.3.16. I was hoping to make it python 3.10. I have seen instructions online but I do not know where to run those commands and where to start. Thanks in advance for any help. -
Withdrawal in Django Rest API
I am getting an error "UserRoom object has no attribute 'images'" models.py class UserRoom(models.Model): objects = None categoty = [ ('President Lux', 'President Lux'), ('Lux', 'Lux'), ('Double', 'Double'), ('Standard', 'Standard'), ] name = models.CharField(max_length=150, choices=categoty, verbose_name='Категория') room_num = models.CharField(max_length=150,verbose_name='Доступные номера для категории') about = models.TextField(verbose_name='Подробности') price = models.IntegerField(verbose_name='Цена') img360 = models.FileField(verbose_name='Фотография в 360') class Meta: verbose_name = 'Номер (About)' verbose_name_plural = 'Номера (About)' class UserImg(models.Model): objects = None name = models.ForeignKey(UserRoom, on_delete=models.CASCADE, verbose_name='img2') img = models.FileField(upload_to='User img', verbose_name='Фотография') class Meta: verbose_name = 'Фотографию' verbose_name_plural = 'Фотографии' views.py class UserRoomViewSet(ModelViewSet): permission_classes = [AllowAny] queryset = UserRoom.objects.all() serializer_class = UserRoomSer serializers.py class UserImgSer(ModelSerializer): class Meta: model = UserImg fields = '__all__' class UserRoomSer(ModelSerializer): images = RelatedField( many=True, queryset=UserImg.objects.all()) class Meta: model = UserRoom fields = [ 'name', 'room_num', 'about', 'price', 'img360', 'images', ] urls.py from rest_framework import routers router = routers.DefaultRouter() router.register(r'room', UserRoomViewSet) urlpatterns = router.urls please help me with this problem i can't get json IN THE IDEA I SHOULD LOOK LIKE THIS { "images": [ { "name": "", "img": "" }, { "name": "", "img": "" } ], "name": "", "room_num": "", "about": "", "price": "", "img360": "" } ANOTHER PROGRAMMER HELPED ME AND EVERYTHING WORKS FOR HIM BUT WHY …