Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get 1-4 Items via Django Rest Framework
I want to create awebapp where the user can choose between comparing 2,3 or 4 items of the database (Postgres). i already could create a view function to query a fixed amount of items. e.g query 3 Items View Function from myapp.models import Item @api_view(['GET']) def get_three_items(request, pk1, pk2, pk3): item1 = Item.objects.get(pk=pk1) item2 = Item.objects.get(pk=pk2) item3 = Item.objects.get(pk=pk3) data = [item1.serialize(), item2.serialize(), item3.serialize()] return Response(data) urls.py from django.urls import path from .views import get_three_items urlpatterns = [ path('items/<int:pk1>/<int:pk2>/<int:pk3>/', get_three_items), # ... ] But in my web app the user is able to choose between comparing 2,3 or 4 items. Is there a way to write the View Function and URL in a way, that it is dynamic or do i have to create a view for each compare capacity. So a view to compare 2 items. A view to compare 3 items and a view to compare 4 items? -
Django custom tags requires 3 arguments, 2 provided
#custom_tags.py def modulo(value, number,number2): mod = value % number if mod == number2: return True else: return False {% comment %} index.html {% endcomment %} {% for post in posts|slice:"1:"%} {% if post.id|modulo:4:0 %} <div class="post-entry-1"> <a href="{{post.slug}}"><img src="{{post.image.url}}" alt="" class="img-fluid"></a> <div class="post-meta"><span class="date">{{post.category}}</span> <span class="mx-1">&bullet;</span> <span>{{post.created_date}}</span></div> <h2><a href="single-post.html">{{ post.title }}</a></h2> </div> {% endif %} {% endfor %} ------------eror------- TemplateSyntaxError at /blog/ modulo requires 3 arguments, 2 provided When I mod the value with the variable number, I want to check the result with the variable number2 -
How to serve user uploaded media files in Django Production without any using anything else as a service?
What is the best way to serve media files in Production without using S3 or FTP? Whitenoise doesn't support it. I'll have to serve some ZIP files that'll be created from a view. I can compromise security aspects, will run it on RailwayApp. I had tried using Whitenoise but it doesn't support media files. -
How to pass model validations to ModelSerializer when using source parameter?
In my serializer I have my columns from model changed to different names because I need them that way in API. model: class User(models.Model): name = models.CharField(max_length=50, null=True) telephone_number = models.CharField(max_length=15, null=True, blank=True) serializer: class UserSerializer(serializers.ModelSerializer): phoneNumber = serializers.CharField(source='telephone_number') class Meta: model = User fields = ('name', 'telephone_number') But when I do it then serializer doesn't take into account validations given set in model. >>> serializer = UserSerializer() >>> print(repr(serializer)) UserSerializer(): name = CharField(allow_null=True, max_length=50, required=False) phoneNumber = CharField(source='telephone_number') <- no max_length here How to invoke these validations without need to duplicate them into serializer? (of course my models are considerably bigger that's why i'm asking) -
Watchman looking to opt/homebrew/root-state and can't access it
Im trying to run my Django server as I did lot of times before, but probably after update or so im receiving errors from watchman, specifically this one Watchman warning: opendir(/opt/homebrew/var/run/watchman/root-state) -> Permission denied. And its strange because from what I researched this folder should have restricted access. So I have two folders there, user-state and root-state Its still running server when im starting it, but throwing bunch of those errors in terminal so im just curios why its even watching in this dir. After deleting all watching paths its starts looking in this path again. -
Django ForeignKey to a model that might not exist
I want to set a foreign key in app1 to a model of app2 that is an optional dependency. To achieve loose coupling, i want app1 to work even if app2 is not installed, with that foreign key simply being deactivated. Is there a way to do this? (and is it a good idea?) # app1/models.py optional_field = models.ForeignKey( "app2.some_model", null=True, blank=True, on_delete=models.SET_NULL ) -
How to find what is the actual error in static? [closed]
I have included the following code in my Django project to display a background image, but I am encountering an error in the static part. I have already checked the STATIC_URL, STATIC_ROOT, and STATICFILES_DIRS settings and ensured that the about.jpg file is located in the correct directory. What else could be causing this error and how can I fix it?" <div class="home"> <div class="background_image" style="background-image:url({%static'images/about.jpg'%});" </div> </div> -
How to sort a queryset based on objects' foreign key by sorted method?
I'm happy with the instruction to do sorting: sorted(qs, key=lambda obj: obj.name.lower(), reverse=True) But as I need to sort the queryset by obj's foreign key's field. It looks invalid with: (Sort won't work! The order didn't change.) sorted(qs, key=lambda obj: obj.fkname.name.lower(), reverse=True) which fkname is the foreign key of the object. I don't want to do sorting like this: Course.objects.order_by("subject__name")[0].name # The course cls has a FK to Subject. Can this be possible? -
Djnago model 'signup' have the field 'username' but i got the error "signup given an unexcpected argument 'username' "signuo
i have a model signup in django which contains the fields username ,email,user but i got the error signup got an unexcpected argument "username" I tried to change the name of model and field but i got the same error -
Django Rest Framework Model Viewsets 'POST' method not appeared in ALLOW methods after explicitly allowing it
Fairly new to it but have after trying out many different solutions, I still get the following problem where the POST html form would not appear (and POST method not allowed) as seen below, all while using a root superuser model.py class Category(models.Model): category = models.CharField('category', max_length=100, null=False, blank=False, default="NA") def __str__(self) -> str: return self.category class Meta: verbose_name_plural = "categories" class Item(models.Model): name = models.CharField('name', max_length=64) slug = models.SlugField(max_length=64, null=True, blank=True) icon = models.ImageField(blank=True, upload_to ='uploads/') category = models.ForeignKey( Category, on_delete=models.CASCADE, default='Uncategorized') subcategory = models.CharField( max_length=255, null=True, blank=True) quantity = models.DecimalField( max_digits=9, decimal_places=2) suggested_value = models.DecimalField( max_digits=6, decimal_places=2, null=False) retail_value = models.DecimalField(max_digits=6, decimal_places=2,max_length=30) description = models.TextField('description', max_length=255, blank=True) created_at = models.DateTimeField(auto_now_add=True, db_index=True) tenant = models.TextField('tenant', default='shared') exclude = ('tenant') class Meta: # db_table = "storeItems_item" default_permissions = ('view','add', 'change', 'delete') ordering = ['name'] get_latest_by = 'created_at' def __str__(self): return self.name def get_absolute_url(self): return reverse( 'storeItems_item_detail', args=(), kwargs={'slug': self.slug}) def save(self, *args, **kwargs): # assign permission to item group = Group.objects.get(name=self.tenant) super(Item, self).save(*args, **kwargs) for perm in ['view_item', 'add_item','change_item']: assign_perm(perm, group, self) # Default retail value if not self.retail_value: self.retail_value = self.suggested_value() super().save(*args, **kwargs) Everything I've tried with configuring the viewset's permission: class StoreItemsViewSet( viewsets.ModelViewSet, PermissionListMixin, # viewsets.GenericViewSet, mixins.ListModelMixin, # … -
authenticate() takes from 0 to 1 positional arguments but 2 were given
I'm trying to submit this User model, but when I try to create a user, it throws me an error: authenticate() takes from 0 to 1 positional arguments, but 2 were given. While it throws this error, it successfully creates the user with no password when I check my admin How can I solve this problem? Models.py: class User(AbstractUser): username = models.CharField(max_length=70, unique=True) email = models.EmailField(unique=True) phone_number = models.CharField(max_length=15) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'phone_number', 'password'] def __str__(self): return "{}".format(self.email) Views.py: def create_user(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = form.save() authenticate(request, user) return redirect('Home') else: form = RegistrationForm() return render(request, 'register.html) Forms.py: class RegistrationForms(forms.Form): username = forms.CharField(label="Username", max_length=70, widget=forms.TextInput(attrs={'class':'form-control'})) first_name = forms.CharField(label="First Name", widget=forms.TextInput(attrs={'class':'form-control'})) last_name = forms.CharField(label="last Name", widget=forms.TextInput(attrs={'class':'form-control'})) email = forms.EmailField(label="School Email", widget=forms.EmailInput(attrs={'class':'form-control'})) phone_number = PhoneNumberField(label="School Phone Number", widget=forms.NumberInput(attrs={'class':'form-control'})) password = forms.CharField(label="Password", widget=forms.PasswordInput(attrs={'class':'form-control'})) repeat_password = forms.CharField(label="Repeat Password", widget=forms.PasswordInput(attrs={'class':'form-control'})) class Meta: model = User fields = ['username', 'password', 'email', 'first_name', 'last_name', 'phone_number', 'repeat_password'] -
Django upload many images to model field
I have project in django responsible for creating notes with optional adding images. Now I can add note with maximum one image. I want to allow user add as many images as want, but I don't know how. I tried using ArrayField in model field but it didn't worked. I want to be this way: when user click 'Add image' and explorer shows up he can choose more than one image. And then these images save to one model instance. For example if img field will be ArrayField in database will be: img = ['image1.jpg', 'image2.jpg', 'image3.jpg'], I don't want to create as many objects as there is images to upload. My model: class Note(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='note', null=True) title = models.CharField(max_length=200) note_text = models.TextField() add_date = models.DateTimeField('added date') img = models.ImageField(upload_to='images', blank=True) edit_dates = ArrayField( models.DateTimeField('edit dates', blank=True, null=True), default=list, ) def __str__(self): return self.title My form: class AddNewNote(forms.ModelForm): class Meta: model = Note fields = ['title', 'note_text', 'img', ] My view: class CreateNoteView(CreateView): model = Note template_name = 'notes/add_note.html' form_class = AddNewNote def get_success_url(self): return reverse('show', kwargs={'pk' : self.object.pk}) def form_valid(self, form): form.instance.add_date = timezone.now() form.instance.user = self.request.user return super(CreateNoteView, self).form_valid(form) and add_note.html: {% extends 'notes/base.html' … -
Django collectstatic erroring
I've got this collectstatic error since upgrading from Django 3.x to 4.y Traceback (most recent call last): File "manage.py", line 13, in <module> execute_from_command_line(sys.argv) File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 209, in handle collected = self.collect() File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 154, in collect raise processed File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/contrib/staticfiles/storage.py", line 338, in _post_process content = pattern.sub(converter, content) File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/contrib/staticfiles/storage.py", line 215, in converter hashed_url = self._url( File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/contrib/staticfiles/storage.py", line 152, in _url hashed_name = hashed_name_func(*args) File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/contrib/staticfiles/storage.py", line 388, in _stored_name cache_name = self.clean_name(self.hashed_name(name)) File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/contrib/staticfiles/storage.py", line 113, in hashed_name raise ValueError( ValueError: The file 'dist/vendor/bootstrap-select/js/i18n/defaults-ar_AR.js.map' could not be found with <core.storage.StaticStorage object at 0x7f7a3230e160>. I'm storing to S3 and here is my specific storage class class MediaStorage(S3Boto3Storage): """ This is our default storage backend for all media in the system. DEFAULT_FILE_STORAGE expects a class and not an instance """ def __init__(self, *args, **kwargs): kwargs.setdefault("file_overwrite", False) kwargs.setdefault("url_protocol", "https:") kwargs.setdefault("querystring_auth", False) kwargs.setdefault("location", get_storage_env("media")) kwargs.setdefault("default_acl", "public-read") kwargs.setdefault("object_parameters", {"CacheControl": "max-age=31536000"}) super(MediaStorage, self).__init__(*args, **kwargs) def _save_content(self, obj, content, parameters): """ We create a clone of the content file … -
Storing pdf / image or both files in database not in storage/folder in django
I want to store images and pdf files in the database directly and not in the folder storage, what field type should be given in models along with other information which will be stored in another table and files will be stored in another table of the database. and also how to retrieve those files and view file in later time. #django #fileupload tried looking for multiple resources which all were showing to store files in storage -
nothing happens after running python manage.py shell < script.py
This is my first time trying to run a script. I'm trying to hash previously stored plain text in my db. Anyway I created script.py file in my project folder it doesn't seem to do anything what am I missing? The command I'm running in my virtual env: python manage.py shell < script.py My script.py file: from django.contrib.auth.hashers import make_password from myapp.models import User def hash_existing_passwords(): for user in User.objects.all(): user.user_password = make_password(user.user_password) user.save() -
DJANGO i want but deafult image but i cant always error [closed]
DJANGO i want but deafult image but i cant always error i but in the top {% load static %} <div class="download-img"> <div> <h3>{{books.username}}</h3> <small>{{books.created|timesince}}</small><br><br> {% if books.image.url %} <img src="{{books.image.url}}"> {% else %} <img src="{% static 'images/genericBookCover.jpg %}"> {% endif %} </div> </div> enter image description here -
Kept getting redirected to login page after keying login details correctly
can someone help me? Even though I have keyed in the correct credentials, I kept getting redirected back to the login page instead of the index page. Everything appears to be working fine, am unable to find the root cause of the problem. Help is deeply appreciated. My view code def login_view(request): if request.method == 'POST': form = LoginForm(request.POST or None) if form.is_valid(): email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = authenticate(request, username=email, password=password) print('user:', user) print(password) if user is not None: login(request, user) print('1') return redirect('app:index') else: print('2') return JsonResponse({'success': False, 'message': 'Invalid email or password.'}) else: form = LoginForm() print('3') return render(request, 'login.html', {'form': form}) Terminal Output 3 1 3 -
Stripe configuration for saas application
I am creating a saas application using Django and handling payments using stripe. Here I have three types of pricing models. An admin could register any of the three plans. The admin could add multiple users to his team. Start-up: Free of cost supports up to 5 users. Have no time limit. Scale-up: supports up to 10 users. have monthly or yearly subscriptions. $1 per user per month. When the user number is 6 after the monthly period the charge will be 6*1 = $6 per month Premium: supports unlimited users. have monthly or yearly subscriptions. $2 per user per month. When the user number is 11 after the monthly period the charge will be 11*2 = $22 per month How can I configure these requirements into Stripe? I have created 3 products and created pricing for all of them, but I have no idea how can I handle the limit of the user. How can I charge the customer by the number of users in a team? -
how to link ipaddress to a name to allow connections when on the same router
So I making a small website with django, and I want my colleagues to be able to connect. We all will be using the same router, and although I can ask them to connect via the address I provide http://192.168.100.xxx on port 8000. I decided to make it easier by mapping the address to a name, so they can connect via http://my_server:8000. Although I am unsure on how to come about this. Whether to do it from the router settings, or my system settings. I've tried searching online on on how to do such, and most articles are come accross are very confusing. I would like someone to give a straightforwards approach to this. -
Can't send html template in google API
I am trying to send html template in google mail through python. I can send mail successfully but it is just text. For example when I send Hello world it will go as it is. I want to make the text bold. Here is my function for sending mail. `def send_email(subject: str, message: str, recipient: RecipientType): email = EmailMessage( subject=subject, body=message, from_email=FROM_EMAIL, to=[recipient.email], ) message = email.message() raw = base64.urlsafe_b64encode(message.as_bytes()).decode() binary_content = {'raw': raw, 'payload': {'mimeType': 'multipart/alternative'}} connection.users().messages().send(userId='me', body=binary_content).execute() ` I am using python and Google API. Thank you in advance. I tried different Mimetype but I am not so good with these things. -
AWX django.db.utils.OperationalError: could not translate host name "postgres" to address: Name or service not known
I have an AWX deployment using docker compose. The postgres database is having issues with dns name resolution. The issue started after I updated the docker-compose.yml to force the awx_web container to write some DNS IPs in /etc/resolv.conf. After that I ran: docker pull; docker compose up -d The containers were recreated, and I could no longer connect to the AWX web interface. I have tried stopping the containers, restarting them, reloading nginx and confirm it's running, recreating the containers with tweaked docker-compose.yml's, and I keep running into the server error issue. $ awx logs awx_web self.connect() File "/var/lib/awx/venv/awx/lib/python3.6/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/var/lib/awx/venv/awx/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/var/lib/awx/venv/awx/lib/python3.6/site-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not translate host name "postgres" to address: Name or service not known RESULT 2 OKREADY 2023-03-15 02:16:01,844 INFO exited: wsbroadcast (exit status 1; not expected) 2023-03-15 02:16:01,844 INFO exited: wsbroadcast (exit status 1; not expected) 2023-03-15 02:16:02,848 INFO spawned: 'wsbroadcast' with pid 7561 2023-03-15 02:16:02,848 INFO spawned: 'wsbroadcast' with pid 7561 2023-03-15 02:16:03,850 INFO success: wsbroadcast entered RUNNING state, process has stayed up for > than 1 seconds (startsecs) 2023-03-15 02:16:03,850 INFO … -
Django not working correctly with unit tests
Python 3.10 Django 4.0 MySQL backend in practice, but I guess during unit tests its using in memory SQLLite ModelA - primary model ModelB - ModelA contains a list of ModelB's The sequence of events happens like this: User posts to /endpoint ModelA gets inserted into DB with ModelB1, ModelB2, ModelB3 as child rows in my_method(): model_bs = list(model_a.model_bs.all()) model_bs contains b1, b2, b3 as expected. User posts to /endpoint again ModelA gets 3 new ModelB's inserted, ModelB4 - ModelB6 This is where things go haywire, but ONLY during the unit test. In my_method(), model_bs = list(model_a.model_bs.all()) model_bs STILL only contains b1, b2, b3 when it should have b1 - b6. If I look at ModelB.objects.all(), the in-memory DB has all 6 rows. Anybody seen this before? All 6 steps are happening within the context of a single unit test. If I try to do this against a real instance of MySQL, the second post does in fact get b1 - b6 as expected since it's a new actual instance of model_a (but representing the same database row). I don't really want to clear the cache or anything like that since the idea is that the parent model has already … -
Issue while trying to submit ajax form in django
Server Side Code @csrf_protect def Authenticate(request): if request.method == "POST": return JsonResponse({"success": False}) Form <form class="row" id="frmLogin"> {% csrf_token %} <input type="text" name="username" /> <input type="password" name="password" /> <button class="btn btn-primary">Submit</button> </form> JQuery $(document).ready(function() { $("form#frmLogin").validate({ rules: { "username": { "required": true }, "password": { "required": true } }, submitHandler: function(form) { $.post({ url: "/authenticate/", contentType: "application/json;charset=utf-8;", dataType: "json", data: JSON.stringify({ "username": $(form).find("[name='username']").val(), "password": $(form).find("[name='password']").val(), "csrfmiddlewaretoken": $(form).find("[name='csrfmiddlewaretoken']").val() }), async: true, success: function(response) { } }); } }); }); Error Message -
for DJANGO how can make only owner the post edit and delete
sorry for bad english im arabic and first im new here i wnat know how "DJANGO" how can make only owner the post edit and delete and THANK YOU `class Book(models.Model): username = models.ForeignKey(User , on_delete=models.CASCADE) title = models.CharField(max_length=40) descriptions = models.TextField(blank=True , null=True) image = models.ImageField(upload_to='books_pic' , blank=True , null=True , default='images/genericBookCover.jpg') bookauthor = models.CharField(max_length=18 , null=True , blank=True) downloadlink = models.URLField() created = models.DateTimeField(auto_now_add=timezone.now) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=False) slug = models.SlugField(null=True , blank=True)` `def book_edit(request , id): update = Book.objects.get(id=id) form = AddBookForm(instance=update) if request.method == 'POST': form = AddBookForm(request.POST or None , request.FILES or None , instance=update) if form.is_valid(): form.save() #return redirect('') context = {'form':form} return render(request , 'pages/edit_book.html' , context)` `def book_delete(request , id): delete = Book.objects.get(id=id) if request.method == 'POST': delete.delete() return redirect('/') context = {'delete':delete} return render(request , 'pages/delete_book.html' , context)` -
CSRF token seems to be getting in the way
CSRF token seems to be getting in the way I am writing django tests for my application, one of my views allows users to "like" other users posts. But the tests are failing, the issue seems to be that there is no CSRF token but I'm not sure if that's really it. POST data is not used by the view, it only uses the url data the only reason I'm saying this is because some other tests I wrote has similar problems and that solved it. But nothing I try is working here is my test: from django.test import TestCase, Client from django.utils import timezone from django.contrib.auth import get_user_model from django.contrib.auth.models import User from django.middleware.csrf import get_token from .views import update from .models import Post, Like --- some code ommited --- def test_like_view(self): # make a post p1 = Post.objects.create(title='title', body='body', published_date=timezone.now(), created_by=self.user) # get CSRF token response = self.client.get(f'/{p1.id}/update/') csrf_token = response.cookies['csrftoken'].value # send POST request with CSRF token response = self.client.post(f'/{p1.id}/like/', {'csrfmiddlewaretoken': csrf_token}) # check that the response status code is 302, indicating a redirect self.assertEqual(response.status_code, 302) # check that a Like object was created self.assertTrue(Like.objects.filter(post=p1).exists()) and here is the view: from django.shortcuts import render from django.http import …