Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django For Backend, Frontend Or Both
Please can Django be used to create a full functioning web application in Backend, Frontend or both and if so, can anyone suggest sites to learn on, a tutorial or complete web application course on Django or smth relating to how to code using Django. Thank You -
Image update issue in drf using put method
I am using Django rest framework, I have a issue regarding update my html data with image field using put method. Everthing is fine in response using postman but when i use ajax then it gives me following error in console. PLease help to resolve this issue. I want to update my data with image using put method only but above error interrupt my work. Please help me to resolve my issue I want to update my data with image using put method only but above error interrupt my work. Please help me to resolve my issue My views,py file: @api_view(['PUT']) # @csrf_exempt @authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def update_blog(request, id): try: blog = Blog.objects.get(id=id) except Blog.DoesNotExist: return Response(status=404) if blog.user_id != request.user.id: return Response({'response':'You do not have permission to update that'}) if request.method == 'PUT': serializer = AddBlogSerializer(blog, context={'request': request}, data=request.data) if serializer.is_valid(): serializer.save() data = {'result':'success', 'message':'Blog post updated successfully'} return Response(data=data, status=200) if not serializer.is_valid(): data = { 'result': 'error', 'message':serializer.errors} return Response(data=data) My response data is fine in views.py file My bootstrap html modal <!-- Modal --> <div class="modal fade" id="exampleModal1" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Update Blog</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" … -
Using proxy model as a signal sender
I have a proxy model. class ProxyModel(ParentModel): objects = ProxyModelManager() class Meta: proxy = True I'm trying to define my proxy model as a sender. @receiver(post_save, sender=core_models.ProxyModel) def test_receiver(sender, instance, **kwargs): print("test receiver") But the function is not called after the model is saved. Is it possible to define proxy model as sender? If so how can I do ? Thanks. -
my Django forms not working and also not submitting
I am not understanding why my forms not submitting. It seems to me everything correct in my code. Where I am doing mistake: views.py: projectfroms = CustomerProjectFroms(request.POST or None) if request.method == "POST": if projectfroms.is_valid(): projectfroms.instance.user = request.user messages.add_message(request, messages.INFO,'You project submitted sucessfully') projectfroms.save() return redirect('members:user-profile-private') else: messages.add_message(request, messages.INFO,"You project didn't submitted sucessfully") else: projectfroms = CustomerProjectFroms() I am getting this message "You project didn't submitted sucessfully" which confirm me my forms not submitting and I also rechecked from admin panel. models.py: class CustomerProject(models.Model): user = models.ForeignKey(UserManagement,on_delete=models.CASCADE) project_title = models.CharField(max_length=2000,blank=True,null=True) project_description = models.TextField(blank=True,null=True) froms.py class CustomerProjectFroms(forms.ModelForm): class Meta: model = CustomerProject fields = ['project_title','project_description'] -
Why do some images have the little magnifying glass?
I added an image to a "rich text" block of my website, but it displays with a little magnifying glass in the corner that allows you to see the image full size. I don't want this. I've looked at other images on the same site that don't have the little magnifying glass, to try to figure out what I did differently, but I can't figure it out. Please help. -
This is an hard one: allow users to send email through their own gmail without in a scalable way on django
This is an hard one I am making a django application to help people assemble construction workers teams. The app works as follow (more or less): A user sign up and upload all it's contacts. Each contact has an emails, a job title and a preference (how much the user like to work with this person). The user create a job element and select all the positions he needs to fill for the job (I need 2 carpenters, 1 cement guy...). The app start sending out email to the users' contact that have the right title starting by the one with the highest preference to check if they are available and interested for the job. If the person it's interested, they click on an link in the email and the position is marked as filled. If the person it's not interested, they click on another link and the app reach out to the next contact in line. I set up the whole app but I am having some troubles with how to send emails. I initially though about using Gmail API but I am now realizing that doing requires that every user goes into Google Api Console, download their credentials … -
How to create multiple instances of a model with factoryboy in django?
How do I create multiple instances of this Resource? When I try to do it, I get the same instance created. I do tend to end up with it creating multiple users, but only one Resource. Here is the factory declaration class ResourceFactory(DjangoModelFactory): class Meta: model = Resource client = factory.SubFactory( ClientFactory, ) user = factory.SubFactory( UserFactory, ) start_date = Faker("date_time") end_date = None department = Faker("sentence", nb_words=2) title = Faker("sentence", nb_words=4) custom_data_field = {"fake": "data"} This is roughly how I have been trying to do things. I want all resources associated with the same client. At this point, I got the client from the database, because I was getting random errors, and that seemed to fix those errors, at least. client = ClientFactory() db_client = Client.objects.get(id=client.id) resources = [ResourceFactory(client=db_client) for i in range(5)] if I run len(Resource.objects.all()) at this point, it comes back as 1. How do I create 5 separate resources in the database, all associated with the same client? -
Bootstrap / Django: recommended way to render two cards side-by-side (with responsiveness)
I have the following index.html page that leverages Django templates: {% extends "layout.html" %} {% block body %} {% for entry in entries %} <div class="card h-100 mb-3" style="max-width: 540px;"> <a href="{% url 'entry' entry.id %}"> <img class="card-img-top" src="{{ entry.image.url }}" alt="{{ entry.title }}"> </a> <div class="card-body"> <h5 class="card-title">{{ entry.title }}</h5> <p class="card-text">{{ entry.description }}</p> {% endif %} </div> </div> {% empty %} No content found. {% endfor %} {% endblock %} Currently, the Bootstrap cards render in a single column (one on top of the other), and they're left-justified. What is the best way to render cards such that there are two cards side-by-side (and responsive to become a single column if the screen becomes narrow)? Thanks in advance! -
Why is the checkbox not being saved as checked? (Python, Django, HTML)
I was following this tutorial by Tech with Tim, but after adding the code from the video, my checkboxes wont work. My code: views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .models import Item, ToDoList from .forms import CreateNewList # Create your views here. def index(response): return HttpResponse("<h1>Hello, world!</h1>") def item_by_id(id): item = Item.objects.get(pk=id) return HttpResponse(f"Item: {item.title}, published on {item.datetime_found}") def home(response): return render(response, "myapp/home.html", {}) def base(response): return render(response, "myapp/base.html", {}) def itemlist(response, list_id): ls = ToDoList.objects.get(id=list_id) if response.method == "POST": print(response.POST) # SAVING CHECK-BUTTONS if response.POST.get("save"): for item in ls.listitem_set.all(): if response.POST.get("c" + str(item.id)) == "clicked": item.complete = True else: item.complete = False item.save() # ADDING ITEM TO LIST elif response.POST.get("newListItem"): txt = response.POST.get("new") if len(txt) > 2: ls.listitem_set.create(text=txt, complete=False) else: print("Invalid") return render(response, "myapp/itemlist.html", {"ls": ls}) def create(response): if response.method == "POST": form = CreateNewList(response.POST) # Takes POST and uses data for form if form.is_valid(): # is_valid() checks class-fields for valid input n = form.cleaned_data["name"] # Clean and un-enc data, specify field "name" t = ToDoList(name=n) # Use data to create new ToDoList t.save() return HttpResponseRedirect("itemlist/%i" % t.id) # Redirect to page that shows the list else: form = CreateNewList() return render(response, "myapp/create.html", {"form": … -
Python Django - PostgresSQL Database Awith Amazon RDS Shuts Down After pgAdmin app is closed
I am working on a Django project right now and want to use Postgres for my database. I am somewhat confused on how sending data to the database (hosted on Amazon RDS) works. I have it currently set for inbound rules as my IP, as most articles say to do. When I eventually move to production, I'd imagine these inbound rules don't work. What rules should I use so that users can access the data in the database? -
AttributeError: 'IsInvited' object has no attribute 'request'
I have a modelviewset like this: class MeetingViewSet(viewsets.ModelViewSet): queryset = Meeting.objects.all() serializer_class = MeetingSerializer permission_classes =[IsAuthenticated & IsInvited | IsOwner] and permissions: class IsInvited(BasePermission): message = 'you must have been invited to see this meeting' def has_object_permission(self, object, request, view): if self.request.method == 'GET' and object.is_invited(self.request.user): return True return False class IsOwner(BasePermission): def has_permission(self, request, view): return request.user and request.user.is_authenticated def has_object_permission(self, object, request, view): if self.request.user == object.host: return True return False but i got this error : Internal Server Error: /api/meetings/1/ Traceback (most recent call last): File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/mixins.py", line 54, in retrieve instance = self.get_object() File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/generics.py", line 99, in get_object self.check_object_permissions(self.request, obj) File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/views.py", line 345, in check_object_permissions if not permission.has_object_permission(request, self, obj): File "/home/admin1/envs/myvenv/lib/python3.8/site-packages/rest_framework/permissions.py", line 81, in has_object_permission self.op1.has_object_permission(request, view, obj) or … -
Can i implement django rest api with just jquery and ajax in production?
I am quite new to django rest framework. Is it appropriate if I implement Django rest framework without react front-end or anything like that but just with simple jquery UI ajax. And can I use it in production. It would be really nice to have your expert opinion. -
_maybe_load_initial_epoch_from_ckpt() takes 2 positional arguments but 3 were given? Encountered this error while deploying CNN model with Django?
I've trained a CNN model with an image dataset, saved the model with the name classifier.h5. Now, I need to load this model in my Django web application to make predictions. I've implemented code in the following way, but encountering an error _maybe_load_initial_epoch_from_ckpt() takes 2 positional arguments but 3 were given. What could cause this error and how to resolve it? My CNN Model EPOCHS = 60 batch_size = 32 iter_per_epoch = len(x_train)//batch_size val_per_epoch = len(x_test)//batch_size print(len(x_train)) print(len(x_test)) classifier = Sequential() classifier.add(Conv2D(32, 3, activation='relu', padding='same', input_shape=(img_w, img_h, 3))) classifier.add(BatchNormalization()) classifier.add(MaxPooling2D()) classifier.add(Conv2D(32, 3, activation='relu', padding='same', kernel_initializer='he_uniform')) classifier.add(BatchNormalization()) classifier.add(MaxPooling2D()) classifier.add(Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_uniform')) classifier.add(BatchNormalization()) classifier.add(MaxPooling2D()) classifier.add(Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_uniform')) classifier.add(BatchNormalization()) classifier.add(MaxPooling2D()) classifier.add(Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_uniform')) classifier.add(BatchNormalization()) classifier.add(MaxPooling2D()) classifier.add(Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_uniform')) classifier.add(BatchNormalization()) classifier.add(MaxPooling2D()) classifier.add(Flatten()) classifier.add(Dropout(0.5)) classifier.add(Dense(128, activation='relu')) classifier.add(Dense(4, activation='softmax')) classifier.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy']) classifier.summary() train_datagen = ImageDataGenerator( rotation_range=25, zoom_range=0.1, width_shift_range=0.1, height_shift_range=0.1, shear_range=0.2, horizontal_flip=True ) val_datagen = ImageDataGenerator() train_gen = train_datagen.flow(x_train, y_train, batch_size=batch_size) val_gen = val_datagen.flow(x_test, y_test, batch_size=batch_size) m = classifier.fit_generator( train_gen, steps_per_epoch=iter_per_epoch, epochs=EPOCHS, validation_data=val_gen, validation_steps=val_per_epoch, verbose=1 ) In My views.py gpuoptions = tf.compat.v1.GPUOptions(allow_growth=True) graph = Graph() with graph.as_default(): tf_session = tf.compat.v1.Session( config=tf.compat.v1.ConfigProto(gpu_options=gpuoptions)) with tf_session.as_default(): model = load_model('./models/classifier.h5') def process(img): test_image = cv2.resize(img, (int(img_w*1.5), int(img_h*1.5))) test_image = preprocess(test_image) test_image = … -
django template tags not rendering correctly
{% for page in pages %} <li><a href="{{ page.url }}">{{ page.title }}</a></li> {% if user.is_authenticated %} {% if fav_list %} <button id="test">Test button</button> {% if page in fav_list %} <button id="unsaveFavorite" class="showUnsaveFavorite" data-pageid="{{page.id}}">Unsave</button> {% endif %} { % else % } <button id="saveFavorite" class="showSaveFavorite" data-pageid="{{page.id}}">Save</button> {% endif %} {% endif %} {% endfor %} The buttons inside the if else are not rendering but they are in a if else and one should atleast render. What is the problem with my code . The fav_list is "<QuerySet []>". -
Is there a way to record the movements of one model in another?
Is there a way to record the movements of one model in another? Let me explain, I need my Inventory_Movements model to save the date and quantity of the new stock that enters my Products model. class Products(models.Model): barcode = models.CharField('Barcode', max_length=13, unique=True) name = models.CharField('Name product', max_length=60) price_cost = models.DecimalField('Cost price', max_digits=4, decimal_places=2) price_sale = models.DecimalField('Sale price', max_digits=4, decimal_places=2) stock = models.PositiveIntegerField('Stock', default=0) class InventoryMovements(models.Model): update_date = models.DateTimeField('Datetime', auto_now=True, auto_now_add=False) barcode_product = models.CharField('Barcode', max_length=13, unique=True) new_stock = models.PositiveIntegerField('Stock', default=0) I am new in this world of programming and I am not sure how to do it and if it is possible Thanks in advance -
Django How can I update relational model from its relative model
I have two models that are class Personal (models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) lastname = models.CharField(max_length=255) user_roles_id = models.ForeignKey(User_Role, on_delete=models.CASCADE) hospitals_id = models.ForeignKey(Hospital, on_delete=models.CASCADE) hospital_local_users_id = models.OneToOneField( Hospital_Local_User, on_delete=models.CASCADE) isDeleted = models.BooleanField(default=False) class Hospital_Local_User(models.Model): id = models.AutoField(primary_key=True) email = models.CharField(max_length=320) password = models.CharField(max_length=45) phone = models.CharField(max_length=45) I can change Person model with selectedUser = Personal.objects.get(id=userId) selectedUser.name = name but I cannot change mail and phone with belove code. selectedUser.hospital_local_users_id.email = email I can reach email with above code but I cannot update it. I couldn't figure out how to solve this issue. -
Django taggit aggregation query to return count per tag
I am using Django 3.2 and django-taggit 1.4 I have a model like this: class Meal(models.Model): # some fields is_cooked = models.Boolean() tags = TaggitManager() I am trying to generate a dictionary keyed by tag name and value of the number of times the tag appears - but only for meals that have the is_cooked flag set to True. I have tried the following: pks = list(Meal.objects.filter(is_cooked=True)) ct = ContentType.objects.get_for_model(Meal) b=TaggedItem.objects.filter(content_type=ct, object_id__in=pks).annotate(num_times=Count('tag__name')) This is not returning the expected results (and I expect that it might be hitting the DB several times because of so many lookups - but I don't want to get distracted by premature optimisation concerns. What am I doing wrong, and how do I get the count of Tags per tag? -
Django - adding variables
I can't do one thing and I have a huge problem with it. I want to make a view with the task, number of points and a button that will add points if the task is done. I would like the "grand" variable to be added to the "points" variable when the button is clicked. I tried to do it along with the django tutorial but unfortunately can't. class Quest(models.Model): task = models.CharField(max_length=200, null=True) grand = models.IntegerField(default=1, null=True) class Score(models.Model): prize = models.ForeignKey(Quest, default=1, on_delete=models.CASCADE) points = models.IntegerField(default=0) user = models.ForeignKey(User, on_delete=models.CASCADE) -
Output audio stream in HTML template, django
My python script uses pyaudio to output live audio after applying some filters. Now, I am adding the script to a website with django. The goal is to make a GUI with the audio stream and filters. So far, I've only found <audio controls></audio> but this will only output a file, statically. This does not work for my needs. Is there a way I can output my pyaudio stream on my webpage? How can I output my audio feed dynamically? -
Django forms.ModelChoiceField (empty_label) NOT passing the (mark_safe) values
I have a problem using the forms.py file, as I'm trying to customize the empty_label attribute of the forms.ModelChoiceField forms type. My main target is to customize the placeholder by passing HTML and CSS using the mark_safe function. However, when the page is rendered, the placeholder is rendered without the added HTML. The added HTML is present in the viewSource of the page but not the DOM. class ModelX(forms.Form): Name = forms.ModelChoiceField( empty_label=mark_safe('<span style="font-style: italic; color:#6c757d;"> (Please Select a name...) </span>'), ) -
Django Rest Framework - PrimaryKeyRelatedField with post_save signal
I am building an endpoint that uses the PrimaryKeyRelatedField to set the ManyToOne/Reverse Foreign key relationship of the example House model provided below: class House(models.Model): name = models.CharField(max_length=245) class Car(models.Model): name = models.CharField(max_length=245) house = models.ForeignKey(House, on_delete=models.DO_NOTHING, null=True, related_name='cars') The serializer uses the PrimaryKeyRelatedField in the following way: class HouseSerializer(serializers.ModelSerializer): cars = serializers.PrimaryKeyRelatedField(queryset=models.Car.objects.all(), many=True) class Meta: model = models.House fields = "__all__" I would like to create a signal which, after a house is saved, does something with the related cars. For example: @receiver(post_save, sender=models.House) def post_save_house(sender, **kwargs): instance = kwargs['instance'] print(instance.cars.all()) However, it seems that when updating a House object as well as its related Car objects through the HouseSerializer, the instance.cars.all() queryset still corresponds to the unupdated queryset. I tried refetching the objects from the database and clearing the queryset but that does not seem to be the issue. It seems that the PrimarykeyRelatedField first saves the House object before updating the related Car objects which makes sense when considering that, on creation, a House object must exist before attaching a Car object to it. Furthermore, the Car object does not send a post_save signal (I suspect queryset.update() is used to update the foreign keys?) so listening to … -
Can any one tell me the way to configure Django with nginx in arch linux?
Actually i am trying to host my website on a vps there i choose Arch linux as the image i've set-up everything and the site is listening on port 8000 as i want to host you know i need a server and i choose nginx but the problem i am facing that where to configure files and how because every tutorial is based on ubuntu and that sites available directory is not present in the ngnix. then my question is how can i set things up? Django with ngnix in Arch linux? please reply , i am just few steps back to make my dreams come true. please help me. -
Django - How can I change the width of the columns of a TableView?
I have a TableView which has many columns, that only contain a <select> input on each of the rows, so I don't need the columns to be very wide, since all options in those <select> inputs are just emojis. The thing is, the ammount of columns makes the table get a horizontal sidebar, and I would prefer the table to be all visible in the same screen, so I would have to make the columns shorter, but I haven't been able to do it. So far, my table displays like this: I'm looking for either a way to manually set the width of each column, or, preferably, make it so that all columns automatically either become the same size or all shorten enough to always appear without the need of the horizontal scrolling bar. So far, I've tried to use CSS to change the width of all <td> elements, or set the width of the columns in Django itself, doing this in the Table declaration: class PermissionsTable(Table): permission_0 = tables.columns.Column(empty_values=(), verbose_name='Usuarios', orderable=False, attrs={ 'td': { 'width': '50px' } }) [...] But none of those options have changed the width of any column. -
How to update data in back process django
I have a website in Django who collects data from several logs and create and manipulates objects accordingly. This far I have used django commands to run the parsers and do this actions. I am wondering if this is the correct way to do such action? Please share your thought with me thank you! -
Firefox can’t establish a connection to the server at
I am running a django application in Docker. The app was running properly before but now it is giving me the following error continuously. I am not sure where is the error. Please have a look over the following attached screenshot. https://drive.google.com/file/d/1o1Sb8p5AG-H944C9CgmwzZq66TlFHVAD/view?usp=sharing Thank you.