Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with pytest. Queryset in my model
I have problem with pytest. In file tests.py I have got this code @pytest.mark.django_db def test_AddCompany(client): response = client.post('/add-company/', {'name': 'Test Company', 'description': 'test description', 'contact': 'testingmail@mail.pl', 'services': '', 'city': '', 'have_stationary': ''}) assert Company.objects.filter(name='Test') And I got this error E + where <QuerySet []> = <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.db.models.manager.Manager object at 0x000002ACF3AD6C70>>(name='Test') E + where <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.db.models.manager.Manager object at 0x000002ACF3AD6C70>> = <django.db.models.manager.Manager object at 0x0 00002ACF3AD6C70>.filter E + where <django.db.models.manager.Manager object at 0x000002ACF3AD6C70> = Company.objects services, city and have_stationary its foreign key. -
Django how make makemigrations and migrate when making changes at models
Whenever I make changes to the models (and subsequently to the views) when I do makemigrations or migration, I always run into problems. Sometimes running makemigrations django notices the changes, but then when I run the command migrate django writes that there are no changes to be made. Other times, dozens of exceptions are generated during makemigrations. Django writes that he does not find certain tables or certain fields but I read that the errors report the names before my changes. The only solution to all this is to delete content of: _pycache_ views.py sql3.db3 database Leave only models.py. At this point I can proceed with the makemigrations and migrate commands. The question: is there an easier way? What am I wrong? -
Event handlers fires multiple times when triggered [duplicate]
For some reasons unbeknownst to me, the events for elements I created dynamically fires multiple times (mulitplying itself by three each time). Those, I added manually fire only ones. As you can see, I have some console.log() which I use to track if the function was called multiple times or it was the event handler that fired multiple times. Also added event.stopPropagation(), still fires. here is my html code {% extends "mail/layout.html" %} {% load static %} {% block body %} <h2>{{ request.user.email }}</h2> <button class="btn btn-sm btn-outline-primary" id="inbox">Inbox</button> <button class="btn btn-sm btn-outline-primary" id="compose">Compose</button> <button class="btn btn-sm btn-outline-primary" id="sent">Sent</button> <button class="btn btn-sm btn-outline-primary" id="archived">Archived</button> <a class="btn btn-sm btn-outline-primary" href="{% url 'logout' %}">Log Out</a> <hr> <div id="emails-view"> </div> <div id="mail-template"> </div> <div id="compose-view"> <h3>New Email</h3> <form id="compose-form" action="#"> <div class="form-group"> From: <input disabled class="form-control" value="{{ request.user.email }}"> </div> <div class="form-group"> To: <input id="compose-recipients" class="form-control" placeholder="Recipient"> </div> <div class="form-group"> <input class="form-control" id="compose-subject" placeholder="Subject" value="HOMES"> </div> <p><textarea class="form-control" id="compose-body" placeholder="Body"></textarea></p> <p><input value="Send" type="submit" class="btn btn-primary" id='compose-submit'/></p> <!--<p><button class="btn btn-primary" id="compose-submit">Send</button></p>--> </form> </div> {% endblock %} {% block script %} <script src="{% static 'mail/index.js' %}" type='text/javascript'></script> {% endblock %} here is my Javascript file function check_parent(e){ return e.id || e.parentNode.id || e.parentNode.parentNode.id; } function … -
Prevent redirection in Django template form
Currently, my application is rendering an Django Template model form wherein some images are referred from another model. In order to delete and add images for the other model, I am handling it with a button with an overriden formaction that points to a DRF-based REST endpoint which deals with the images. However, whenever the service is invoked, it redirects the app to API response page. I would like to if it is possible to prevent redirection after formaction for button or input html elements -
Fetch with same path, sometimes failed
StackOverflow Got an issue with fetch in js + Django document.addEventListener("DOMContentLoaded", function () { // Use buttons to toggle between views document .querySelector("#inbox") .addEventListener("click", () => load_mailbox("inbox")); document .querySelector("#sent") .addEventListener("click", () => load_mailbox("sent")); document .querySelector("#archived") .addEventListener("click", () => load_mailbox("archive")); document.querySelector("#compose").addEventListener("click", compose_email); // By default, load the inbox load_mailbox("inbox"); console.log("again loaded INBOX____________") // check is the compose submitted document.querySelector("#compose-form").onsubmit = function () { fetch("/emails", { method: "POST", body: JSON.stringify({ recipients: document.querySelector("#compose-recipients").value, subject: document.querySelector("#compose-subject").value, body: document.querySelector("#compose-body").value, }), }) .then((response) => response.json()) .then((result) => { // Print result console.log(result); load_mailbox("sent"); }); }; }); Inbox, Sent and Archive they are my buttons, which I used to navigate when it clicked, neededd div will be shown, others will be hidden. function load_mailbox(mailbox) { // Show the mailbox and hide other views document.querySelector("#emails-view").style.display = "block"; document.querySelector("#compose-view").style.display = "none"; document.querySelector("#email-click-view").style.display = "none"; // Show the mailbox name document.querySelector("#emails-view").innerHTML = `<h3>${ mailbox.charAt(0).toUpperCase() + mailbox.slice(1) }</h3>`; if (mailbox === "inbox") { fetch_mail_by_folder("inbox") } if (mailbox === "sent") { fetch_mail_by_folder("sent") } if (mailbox === "archive") { fetch_mail_by_folder("archive") } } Load mailbox will call other function, which will fetch the data for the page function fetch_mail_by_folder(folder) { fetch(`/emails/${folder}`) .then((response) => response.json()) .then((emails) => { // Print emails emails.forEach(email => { const … -
Library for developing datagrid?
I am about to develope a data management webapplication and I need a datagrid like airtable. What is the fast way to build a datagrid like that? What tecknology framework is he best choise? Is it a ready to go product with the compoment I need? Please help 🙌 -
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 ?