Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding tasks to crontab does not work in docker container for image python:3.9.16-slim
I'm creating a container for a Django website. I need a dump DB every two weeks and sent to Google mail as a backup. To do this, I want to add two tasks to the crontab in the container where Django works, one will create a database dump, the other will archive it and send it to the mail. But I faced with a problem. I wrote the following in the Dockerfile: RUN apt update && apt install -y cron # Copy crontab2.txt file to the cron.d directory COPY crontab2.txt /etc/cron.d/new_cron # Give execution rights on the cron job RUN chmod 0644 /etc/cron.d/new_cron # Apply cron job RUN crontab /etc/cron.d/new_cron # Create the log file to be able to run tail RUN touch /var/log/cron.log # Run the command on container startup CMD ["cron", "-f"] In the process of creating the container, I received the following log: Step 4/27 : RUN apt update && apt install -y cron ---> Running in 715c47ebdac4 ... The following NEW packages will be installed: ... cron ... Get:2 http://deb.debian.org/debian bullseye/main amd64 cron amd64 3.0pl1-137 [99.6 kB] ... Selecting previously unselected package cron. Preparing to unpack .../1-cron_3.0pl1-137_amd64.deb ... Unpacking cron (3.0pl1-137) ... ... Setting up cron … -
I’m on my first ever django-python web project. CSS is messing up a lot
The html code: <div class=“main”> <img src={% static path/to/my/image %} alt=“image1” class=“second-image”> <div class=“about”> <h3>Dummy text</h3> <p>Lorem ipsum dolor sit amet</p> <button class=“btn”>Learn More</button> </div> </div> The media query I gave is (@media (max-width: 600px) I’m not copy-pasting my code as I’m typing this up on my phone. It’s also my first time in here. I’ve been trying way too many methods and got mixed up with what I wanted. Anyway, I built this webpage that’s looking good and working fine. I didn’t add any media queries and hence it isn’t responsive. What I’m trying to do now is to get the text to the bottom of the viewport and the image, placed left to the text, to the top. It’s something subtle but I can’t get it out. In case any of this is unclear, what I want is a smooth responsive page where the image gets displayed right after the text. I don’t think I can keep going if the first step is not going right. I don’t get how positioning works. Also, this part of the code comes after the hero section with those fancy picture and navigation bar and all that. When I tried different methods, … -
How do I get my background image to fit exactly within its responsive container - i.e. NOT keeping its aspect ratio?
All questions I come across talk about keeping an image's aspect ratio. I don't want the image to keep its aspect ratio. I want the image's width to exactly match the container's width, and the image's height to exactly match the container's height. The container is responsive. None of the settings I have tried solve this problem. Assuming my image is originally square and the responsive container is a horizontal rectangle: background-size: cover; This fills the container horizontally but keeps the aspect ratio, so it doesn't squash the image to fit completely within the container. background-size: contain; This fills the container vertically but repeats the image to fill it horizontally. It does not stretch the image horizontally to fill the container. Auto, inherit, unset, etc. are all just variations of keeping the aspect ratio. How can I make it so that my image dimensions match exactly the responsive container dimensions? My website project is only using DJango, CSS, HTML. -
Why does iterating over CheckboxSelectMultiple render bound method?
I am trying to iterate over a MultipleChoiceField with it's widget set as CheckboxSelectMultiple. I'm following the documentation specified here, which clearly states that I should be able to use {{ foo.tag }} to render the input element, however when I try, it renders this: <bound method BoundWidget.tag of <django.forms.boundfield.BoundWidget object at 0x7fbce1e38fd0>> It renders {{ foo.choice_label }} correctly. I have tried setting up a test project with roughly the same layout as below to test if this also happens in other projects, but there it rendered properly. I also tried to swap the widget to RadioSelect, which the documentation uses, but this also did not render properly. I use jinja2 as the template engine. forms.py: class GivePermissionsForm(forms.Form): def __init__(self, id, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["users"] = forms.MultipleChoiceField( choices=get_users(id), widget=forms.CheckboxSelectMultiple() ) users = forms.MultipleChoiceField() Note: get_users(id) is a method that returns a list of tuples in the format (user_id, user_name) views.py: def overview(request, id): # other, nonrelevant code form = GivePermissionForm(id) return render(reqest, "myapp/overview.jinja", {"form": form}) Note: overview.jinja2 includes form.jinja2. form.jinja2: <form> {% for user in form.users %} <label for="{{ user.id_for_label }}">{{ user.choice_label }}</label> {{ user.tag }} {% endfor %} </form> I also tried to set choices in CheckboxSelectMultiple, but … -
Docker doesn't see .env in dockerfile when trying to run Django collectstatic
I have multiple containers run in the order stated in docker-compose. In an app container, I need to execute file collectstatic. The thing is when I try to do it in dockerfile like that: RUN python manage.py collectstatic it breaks down as it doesn't see env vars, although the file is declared in the docker-compose. When I omit that line (and lines in other containers that depend on it) and I log into the container and generate the files - everything runs smoothly. How can I run it automatically? -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe1 in position 29: invalid continuation byte
File "C:\Users\binc2\AppData\Roaming\Python\Python311\site-packages\keras\saving\saving_api.py", line 212, in load_model return legacy_sm_saving_lib.load_model( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\binc2\AppData\Roaming\Python\Python311\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler raise e.with_traceback(filtered_tb) from None File "C:\Users\binc2\AppData\Roaming\Python\Python311\site-packages\tensorflow\python\lib\io\file_io.py", line 703, in is_directory_v2 return _pywrap_file_io.IsDirectory(compat.path_to_bytes(path)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe1 in position 29: invalid continuation byte help me please, i don't know why this error occurs! -
not using django auth.login_required decorator will throw a TypeError of adding different data type fields together.Why?
Hello I have figured out the solution for my problem but I want to know why isit occuring in the first place. I am a beginner in django. I am buidling a social media website which has a function for handling likes on a post everything is working fine now. I figured the following error occured when i did not use login_required decorator it would throw error Tried to update field core.LikePost.post_id with a model instance, <Post: jay>. Use a value compatible with CharField. @login_required(login_url="signin") def like_post(request): username = request.user.username post_id = request.GET.get('post_id') post = Post.objects.get(id=post_id) like_filter = LikePost.objects.filter(post_id=post_id,username=username).first() if like_filter == None: new_like = LikePost.objects.create(post_id=post,username=username) new_like.save() post.no_of_likes = post.no_of_likes + 1 post.save() return redirect('/') else: like_filter.delete() post.no_of_likes = post.no_of_likes-1 post.save() return redirect("/") Models.py class Post(models.Model): id = models.UUIDField(primary_key=True,default=uuid.uuid4) user = models.CharField(max_length=100) image = models.ImageField(upload_to="post_images") caption = models.TextField() created_at = models.DateTimeField(default=datetime.now) no_of_likes = models.IntegerField(default=0) def __str__(self): return self.user class LikePost(models.Model): post_id = models.CharField(max_length=500) username = models.CharField(max_length=100) def __str__(self): return self.username I receive the error when i remove the login_required decorator.I just want to know why is this happening. Can somebody please explain why is this happening? -
pymongo.errors.OperationFailure: namespace name generated from index name is too long
I know the index name is too long, django_content_type_app_label_model_76bd3d3b_uniq, but this is auto genarate by django makemigrations, so how to edit and contral this long index name? TKS! pymongo.errors.OperationFailure: namespace name generated from index name is too long, full error: {'ok': 0.0, 'code': 67, 'errmsg': 'namespace name generated from index name is too long', 'operationTime': Timestamp(1677686036, 1)} The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/ec2-user/miniconda3/envs/py38/lib/python3.8/site-packages/djongo/cursor.py", line 51, in execute self.result = Query( File "/home/ec2-user/miniconda3/envs/py38/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 784, in __init__ self._query = self.parse() File "/home/ec2-user/miniconda3/envs/py38/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 869, in parse raise exe from e djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: None FAILED SQL: ALTER TABLE "django_content_type" ADD CONSTRAINT "django_content_type_app_label_model_76bd3d3b_uniq" UNIQUE ("app_label", "model") Params: () Version: 1.3.6 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/ec2-user/miniconda3/envs/py38/lib/python3.8/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/ec2-user/miniconda3/envs/py38/lib/python3.8/site-packages/djongo/cursor.py", line 59, in execute raise db_exe from e djongo.database.DatabaseError -
Getting access token from vk.com. Django
The bottom line is this: make a so-called VK binding in order to obtain an access token. I'm trying to make a request, an error is thrown: { "error": "invalid_client", "error_description": "client_id is undefined" } I also first tried to authorize via VK, thinking that I could get an access token this way (I don’t know if it’s possible so really get it), and I sort of managed to implement authorization, and there were no errors about client_id. The question is: Is the idea of obtaining an access token correct (meaning, is it really done the way I intended, or is everything fundamentally wrong)? If not, how can it be implemented, if so, where are the errors? Code below views.py redirect to vk @login_required def vk_link(request): return redirect('https://oauth.vk.com/access_token/', params={ 'client_id': 'id', 'client_secret': 'token', 'redirect_url': 'http://127.0.0.1:8000/profile', 'code': request.GET.get('code'), }) urls.py urlpatterns = [ re_path(r'^login', views.login, name="login"), path('admin/', admin.site.urls), path('', views.index, name="main"), path('signUp', views.signUp, name="signUp"), path('profile', views.profile, name='profile'), path('logout', views.logout_view, name='logout'), path('vk', views.vk_link, name="vk"), ] **redirect button** <a href="{% url 'vk' %}"> <img src="" alt="vk"> </a> id and secret replaced for obvious reasons -
How to set WordPress to sub directory with Python(Django) project in nginx?
I want to set WordPress to the sub directory of the server that uses the root directory in the Python(Django) project. sample.com/ -> for Python(Django) project sample.com/wordpress -> for wordpress project The nginx configuration file is set as bellow, but if I access the URL sample.com/wordpress that I want to show WordPress, it will show 404 Not Found. How should I make the nginx configuration file in this case? server { listen 443 ssl default_server; server_name sample.com; ssl on; ssl_certificate /etc/letsencrypt/live/sample.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/sample.com/privkey.pem; location =/fabicon.ico {access_log off; log_not_found off;} location /static{ alias /usr/share/nginx/html/static; } location /media{ alias /usr/share/nginx/html/media; } location /{ include proxy_params; proxy_pass http://unix:/home/user/project/project/project.sock; } location /wordpress { alias /var/www/wordpress; index index.php; try_files $uri $uri/ /wordpress/index.php?q=$uri&$args; } location ~ ^/wordpress/.+\.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; } } -
Python3.9 Django Web API FrameWork Models - join Tables and convert to API
I have two tables, table A & table B, table A is managed = 'true' and table B is false. table A data from user input and table B data is from JIRA, table B will have more records compared to table A. I'm loading table B data from csv using load mysql statement. I converted table A to API and table B to API using Django rest framework. but I need table A + Table B data to covert it into API so that I can produce the results in web. Below is the sample model definition which I have. class modelA(models.Model): id=models.CharField(max_length=100, primary_key=True) type=models.CharField(max_length=100, null=True) comments=models.CharField(max_length=100, null=True) class modelB(models.Model): id=models.CharField(max_length=100, primary_key=True) status=models.CharField(max_length=100, null=True) duedate=models.DateField(null=True) I want left join modelA with modelB, and display all the data based on id column and convert it to API using Django Web Framework. I don't know how to do this, I googled and got many examples which specifies foreign key in model without primary key, and cascade delete option, but I don't want to delete anything and as I mentioned modelB is not managed by Django, could someone please suggest some simple steps to achieve this?, Thank You!! python 3.9, Distribution Redhat … -
How to Use Socket.io to send Messages from Django views.py?
so i am a bit new to this OK, so when i do it from outside the views.py it works perfectly and it console.logs in my browser running django my socketio_server.py file in the Django project folder import socketio import eventlet.wsgi # create a Socket.IO server sio = socketio.Server(cors_allowed_origins='*') # wrap with a WSGI application app = socketio.WSGIApp(sio) @sio.event def connect(sid, environ): print('Client connected:', sid) # start the server and listen for connections if __name__ == '__main__': eventlet.wsgi.server(eventlet.listen(('0.0.0.0', 8080)), app) I then run this file using python3 socketio_server.py in the terminal python3 socketio_server.py (325591) wsgi starting up on http://0.0.0.0:8080 my JS file const socket = io('http://localhost:8080'); socket.on('connect', () => { console.log('Socket connected'); }); // # The below message needs to come from django views, but i get no such message in the console output socket.on('django', (data) => { console.log(data); }); so in the above js file i get the console.log of socket.on (connect) but not the below message which comes from the views my views.py file from practice.socketio_server import sio # Create your views here. def socket_testing(request): sio.emit("django","THIS MESSAGE IS FROM DJANGO VIEWS") print("I GOT THE MESSAGE") return render(request, 'testing/socket_testing.html') i run my python3 manage.py runserver 0.0.0.0:9000 and the python3 … -
How to implement a multi form 'wizard' using forms
I'm not using django-formtools, just built in forms. I'm struggling to understand the correct flow to construct such a view. I was trying to chain my logic like so def step_one(request, ...): if request.method == 'POST': form = step_one_form(data=request.POST) else: form = step_one_form() if form.is_valid(): foo = request.POST.get('foo') return step_two(request,foo) return render(request, 'wizard.html', context={'form',form}) def step_two(request, ...) if request.method == 'POST': form = step_two_form(data=request.POST) else: form = step_two_form() if form.is_valid(): foo = request.POST.get('foo') bar = request.POST.get('bar') return step_three(request, foo, bar) return render(request, 'wizard.html', context={'form',form} def get_view(request): return step_one(request) Edit: I realized that I can past data=request.POST to my form constructor, and that kind of works, but because step_two etc are always POST the form always shows "this field is required" errors on the first rendering. What is the preferred technique to not render the error on first load? Do you have to use a hidden field or something? -
How can I refer a field from a table which is not related with the field directly?
I am always confused by Django ORM especially joining tables, I think I am weak at it. I tried to JOIN 4 tables, Order, OrderDetail, Item and ItemPhoto and access to ItemPhoto.photo from Order table. However, I do not know what to do. Please let me ask you some good way to JOIN my tables. Thank you. PS. Maybe, my database schema is not good??? First Approach (without thinking deeply): # Error occured because Order table doesn't have item Field. subqs = ItemPhoto.objects.filter(item=OuterRef('item')).filter(priority=1) queryset = Order.objects.prefetch_related( Prefetch( 'orderdetail_orderid', queryset=OrderDetail.objects.select_related('order', 'item'), to_attr='oor', ), ).filter(user=user).order_by('-order').annotate( item_photos=Subquery(subqs.values('photo')), ) # FieldError: Cannot resolve keyword 'item' into field. Choices are: created_at, id, orderdetail_orderid, total_price, user, ... Second approach: # I read Manual and followed a way I found in it. # But, in this case, OuterRef(OuterRef('item')) means User.item??? subqs = ItemPhoto.objects.filter(item=OuterRef(OuterRef('item'))).filter(priority=1) # ◆ Changed ◆ queryset = Order.objects.prefetch_related( Prefetch( 'orderdetail_orderid', queryset=OrderDetail.objects.select_related('order', 'item'), to_attr='oor', ), ).filter(user=user).order_by('-order').annotate( item_photos=Subquery(subqs.values('photo')), ) # ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. Third Approach: queryset = Order.objects.prefetch_related( Prefetch( 'orderdetail_orderid', queryset=OrderDetail.objects.select_related('order', 'item').prefetch_related('item_photo'), # ◆ Changed ◆ to_attr='oor', ), ).filter(user=user).order_by('-order') # ◆ Changed ◆ # AttributeError: Cannot find 'item_photo' on OrderDetail object, 'item_photo' … -
What does mean from the Django Framework
If you want to change the server’s IP, pass it along with the port. For example, to listen on all available public IPs (which is useful if you are running Vagrant or want to show off your work on other computers on the network), use: python manage.py runserver 0.0.0.0:8000 What does it mean by listen on all available public IPs? I just want to know what it means -
django prefetch_related filtered with object column
models: class Person(models.Model): birth_date = models.DateField() class PersonData(models.Model): (...) last_name = models.CharField(max_length=255) valid_from = models.DateField() #default data urodzenia (Person) valid_to = models.DateField(default=date(year=2999,month=12,day=31)) class Transaction(models.Model): person = models.ForeignKey(Person, on_delete=models.RESTRICT) (...) And now I want to get transaction which are before context_date: context={} context[context_date]=date.today() transactions = Transaction.objects.filter(execution_date__lte=context['context_date']).prefetch_related.prefetch_related(Prefetch('person__persondata_set',queryset=PersonData.objects.filter(valid_to__gte=context['context_date'],valid_from__lte=context['context_date']))) But this is inproper - because the prefetch data uses in global context_date. I want to have name relevant to transaction.execution_date not context_date! Transaction.objects.filter(execution_date__lte=context['context_date']).prefetch_related.prefetch_related(Prefetch('person__persondata_set',queryset=PersonData.objects.filter(valid_to__gte=execution_date,valid_from__lte=execution_date))) -
Django does not see a change in the primary key data type
In the data model, I changed the data type from INT to VarChar for the ID field. Unfortunately, this change was not noticed by macemigrations and I was forced to do a migrate zero and generate the migration file from scratch. Unfortunately, this didn't help either, as the ID field was still of type INT. Therefore, I modified the file and did the migrations. A table as I expected was created in the database. I even did a manual INSERT into the database which ended up being a succes. Unfortunately, Django has a problem with the insert and throws an error : Field 'id' expected a number but got '230301-001'. Request Method: POST Request URL: http://192.168.1.249:8080/maintenance/new Django Version: 4.1.3 Exception Type: ValueError Exception Value: Field 'id' expected a number but got '230301-001'. I also paste the stack: /home/gaza/projects/django/maintenance/models.py, line 60, in save super(Report, self).save(*args, **kwargs) … Local vars Variable Value __class__ <class 'maintenance.models.Report'> args () id_date '230301' kwargs {} new_id '230301-001' qs <QuerySet []> self <Report: 230301--001> today datetime.datetime(2023, 3, 1, 14, 19, 41, 369941) user <SimpleLazyObject: <User: superadmin>> Below is my model definition and the SQL itself from the database that created the tables. class Report(ModelBaseClass): id = models.CharField(max_length=10, … -
Why gunicorn returns 403 forbidden after nginx proxing?
I have a django app which I run using gunicorn inside docker container. Then I use nginx as proxy server. When I request open container port directly (http://localhost:8899/) it's working OK, but when I trying request http://localhost I/m getting 403 Forbidden error from gunicorn "GET / HTTP/1.0" 403. Do you have any ideas what I'm doing wrong? # nginx.conf upstream django { server web:8000 fail_timeout=30 max_fails=30 weight=50; server web:8000 fail_timeout=30 max_fails=30 weight=50; } ... location = / { root /src; try_files $uri @django; } location / { root /src; try_files $uri @django; } location @django { proxy_pass http://django; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } # docker-compose.yml nginx: ports: - mode: host target: 80 published: "8080" protocol: tcp - mode: host target: 443 published: "443" protocol: tcp ... web: ports: - mode: host target: 8000 published: "8899" protocol: tcp ... -
How to pass value in a Get request in React so I can apply filter on the backend?
I would like to retrieve a list of filtered messages from my API to my React App. On the backend the view for the Message Model looks like this. class MessageView(viewsets.ModelViewSet): """View for the messages""" serializer_class = MessageSerializer queryset = Message.objects.all() permission_classes = [IsAuthenticated] def get_queryset(self): """Retrieve recipes linked to the authenticated user""" return self.queryset.filter(channel = self.request.channel) def perform_create(self, serializer): """ Create a new recipe """ serializer.save(user=self.request.user) It re writes the get_queryset() function so I only retrieve the messages from a given channel which is a ForeignKey of Message. On the React part is there any way to pass the channel object in the request so that channel = self.request.channel would work? Alternatively I could just retrieve all the messages and then filter on the frontend. But I feel like filtering from the api view would be better, or am I completly wrong? Thanks, -
Inlined buttons are forced into a new line when converted to django form fields
Here's what I'm trying to replicate using django form and view classes: * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Roboto', sans-serif } body { height: 100vh; padding: 10px } label[for^='id_choice'], .selectable { display: flex; margin-top: 10px; padding: 10px 12px; border-radius: 5px; cursor: pointer; border: 1px solid #ddd; margin-right: 5px; } .selectable:active { border: 1px solid #0d6efd; } .selectable:hover { background: #0f5132; } input[type='radio'] { width: 22px; height: 22px; margin-right: 10px; } input[type='radio']:before { content: ''; display: block; width: 60%; height: 60%; margin: 20% auto; border-radius: 50%; } input[type="radio"]:checked:before { background: #20c997; } input[type="radio"]:checked { border-color: #20c997; } .selectable:has(input:checked){ border: 1px solid #20c997; } button[type="submit"] { display: block; margin-top: 20px; margin-left: 45%; } .selectable-btn { width: 45px; height: 45px; margin-top: 10px; margin-right: 5px; } <input type="text" class="form-control selectable" placeholder="Title"> <div class="input-group"> <input type="text" class="form-control selectable" placeholder="Selection"> <button class="btn btn-success add-form-row selectable-btn">+</button> <button class="btn btn-danger remove-form-row selectable-btn">-</button> </div> which allows the +/- buttons to be inlined with the second text input. So I use the following form class: from django import forms class SelectionForm(forms.Form): title = forms.CharField( max_length=255, widget=forms.TextInput( attrs={'placeholder': 'Title', 'class': 'form-control selectable'} ), label='' ) selection = forms.CharField( max_length=255, widget=forms.TextInput( attrs={'placeholder': 'Selection', 'class': 'form-control selectable'} ), label='' ) … -
How to create custom validator class for serializer in django python?
I need to remake this validator method, create a custom validator class, check that it is impossible to subscribe to itself. I'm new to this, please help, according to the examples from the documentation, I could not do this. class FollowSerializer(serializers.ModelSerializer): following = serializers.SlugRelatedField( queryset=User.objects.all(), slug_field='username' ) user = serializers.SlugRelatedField( read_only=True, slug_field='username', default=serializers.CurrentUserDefault(), validators=[CheckingYourSubscription] ) def validate_following(self, following): user = self.context['request'].user if user == following: raise serializers.ValidationError( 'Subscriptions to yourself are prohibited!' ) return following class Meta: fields = '__all__' model = Follow validators = [ serializers.UniqueTogetherValidator( queryset=Follow.objects.all(), fields=('user', 'following'), message='This subscription has already been issued.' ), ] -
How to extract and return data from multiple tables via foreign keys with django rest?
I have the following models: class Stock(models.Model): bar_id = models.ForeignKey(Bar, on_delete=models.CASCADE, related_name="bars") stock = models.IntegerField() class Bar(models.Model): name = models.CharField(max_length=200) Note that one Bar can have multiple Stock I would like, for one Bar, to retrieve and return all the stocks that are associated. SO, in my urls, I have: path('stock/<int:pk>/', views.StockListPerBar.as_view()) With the view being: class StockListPerBar(generics.RetrieveAPIView): queryset = Bar.objects.all() serializer_class = StockListPerBarSerializer And the serializer is: class StockListPerBarSerializer(serializers.ModelSerializer): bars = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Bar fields = ["name", "bars"] This provide the following output: { "name": "Some bar name", "bars": [ 4, 5, 6, 7 ] } However, I would like the output to be a bit different, like so (truncated): [ { "id": 4, "stock": 10 }, { "id": 5, "stock": 0 } ] How may I achieve that ? -
Django Form Add user from a specific group
I'm new with Django. There is my model : class Classe(models.Model): title = models.CharField(max_length=25) titulaire = models.ForeignKey(User, related_name='titulaire', on_delete=models.SET_NULL, null=True, blank=True) In a form, I would like add the "titulaire" field and select user from a specific group. Any tips ? Thanks I'll tried something like that.. class ModifyClasse(ModelForm): class Meta: model = Classe fields = ['title' , 'year', 'titulaire', 'cotitulaire'] def __init__(self, *args, **kwargs): qs = User.objects.filter(groups__name__in=['Profs']) titulaire = kwargs.pop('qs', None) super(ModifyClasse, self).__init__(*args, **kwargs) del self.fields['titulaire'] -
Django: import error or possible settings misconfiguration
I am trying to use a model I created in myapp/models.py in another file called store.py, but every attempt to import models.py has failed. Both store.py and model.py are in my Django app folder. Here is what I tried so far: A) from . import models radio = models.Radio(....) ImportError: attempted relative import with no known parent package B) from myapp.models import Radio radio = Radio(....) ModuleNotFoundError: No module named 'myapp' C) from .models import Radio radio = Radio(....) ImportError: attempted relative import with no known parent package D) from models import Radio radio = Radio(....) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Note: manage.py makemigrations && manage.py migrate have already been run after creating the model myapp is installed in settings.py's INSTALLED_APPS as 'myapp.apps.MyappConfig' My tree: ├── base │ ├── __init__.py │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── myapp │ ├── __init__.py │ ├── __pycache__ │ ├── admin.py │ ├── apps.py │ ├── fetch.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── __init__.py │ ├── models.py │ ├── scripts │ ├── static │ │ └── … -
DRF - serializer saves data but changes a date?
I have the following output from print(serializer.data): [OrderedDict([('last_price', '62.63'), ('name', None), ('country', None), ('sector', None), ('industry', None), ('ticker', 'VUSA'), ('high_price', 62.7075), ('last_date_time', '2023-03-01T00:00:00+04:00')])] When I go and look in the database(sql and postgres) the last_date_time field is: 2023-02-28 20:00:00. The create statement: def create(self, request, *args, **kwargs): if self.request.user.is_superuser: serializer = self.get_serializer(data=request.data, many=isinstance(request.data, list)) serializer.is_valid(raise_exception=True) print(serializer.data) self.perform_create(serializer) return Response({"Status": "We should be done"}) The model: class UsStockPriceModel(models.Model): ticker = models.CharField(max_length=30, blank=False, db_index=True) name = models.CharField(max_length=150, blank=True, null=True) # mainly for US stocks country = models.CharField(max_length=100, blank=True, null=True) sector = models.CharField(max_length=100, blank=True, null=True) industry = models.CharField(max_length=100, blank=True, null=True) last_price = models.FloatField(blank=True, null=True) high_price = models.FloatField(blank=True, null=True) last_date_time = models.DateTimeField(db_index=True) created_at = models.DateTimeField(auto_now_add=True) The Serializer: class UsStockPriceSerializer(serializers.ModelSerializer): # ticker = models.CharField(max_length=30, blank=False) last_price = serializers.CharField(required=False, allow_null=True, allow_blank=True) name = serializers.CharField(required=False, allow_null=True, allow_blank=True) # mainly for US stocks country = serializers.CharField(required=False, allow_null=True, allow_blank=True) sector = serializers.CharField(required=False, allow_null=True, allow_blank=True) industry = serializers.CharField(required=False, allow_null=True, allow_blank=True) # last_date_time = models.DateTimeField() class Meta: model = UsStockPriceModel fields = '__all__' def validate_last_price(self, value): if not value: return None try: return float(value) except ValueError: raise serializers.ValidationError('Valid integer is required') Not sure what is going wrong here.