Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
allow users view own objects in django admin
i want give access to users to admin panel i have a table : class Todo(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) title = models.CharField(max_length=100) date = models.DateTimeField() def __str__(self): return self.title i want just allow users to see,edit,add and delete their own objects in admin panel not others. i wrote this: class TodoAdmin(admin.ModelAdmin): def queryset(self, request): queryset = super(TodoAdmin, self).queryset(request) queryset = queryset.filter(user = request.user) return queryset but didnt work. how can i do that? -
Npm server not available after docker compose
I'm fairly new to docker. I was trying to separate my web app on modules for backend (django), frontend (react) and with some postgres db. Here is my docker-compose.yml : version: "3.8" services: db: image: postgres container_name: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres volumes: - ./private/posgtesql/data/data:/var/lib/postgresql/data app: build: . container_name: app working_dir: /app/label_it command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - "8000:8000" depends_on: - db front: build: context: ./label_it dockerfile: Dockerfile container_name: front command: npm run dev working_dir: /app/label_it/front volumes: - ./label_it/front:/app/label_it/front - ./label_it/front/node-modules:/app/./label_it/front/node_modules ports: - "8001:8000" depends_on: - app Django side runs like dream, browsing 127.0.0.1:8000 responses with server site. BUT. There is nothing on 127.0.0.1:8001. Correct me if I'm wrong, but I should be getting both servers for django AND for react on respecting ports?? Searched whole internet looking for solution. All I found was to check if node server actually runs on 0.0.0.0:8001 and it does according to : CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES baa18d3bfa73 labeling-lab-platform_front "docker-entrypoint.s…" 24 minutes ago Up 24 minutes 3000/tcp, 0.0.0.0:8001->8000/tcp front 6a76ba3a901b labeling-lab-platform_app "python manage.py ru…" About an hour ago Up 24 minutes 0.0.0.0:8000->8000/tcp app c0d1d27ed930 postgres "docker-entrypoint.s…" About an hour ago Up 24 minutes … -
Django POST-test for registering user
I want to test a user registering view in Django. The following test def test_view_register_redirects_to_homepage(self): response = self.client.post(reverse('register'), {'username': 'normal@user.com', 'password1': '3Zu!!44l', 'password2': '3Zu!44l'}) self.assertRedirects(response, '/') returns the following error message: AssertionError: 200!=302 Response didn't redirect as expected: Response code was 200 (expected 302). However, if I actually run the server, I see that it should work, hence, I'll guess there is something wrong with my test. My view looks like this def registerView(request): if request.method == "GET": return render( request, "accounts/register.html", {"form": CustomUserCreationForm} ) elif request.method == "POST": form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('/') return render(request, 'accounts/register.html', {'form': form}) whereas my form looks like class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = CustomUser fields = ('email',) and my custom user model looks like class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email Any help would be appreciated. P.S: I already tried to use 'email': instead of 'username': in the test code but the result stays the same. -
Django UniqueConstraint usecase
I have the model users and Address with the Address model containing the user as a Foreign key. Is it possible to handle this use case with constraints that in case of multiple users addresses a user can have one default address? Here is a sample code. Thank you. class User(models.Model): name = models.CharField(max_length=10) class Address(models.Model): address = models.CharField(max_length=10) active=models.BooleanField(default=False) user = models.ForeignKey( User, blank=False, null=False, related_name="user_address", on_delete=models.CASCADE) class Meta: constraints = [ models.UniqueConstraint(fields=['user', 'active'], condition=models.Q(active=True), name='user default address.') ] -
My model's field are not showing in admin panels
My models are not showing in admin panel. My models.py class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE), product = models.ForeignKey(Product, on_delete=models.CASCADE), quantity = models.PositiveIntegerField(default=1), def __str__(self): return str(self.id) admin.py: @admin.register(Cart) class CartModelAdmin(admin.ModelAdmin): list_display = ['id', 'user', 'product', 'quantity'] I had also tried this: admin.site.register(Cart) -
HINT: No operator matches the given name and argument types. You might need to add explicit type casts. in Django
I'm wondering why this error display and I've been using Postgresql and I have been observed this error occurs when I use IntegerField on my models like this one b2_sacnumber_id = models.IntegerField(blank=True, null=True). Is there any solution to get the value even I used IntergerFiled in my models? Error LINE 1: ...sac_forms" WHERE "b2_sac_forms"."b2_sacnumber_id" IN (31718,... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. query views.py sample = ['31718','47060'] Sac_forms = list(B2SacForms.objects.using('matchy_data').values_list('b2_id', flat=True).filter(b2_sacnumber_id__in=sample)) What I tried changing the value sample like this one sample = ['31718','47060'] or sample = ["31718","47060"] and even I tried sample = [31718,47060] but still the error occurs -
Why django_migrations table is created even though router does not allow migrations?
I have 'default' and 'secondary' databases. Why, even though it is stated: makemigrations always creates migrations for model changes, but if allow_migrate() returns False, any migration operations for the model_name will be silently skipped when running migrate on the db. Changing the behavior of allow_migrate() for models that already have migrations may result in broken foreign keys, extra tables, or missing tables. When makemigrations verifies the migration history, it skips databases where no app is allowed to migrate. when running ./manage.py migrate --database=secondary I receive all the migrations listed as OK and django_migrations table existing in the 'secondary' database, instead of no migrations and no trace for them. Is it a Django design decision or I messed up the routing? class PrimaryRouter: """Primary router allowing ORM operations only on default database""" # NOTE: https://docs.djangoproject.com/en/3.1/topics/db/multi-db/#an-example def db_for_read(self, model, **hints): return 'default' def db_for_write(self, model, **hints): return 'default' def allow_relation(self, obj1, obj2, **hints): """ Relations between objects are allowed if both objects are in the primary/replica pool. """ db_set = {'default'} if obj1._state.db in db_set and obj2._state.db in db_set: return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ All non-auth models end up in this pool. """ return db == … -
I want to save the current user when it delete a record in django
Suppose i have a DeleteView in django which succesfully delete the particular record but i also want to save which user delete the record for security purpose. I can save current user in CreateView,UpdateView but i don't know how to record current user when it delete a particular record. class PostDelete(DeleteView): model = Post template_name = 'post/confirm_delete.html' success_url = reverse_lazy('post-delete') Thanks -
Run django server in single thread only for one single url endpoint
By default django runserver runs in multiple thread, to stop multithreading there is an option for --nothreading, but by using this all requests are handled in a single thread which impacts in server performance. I need to run an selected url endpoint with single thread and all other endpoints can execute in parallel with multiple threads. My main motive is to handle multiple request within this endpoint in a sequence. -
Django (IIS) deployed, logging issue
I deployed django app on IIS, however my logging code that was working perfectly on local host, caused server 500 error... Can I get any help please? LOGGING = { 'version': 1, 'loggers': { 'django': { 'handlers': ['debuglog'], 'level': 'DEBUG' }, 'django.server': { 'handlers': ['errorlog'], 'level': 'ERROR' } }, 'handlers': { 'debuglog': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': './logs/debug.log', 'formatter': 'simple', }, 'errorlog': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': './logs/error.log', 'formatter': 'simple', } }, 'formatters': { 'simple': { 'format': '{levelname} {message}', 'style': '{', } } } Maybe IIS does not allow django to create log files and it needs permission to do so? If this is the case, how would I do that? -
How to remove duplicate options from a dropdown menu in html?
I have an html code, where I have a dropdown menu whose values all come from reading a column on a database (in Django). The dropdown menu has several redundancies, I would like to remove those duplicate options. Here's the html code part that reads from the database: And here's the script that should eliminate the duplicates -
How to send image as part of email body in django
I am building a portal for sending dynamic emails. Part of the form is an image field which the user can upload an image which I would like to be rendered in the image body, not as an attachment after the form is filled out. This is my code: views.py def emailView(request): if request.method == 'POST': form = ContactForm(request.POST, request.FILES) if form.is_valid(): form.save() name = form.cleaned_data['name'] subject = form.cleaned_data['subject'] image = form.cleaned_data['image'] message = form.cleaned_data['message'] recipient = form.cleaned_data['recipient'] image_url = Email.objects.all().last() domain = request.get_host() final_image = str(domain) + str(image_url.image.url) msg = loader.render_to_string( 'email_portal/email.html', { 'name': name, 'subject': subject, 'domain' : domain, 'final_image' : final_image, 'image_url': image_url, 'message': message, } ) try: send_mail(subject, name, message, [recipient] , fail_silently=True, html_message=msg,) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('/') else: form = ContactForm(request.POST, request.FILES) return render(request, "email_portal/index.html", {'form': form}) email.html <h5>{{ final_image }}</h5> #missing forward slash <a href="{{ domain }}/{{ image_url.image.url }}">My link</a> #missing forward slash <tr> <td background="{{ final_image }}</td> </tr> I have tried concatenating the host and the file path but for some reason, in the email body it's structured correctly but I can't render it as a background image and when I try to click it a forward slash is … -
Login django automatically with provided http link with username and password
User gets an email with http link to django. I want to provide the username and password in the link so that the user automatically logges in. http://www.test.com/username=testusername%password=testpassword Is this possible ? -
'NoneType' object has no attribute 'username'? What should i do?
I am extending User model of Django by following model models.py class Profile(models.Model): user = models.OneToOneField(User, null=False, on_delete = models.CASCADE) First_name = models.CharField(max_length = 128, null = True) Last_name = models.CharField(max_length = 128, null = True) email = models.CharField(max_length = 200, null = True) phone = models.CharField(max_length = 200, null = True) mod_date = models.DateTimeField(auto_now_add = True, null = True) profile_pic = models.ImageField(null = True, blank = True) def __str__(self): return self.user.username views.py def userprofile(request): form = Profile() if request.method == 'POST': form = Profile(request.POST) if form.is_valid(): form.save() context = {'form':form} return render(request, 'cs14/profile.html', context) forms.py class Profile(ModelForm): class Meta: model = Profile fields = ["First_name","Last_name","email", "phone"] When I try to go profile page, it happened error AttributeError at /profile/ 'NoneType' object has no attribute 'username' What is going wrong? -
How to store image file or file temporary using python or django rest_framework without saving in the database? I am new to Django
How to store image file or file temporary using python or django rest_framework without saving in the database? In dajngo rest_framework I did these things in a function based view. temp_file = request.FILES['document_file'] Then, how I store this file temporary without saving in the database? -
module 'hello_world' not found while running the manage.py runserver in django
My site is hosted at centos 7, lamp stack, whm/cpanel. I created a virtual environment mp_env and installed python3.7 and Django in mp_env. This mp_env is created in the same folder where we have public_html folder for main site. In this mp_env folder we have bin and lib. Python3.7 is installed this lib folder and Django was installed in site-packages of this lib. No. I did not do that intentionally. I just installed python and Django in mp-env. They automatically found places. Then I created a project myproject. I could test it with ./manage.py runserver 0.0.0.0:8000. I could change the database to mysql, create users and login to admin from web browser. It was working fine.The project folder is outsite the mp_env. Then I created an app hello_word inside the project directory myproject using this example at https://realpython.com/get-started-with-django-1/ I have followed the steps mentioned there and used everything word by word. Now when I try ./manage.py runserver 0.0.0.0:8000, it gives error - module 'hello_world' could not be found. -
Variable number of inputs with Django
Currently I'm making a platform based on chamilo and I'm stuck because a template´s form for tests. The reason is becasuse I have to adquire de data from the form and organized to send througth the chamilo api rest. Currently This form is made of 6 static hidden inputs, but the real problem is the other inputs that are generate in function of the number of questions. In the forms.py file I defined a class for this form but only with 6 inputs but I don´t know how to handle the variable inputs from the tests answers because the tests have different number of questions and answers class Ejercicios(forms.Form): c_id = forms.CharField() lp_id = forms.CharField() item_id = forms.CharField() item_viewId = forms.CharField() exe_id = forms.CharField() time = forms.CharField() My class in forms.py look like this, how can I add different number of extra forms dynamically? -
'dict' object has no attribute 'coupon' ecommerce/store/views.py, line 254, in add_coupon
I have this e-commerce website I'm creating with django3. and I am getting this problem.AttributeError at /add-coupon/ 'dict' object has no attribute 'coupon' if someone can help please!!! my views def get_coupon(request, code): try: coupon = Coupon.objects.get(code = code) return coupon except ObjectDoesNotExist: messages.info(request, 'This coupon does not exist') return redirect('checkout') def add_coupon(request): data = cartData(request) if request.method == "POST": form = CouponForm(request.POST or None) if form.is_valid(): try: code = form.cleaned_data.get('code') order = data['order'] order.coupon = get_coupon(request, code) order.save() messages.success(request, 'Successfully added coupon!') return redirect('checkout') except ObjectDoesNotExist: messages.info(request, 'You do not have an active order') return redirect('checkout') return redirect('checkout') my guest order function > `def guestOrder(request, data): name = data['form']['name'] email = data['form']['email'] cookieData = cookieCart(request) items = cookieData['items'] user, created = User.objects.get_or_create( username = name, email=email, ) #user.name = name user.save() order = Order.objects.create( user=user, complete=False, coupon=None, #todelete ) for item in items: product = Product.objects.get(id=item['id']) orderItem = OrderItem.objects.create( product=product, order=order, quantity=item['quantity'], ) return user, order -
Testing coroutine function in async web socket consumers using channels
I am writing test cases for an Async WebSocket Consumer using the django channels. I want to mock a coroutine which I have defined in the connect method of my WebSocketConsumer. Consumer.py class ExampleTestConsumer(AsyncWebSocketConsumer): async def connect(self): await function_to_be_tested(args) await self.accept() Test case class TestExampleTestConsumer: async def test can_connect_to_server(self,settings): communicator = WebsocketCommunicator( application=application, path="/ws/example-test/1", ) connected, _ = await communicator.connect() assert connected is True await communicator.disconnect() I want the mocking of function_to_be_tested in this test case for this test case to work . Any suggestions ? -
How to perform multiple table join with Django?
I have a table like this: ID Parent_ID Name Geo 1 Null City A ABC1 12 1 District 1 ABC002 123 12 Ward 1 ABC002003 2 Null City B XYZ2 25 2 District 5 XYZ004 251 25 Ward 4 XYZ002006 Normally, I got the ID of the ward (third in the hierarchical). I need to to do query to get the GEO of the city (first in the herarchical). In query (PostgreSQL), I would do something like this : SELECT l1.Geo FROM routing.r_location l1 JOIN routing.r_location l2 ON l1.ID= l2.Parent_ID JOIN routing.r_location l3 ON l2.ID= l3.Parent_ID WHERE l3.ID= '123' Since, I am beginner with Django, I literally dont know how to do complex join table like this. Please help -
Django how to log loge page with id
I am new to Django and tried existing answers but did not work for me. I would appreciate your help! I can easily get to the general page when I enter the site, but how do I go to my profile when I log in? def login(request, pk=0): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) try: remember = request.POST['remember_me'] if remember: settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = False except: is_private = False settings.SESSION_EXPIRE_AT_BROWSER_CLOSE = True if user is not None: auth.login(request, user) return redirect('/') else: messages.info(request, 'invalid credentials') return redirect('login') else: return render(request, 'registration/login.html') urls.py path('profile/<int:pk>/', views.profiles, name='profile'), -
Only friends posts are not showing
I am building a BlogPost Webapp, AND i am stuck on an Error. views.py def friends_posts(request,user_id): posts = Post.objects.filter(post_owner=user_id) profiles = get_object_or_404(Profile,user_id=user_id) p = request.user.profile you = p.user friends = p.friends.all() context = {'posts':posts,'profiles':profiles,'friends':friends} return render(request, 'friends_posts.html', context) urls.py path('friends_posts/<int:user_id>/',views.friends_posts,name='friends_posts'), friends_posts.html {% for user_p in friends %} {{ user_p.friends.posts.all }} {% endfor %} The Problem friends_posts page is not showing Friends post. It is showing all the information of friends but NOT showing the posts of friends. What i am trying to do I am trying to show all the posts of friends of request.user. I don't know what to do. Any help would be appreciated. Thank You in Advance. -
Pytest django url's tests
I saw some people writing url's test like this: def test_sample_url(): path = reverse('url_name', kwargs={'pk': 1}) assert resolve(path).view_name == 'url_name' As for me this test is not checking anything, because if I place 'url_name' in second line then in third it is obviously going to be equal to it. Am I wrong or missing something? -
How to hide certain json data from passing through if it doesn't meet a condition in Django rest framework?
Hello all I want to hide certain json data from passing through if it doesn't meet a condition in django rest framework, like I have a comment model and serializer, and I don't want the replies to pass through as comments since I have another field for replies which is nested along with the respective comments. These are the serializers: class CommentCreateSerializer(serializers.ModelSerializer): content = serializers.CharField() reply_id = serializers.PrimaryKeyRelatedField(source='reply',queryset=Comment.objects.all(), write_only=True, required=False) user = serializers.ReadOnlyField(source="user.username") class Meta: model = Comment fields = ['id', 'user', 'content', 'reply_id', 'timestamp'] class CommentSerializer(serializers.ModelSerializer): content = serializers.CharField() reply_id = serializers.PrimaryKeyRelatedField(source='reply',queryset=Comment.objects.all(), required=False) user = serializers.ReadOnlyField(source="user.username") replies = CommentCreateSerializer(many=True, read_only=True) class Meta: model = Comment fields = ['id', 'user', 'content', 'replies', 'reply_id', 'timestamp'] This is the json response: "count": 5, "next": null, "previous": null, "results": [ { "id": 2, "user": "testuser2", "content": "comment test!", "replies": [ { "id": 3, "user": "testuser3", "content": "ding", "timestamp": "2021-02-09T15:29:38.230933+01:00" } ], "reply_id": null, "timestamp": "2021-02-09T15:24:11.072502+01:00" }, { "id": 6, "user": "testuser2", "content": "Testing again", "replies": [], "reply_id": null, "timestamp": "2021-02-09T17:33:59.227425+01:00" }, { "id": 5, "user": "testuser2", "content": "Testing", "replies": [], "reply_id": null, "timestamp": "2021-02-09T17:28:41.992143+01:00" }, { "id": 3, "user": "testuser3", "content": "ding", "replies": [], "reply_id": 2, "timestamp": "2021-02-09T15:29:38.230933+01:00" }, { "id": 4, "user": … -
Strange error NameError: name '_mysql' is not defined on VSCode
I'm trying to using mysqlclient==2.0.3 for Django==1.11.17 and I am receiving this error when trying to start python manage.py runserver. The error is really strange because on macOS's terminal the commands works and everything is fine while the error appears only when using the same command from VSCode shell. In both I'm using zsh