Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Warnings in command prompt about notepad after installation Of python package
Why its showing this warning "(process:14700): GLib-GIO-WARNING **: 12:08:05.830: Unexpectedly, UWP app HaukeGtze.NotepadEditor_1.811.1.0_x64__6bk20wvc8rfx2' (AUMId HaukeGtze.NotepadEditor_6bk20wvc8rfx2!notepad') supports 182 extensions but has no verbs" I just installed weasyprint in python and GTK for 64 bit from there on its showing this error? Can anyone help me out of this? Thanks in advance.. -
While testing my Websocket Consumer a model object is not created (Django Channels)
I'm new in Django Channels and I'm trying to build a simple chat app. But when I'm trying to test my async Websocket Consumer I run into the following exception: chat.models.RoomModel.DoesNotExist: RoomModel matching query does not exist. It seems like the test room is not created. test.py file is the following: class ChatTest(TestCase): @sync_to_async def set_data(self): room = RoomModel.objects.create_room('Room1', 'room_password_123') room_slug = room.slug user = User.objects.create_user(username='User1', password='user_password_123') print(RoomModel.objects.all()) # querySet here contains the created room return room_slug, user async def test_my_consumer(self): room_slug, user = await self.set_data() application = URLRouter([ re_path(r'ws/chat/(?P<room_name>\w+)/$', ChatConsumer.as_asgi()), ]) communicator = WebsocketCommunicator(application, f'/ws/chat/{room_slug}/') communicator.scope['user'] = user connected, subprotocol = await communicator.connect() self.assertTrue(connected) await communicator.send_json_to({'message': 'hello'}) response = await communicator.receive_json_from() self.assertEqual('hello', response) await communicator.disconnect() My consumer.py file is the following: class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = f'chat_{self.room_name}' await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard(self.room_group_name, self.channel_name) async def receive(self, text_data): self.message = json.loads(text_data).get('message') data = {'type': 'chat_message'} data.update(await self.create_message()) await self.channel_layer.group_send(self.room_group_name, data) async def chat_message(self, event): await self.send(text_data=json.dumps({ 'message': event['message'], 'user': event['user'], 'timestamp': event['timestamp'] })) @database_sync_to_async def create_message(self): print(RoomModel.objects.all()) # qyerySet turns out to be empty here room = RoomModel.objects.get(slug=self.room_name) msg = room.messagemodel_set.create(text=self.message, user_name=self.scope['user']) return { 'message': msg.text, 'user': self.scope['user'].username, 'timestamp': … -
Update data with image in Django through Axios
I am trying to update the data with a field image. I followed this link https://stackoverflow.com/a/28036805/15320798 to successfully upload an image. But when I try to update the data without changing the image field, it throws the error Upload a valid image. The file you uploaded was either not an image or a corrupted image. The scenario is that I have to change other fields and keep the image field the same. Example Request Payload: { "name":"John" "age":18, "image:""http://localhost:8000/media/9154fb95-0f1.jpg" } and this is how I send the data from vue axios .put(url, data) .then((response) => { console.log("success") }) serializers.py class UserSerializer(serializers.ModelSerializer): image = Base64ImageField(max_length=None,use_url=True,) # this is from the link above class Meta: model = User fields = ( "name", "age", "image" ) Is there any way I can execute this? -
{ "detail": "CSRF Failed: CSRF token missing or incorrect." }
hello guys . I try to register a new Product in my app using DRF and Postman. when I send a request I get this error. the problem is just about my csrf_token. I'll be thankfull if you help me..... this is my view class ProductViewSet(viewsets.ModelViewSet): authentication_classes = (SessionAuthentication,TokenAuthentication) permission_classes = [IsAdminUser] queryset = ProductInfo.objects.all().order_by('-id') serializer_class = ProductSerializer filter_backends = (filters.SearchFilter,) search_fields = ['title','code','owner__username'] I don't have any problem for GET request. -
What's the reason of my drop down class doesn't iterate?
this is base html codes. I sent categories, products in views.py to base.html. they are defined in models.py as Category, Product as OnetoOne Relationship. <div class="btn-group"> {% for category in categories %} <button type="button" class="btn" id="BASE_SECOND_ADAPTERS"> <a href="{{category.get_absolute_url}}" class="btn" id="C_TITLE">{{category.title}}</a> </button> <button type="button"> <span class="sr-only">Toggle Dropdown</span> <div> {% for product in category.product_set.all %} <div class="button"> <a href="{{product.get_absolute_url}}">{{product.name}}</a> </div> {% endfor %} </div> </button> {% endfor %} </div> this is the problem. first, the href in products iteration doesn't work. When i delete the data-toggle="dropdown" it works. 1Cat - 1-2Pro, 1-1Pro 2Cat - 2Pro 3Cat - 3Pro But Iteration ended before 2Category. If i delete the drop down class, It work. How can i solve it? -
connection error between two devices: ImportError: libmariadb.so.3: cannot open shared object file: No such file or directory
I have two devices that I use as MySql server and Django server. My system, which works on my development device, becomes inoperable when it switches to other devices. Settings on 192.168.3.60: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'bildirdi_hurmalar', 'USER': 'gungelir_tirmalar', 'PASSWORD': 'EhuEhu_1793', 'HOST': '192.168.3.65', 'PORT': '3306', } } Apache2 and wsgi on mainside. Error when I run Migrate or runserver: (env) pi@raspberrypi:~/bilidrdi.com $ python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: libmariadb.so.3: cannot open shared object file: No such file or directory During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.7/importlib/__init__.py", line 127, … -
Django don't login after change password use Abstractuser
i custom user use abstractuser class User(AbstractUser): create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) name=models.CharField(max_length=50) phone=models.CharField(max_length=15) position=models.CharField(max_length=30) but when i change password user in adminpage i can't login with login function class LoginClass(View): def get(self,request): if not request.user.is_authenticated: return render(request, 'new_template/signin.html') else: return redirect('user:view_camera') def post(self,request): username1 = request.POST.get('username1') password1= request.POST.get('password1') my_user = authenticate(username=username1,password=password1) if my_user is None: return redirect('/') login(request, my_user) next_url = request.GET.get('next') if next_url is None: return redirect('user:view_camera') else: return redirect(next_url) -
Django data getting issue
Django giving different data to browser and swagger(or postman) it's in swagger(in postman too): But in browser getting wrong data: please any ideas -
How to render .astro files in django
I tried to create a Django web app since the web pages had heavy js files so it took a long time to load the page. To tackle this problem I tried to implement Astro to create a static webpage. But the problem here is that Django renders .astro files also as HTML.Like shown in this image How do I tell Django to render .astro as an Astro file -
Dynamically iterate over variables if it contains a url using Jinja
I have a collection of uploaded photos in Django admin photos URLs are stored in a Django app namely Listing, inside model.py class Listing(models.Model): photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) photo_5 = models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) photo_6 = models.ImageField(upload_to='photos/%Y/%m/%d/',blank=True) my code for views.py looks like def listing(request, listing_id): listing = get_object_or_404(Listing, pk=listing_id) context = { 'listing': listing } return render(request, 'listings/listing.html', context) now, inside my listing.html file I can check if a photo URL is available and then apply the design to show the photo as following {% if listing.photo_1 %} <div class="col-md-2"> <a href="{{ listing.photo_1.url }}" data-lightbox="home-images"> <img src="{{ listing.photo_1.url }}" alt="" class="img-fluid"> </a> </div> {% endif %} I can do it for all six photos but I want to do it dynamically like {% for i in range (1,7) %} {% if listing.photo_{{i}} %} <div class="col-md-2"> <a href="{{ listing.photo_{{i}}.url }}" data-lightbox="home-images"> <img src="{{ listing.photo_{{i}}.url }}" alt="" class="img-fluid"> </a> </div> {% endif %} {% endfor %} is there any way to do it? I tried to pass photos URLs inside the context dictionary as a list like def listing(request, listing_id): listing = get_object_or_404(Listing, pk=listing_id) context = { 'listing': listing 'photos': [listing.photo_1,listing.photo_2,listing.photo_3,listing.photo_4,listing.photo_5,listing.photo_6] } return render(request, 'listings/listing.html', context) … -
How do I use Django's CheckConstraint to restrict a variable at the database level?
I'm trying to write an application that receives incoming tickets for a small IT department. Currently these tickets come in through a webhook so I want to restrict what comes in at the database level. I want to restrict the status variable of the ticket to the choices described in the ticketStatus model but the database is still accepting values outside these choices. I've experimented with using CheckConstraint but can't quite get it to work. My code is as follows: class ticketStatus(models.TextChoices): Active = "Active" Acknowledged = "Acknowledged" Resolved = "Resolved" Unresolved = "Unresolved" class Ticket(models.Model): dateTimeRecieved = models.DateTimeField(default=timezone.now) deviceId = models.ForeignKey(Device, related_name="Device", on_delete=models.DO_NOTHING) issue = models.CharField(max_length=100) status = models.CharField(max_length=20, default="Active") def __str__(self): return f"Device {self.deviceId}: {self.issue}" class Meta: constraints = [ models.CheckConstraint( models.Q(status__in=ticketStatus.values) ), ] At the moment, I'm getting this error when I attempt the migration: TypeError: __init__() takes 1 positional argument but 2 were given I believe this is associated with models.Q(status__in=ticketStatus.values) I'm currently using Django version 3.2.4 -
Return pk of form after submission
I need to return the PK of a form after it is submitted so I can use it in a second form. Everything I find online about returning the PK is for a http redirect not storing it in a variable and working with it in the view view def createPostView(request): currentUser = request.user postForm = PostForm() if request.method == 'POST': postForm = PostForm(request.POST, request.FILES) if postForm.is_valid(): PostFormID = postForm.save(commit=False) PostFormID.author = request.user PostFormID.save() return #need to get pk from this form for f in request.FILES.getlist('images'): test = PostImagesForm(request.POST, request.FILES) if test.is_valid(): instance = test.save(commit=False) instance.post = #need to use pk here instance.images = f instance.save() return HttpResponseRedirect("/") return render(request, 'blog/post_form.html', {'postForm': postForm, 'PostImagesForm':PostImagesForm}) -
Cant display values in Django templates
I'm new to Django, I am trying to display a single book in a template(show.html) like <h1 class="text-center text-4xl py-5">{{book.title}}</h1> <img src="{{ book.thumbnailUrl }}" alt="" class="w-56"> <p>{{book.shortDescription}}</p> <p>{{book.longDescription}}</p> The view rendering the template is (trying to render a single book from JSON file by id) def show(request, id): with open('bookstore/books.json') as file: book_dict = json.load(file)['books'] book = [book for book in book_dict if book['id'] == id] context = {'book': book} return render(request, 'books/show.html', context) When debugging by printing {{ book }} in show.html it results in a list with a dictionary of a book [{'id': 1, 'title': 'Unlocking Android', 'isbn': '1933988673', 'pageCount': 416, 'publishedDate': {'$date': '2009-04-01T00:00:00.000-0700'},...}] Hence I think that's the problem when I try to access the title using dict syntax like({{ book. title}} ) But I can't seem to find a workaround. -
Django saves time data in UTC despite using localtime
In my settings file, I have : LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = True USE_TZ = True in my views: import datetime def some_function: print(datetime.datetime.now()) << prints my local time However, when using the same datetime.datetime.now() to store the current localtime into a DateTimeField, it gets converted in UTC. I understand that its a good things that it all gets converted into UTC when being stored into Database. Objective being, it will be easier for us to convert UTC to any localtime when we are using these stored values and rendering to the user. This last step, of converting UTC time to localtime, which I assume that django should do by default, is where I'm stuck at. the datetime values are still being rendered as UTC instead of my localtime despite using USE_TZ = True in my settings. -
How can I let my users send email from my django app?
I have a django app and users can create a profile and upload their contacts. Is there a way for me to allow them to send email using their email account but through the app? The use case would be that a user would like to send 50 emails to its contacts that are sent through his own email thought. As i write this, I feel this is not possible - lol -
How to query a Django queryset through a foreign key on another model?
I have the following models in my project: class Case(models.Model): ... class File(models.Model): class StatusType(models.TextChoices): ACTIVE = "ACTIVE", _("ACTIVE") DELETED = "DELETED", _("DELETED") case = models.ForeignKey(Case, on_delete=models.CASCADE, null=True) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) status = models.CharField( max_length=255, choices=StatusType.choices, default=StatusType.ACTIVE, ) Basically, in one of my views, I want to a get a list of all the cases where the following conditions are met through the File model: user = request.user status = "ACTIVE" How can I do this in a simple way? I can query for all the files first and then loop through them and add the cases to a list. Is that the best way to go about this problem? Thanks in advance for any help. -
AttributeError: 'User_Profile' object has no attribute '__name__'
Hello I hope everyone is having a good day, my goal is to get my forms.py to send the email form content to a different model into my Django database, from the default User model in Django to my custom-made User_Profile model. I believe if I can fix the error above that, my goal will be accomplished. In my forms.py file, I am importing a class from the model.py then using the function again in the forms.py, which is what is causing the error. I did my research on __ name__ with classes, and from what I understood, it has to do with using the same class two different times and it doesn't know which one to run or something. If someone could explain __name __ with classes better and help me fix the error, I would much much appreciate that. Here is my models.py class User_Profile(models.Model): user = models.OneToOneField(User, null = True, blank = True, on_delete = models.CASCADE) name = models.CharField(max_length = 200, null = True) phone = models.CharField(max_length = 200, null = True) email = models.CharField(max_length = 200, null = True) profile_image = models.ImageField(null = True, blank = True) data_created = models.DateTimeField(auto_now_add = True, null = True) def … -
How can i update the field of a model from another model field in django?
I have two models. DepartmentGoal with a field 'scores' and Task also with a field 'scores' and a foreign departmentgoal. What I want is; If I allocate scores to DepartmentGoal, scores allocated to Task should subtract from scores of DepartmentGoal which means Any number of instances of scores of Task when summed up should be equal to score of a single instance of DepartmentGoal. I just need a clue on how to implement this. This are the models class DepartmentGoal(models.Model): name = models.TextField(max_length=150, null=True) score = models.IntegerField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) def __str__(self): return self.name class Task(models.Model): name = models.CharField(max_length=300, null=True) departmentgoal = models.ForeignKey(DepartmentGoal, on_delete=models.CASCADE, related_name='departgoal', null=True, blank=True) score = models.IntegerField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) def __str__(self): return self.name Here the the forms class DepartmentGoalForm(ModelForm): class Meta: model = DepartmentGoal fields = ( ('name'), ('score'), ) class TaskForm(ModelForm): class Meta: model = Task fields = [ 'departmentgoal', 'name', 'score', ] -
Python Django: How to pass in variable with 'url' call inside of template
I want to be able to pass in a variable for this url function defined in my urls.py: path("edit/<str:title>", views.edit, name="edit"), From my html template, I did this: <a href="{% url 'encyclopedia:edit/{{ entry }}' %}">Edit Entry</a> The goal of this is so the user can click this hyperlink to edit some text within in a textarea box. For that I wanted to pass in the specific name of the page, e.g. HTML. That is what the "entry" variable is used for. However, because of this little bit of code 'encyclopedia:edit/{{ entry }}' I get an error: Here is the error: Reverse for 'edit/{{ entry }}' not found. 'edit/{{ entry }}' is not a valid view function or pattern name. I am fairly new to Django, but I know that I am using Django syntax incorrectly in this case. Usually I would be able to do this with a simple <a href="edit/{{ entry }}">Edit Entry</a> But will this pass in "entry" as a variable? -
Django - myfunc() got an unexpected keyword argument 'paramName'
I'm a front-end developer. trying to create a view in django for our app. inside my app I have created a file utils.py where I have a function which expects a record id to some stuff. In my views.py after importing when I call it I'm getting an error: myfunc() got an unexpected keyword argument 'paramName' calling the function like so: funcFromUtilsPy(myObj['id']) I have tried printing paramName inside the function and it's receiving the id. not what this error means and what's causing it. any suggestions ? -
Registration not working in django on Heroku
I have this weird situation where my term project has been deployed at heroku. It works fine except the database part. After searching it up, most of the suggestions were to make migrations. But when I try to migrate it gives me the following error: OSError: SavedModel file does not exist at: ./multiclass_verification_model/{saved_model.pbtxt|saved_model.pb} The code that loads the model is: model = tf.keras.models.load_model("./multiclass_verification_model") I have also tried: model = tf.keras.models.load_model("/multiclass_verification_model") and model = tf.keras.models.load_model("/app/multiclass_verification_model") it is not working. I am short on time as my project evaluation is drawing near. Any help would be really appreciated. Thank you. -
Django 'AnonymousUser' object is not iterable after added delete function in my views
I am getting this error if user isn't login and try to go admin page 'AnonymousUser' object is not iterable. I am getting this error after added delete function in my views: views.py def DeleteNotificaton(request,noti_id): user= request.user author = Blog.objects.filter(author=user) if user.is_authenticated and not author: Notifications.objects.filter(id=noti_id,receiver=user).delete() Notifications.objects.filter(id=noti_id,sender=user).delete() messages.add_message(request, messages.INFO, 'Notification deleted sucessfully.') return redirect('notifications:notify') elif user.is_authenticated and author: Notifications.objects.filter(id=noti_id,receiver=user).delete() messages.add_message(request, messages.INFO, 'Notification deleted sucessfully.') return redirect('notifications:notify_author') I also tried this: def DeleteNotificaton(request,noti_id): user= request.user if user.is_authenticated: author = Blog.objects.filter(author=user) if user.is_authenticated and not author: Notifications.objects.filter(id=noti_id,receiver=user).delete() Notifications.objects.filter(id=noti_id,sender=user).delete() messages.add_message(request, messages.INFO, 'Notification deleted sucessfully.') return redirect('notifications:notify') elif user.is_authenticated and author: Notifications.objects.filter(id=noti_id,receiver=user).delete() messages.add_message(request, messages.INFO, 'Notification deleted sucessfully.') return redirect('notifications:notify_author') getting this error The view notifications.views.DeleteNotificaton didn't return an HttpResponse object. It returned None instead. -
Weighted average from queryset - Django
How get the weighted average from queryset as quickly as possible. Is it possible without the use of loops. Below is an example. My models.py: class Product(models.Model): price = models.DecimalField(max_digits=15, decimal_places=2) weighted = models.IntegerField() day = models.IntegrField() In my database, I have the following values for day 1: Object ID I: Price=100, weighted=12, day=1 Object ID II: Price=50, weighted=1, day=1 Object ID III: Price=75, weighted=3, day=1 how to calculate the weighted average for day one? day_1_average_weighted = Product.objects.filter(day=1) ???how to get a weighted average - 71.88??? -
Django: Delete ForeignKey instance but keep some of its data on record (for Ecom)
Say you have 2 ecom related models: User and Order. On the Order, you want to keep the User's data because there's a transaction that occurred, and you'd most likely like to keep the customers info, however, you'd also like to allow the customer to delete their account should they choose. For example, the way I see it is something like: from django.contrib.auth import get_user_model from django.db import models class Order(models.Model): customer_email = models.EmailField() customer_first_name = models.CharField(max_length=50) customer_last_name = models.CharField(max_length=50) customer = models.ForeignKey(get_user_model(), on_delete=SET_NULL) def clean(self): if not self.customer_first_name: self.customer_first_name = self.customer.first_name if not self.customer_last_name: self.customer_last_name = self.customer.last_name if not self.customer_email: self.customer_email = self.customer.email def save(self, *args, **kwargs): self.full_clean() return super().save(*args, **kwargs) But that seems like a bunch of duplication. Is there a way to go about building that without duplication, or do you just have to live with writing the same fields from the User model but with different names? -
Trying to use a Model method in View Django
So I'm working on this project (an Inventory app). I have this model method I am trying to use in my View. I'm trying to call it in my view. But I'm always getting an error: 'QuerySet' object has no attribute 'get_quantities_sold' Here is my model: generate_ref_no = str(uuid.uuid1()) class Transaction(models.Model): business = models.ForeignKey(Business_Account, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True) amount = models.FloatField() productSold = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) quanties_of_product_sold = models.IntegerField() transaction_date = models.DateTimeField(auto_now_add=True) payment_method = models.CharField(choices=PAYMENT_METHOD, max_length=50) reference_num = models.CharField(max_length=50, editable=False, default=generate_ref_no) def __str__(self): return f'{self.customer} ' def get_quantities_sold(self,quantities_sold): return print(quantities_sold) My view: class TransactionView(generics.GenericAPIView): def post(self,request, business=None): serializer = TransactionSerializer(data=request.data) if serializer.is_valid(): serializer.save() getTransaction = Transaction.objects.filter(reference_num=serializer.data['reference_num']) getTransaction_serializer = TransactionSerializer(getTransaction, many=True) getTransaction.get_quantities_sold(serializer.data['quanties_of_product_sold ']) return Response(data=serializer.data, status=status.HTTP_201_CREATED) else: return Response(data=serializer.errors, status=status.HTTP_404_NOT_FOUND) I'm trying to call the 'get_quantities_sold' method from the Transaction model in my transaction view but I'm an error: QuerySet' object has no attribute 'get_quantities_sold'