Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
I would like to divide my page in 2 columns with bootstrap on 2 news articles for my django home template
I have created my django home template for my scraper and I would like to divide the page in 2 columns with the scraped stories appearing side by side. I have loaded bootstrap on my Base template with CSS and HTML. This is my code so far {% extends 'base.html' %} {% block title %} <div class="container"> Home </div> {% endblock title %} {% comment %} {% endcomment %} {% block content %} <div class="container"> <div class="p-3 mb-2 bg-dark text-white"> <h1>JSE News</h1> {% for item in jse_articles %} <h3><a href="{{ item.Link }}" target="_blank" rel="noopener noreferrer">{{ item.Headline }}</a></h3> {{item.Text}} <!-- <img src ="{{item.Image}}"> --> {% endfor %} <hr> <br> <h1>Coin Desk News</h1> {% for item in coindesk_articles %} <h3><a href="{{ item.Link }}" target="_blank" rel="noopener noreferrer">{{ item.Headline }}</a></h3> {{item.Text}} {% endfor %} </div> </div> {% endblock content %} -
django: Manager isn't accessible via username_and_password instances
I am facing a error in Django. Here is my code. Also I am working with databases here. Here is my code in models.py: from django.db import models from django.db.models.fields.related import ForeignKey # Create your models here. class username_and_password(models.Model): user_name = models.CharField(max_length=300) password = models.CharField(max_length=300) def __str__(self): return self.password And then I went to the cmd and made migrations. then opened the shell. So far everything worked. In shell I did In [2]: from main.models import database, username_and_password In [3]: data = username_and_password(user_name="Databasetest",password="Runningtest") In [4]: data.save() Everything worked but then when I typed: data.objects.all() It showed me an error: AttributeError Traceback (most recent call last) <ipython-input-4-d33a4311e29a> in <module> ----> 1 data.objects.all() ~\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py in __get__(self, instance, cls) 177 def __get__(self, instance, cls=None): 178 if instance is not None: --> 179 raise AttributeError("Manager isn't accessible via %s instances" % cls.__name__) 180 181 if cls._meta.abstract: AttributeError: Manager isn't accessible via username_and_password instances Please help me on this, I am new to the library Django, Any help is appreciated . -
How do I cross reference two databases in Django?
I have a Django server running where I have two apps: Flowers, and Shops. I would like to do a query where I get information back from both tables at the same time. With SQL, I would say SELECT * FROM flowers, shops WHERE flowers.flowerID=shop.flowerID. How would I do this for Django? I currently have serializers for both individual apps, but cannot seem to combine them. The flowers.models.py is set up like this: class Flowers(models.Model): flowerID = models.IntegerField() flowerName = models.TextField() flowerSpecies = models.TextField() flowerColour = models.TextField() The shop.models.py is set up like this: class Shop(models.Model): flowerID = models.IntegerField() quantity = models.IntegerField() cost = models.TextField() comments = models.TextField() Any help is appreciated - even if it is pointing to specific online resources. -
Django + MongoDB + Djongo: can't json serialize ObjectId
I'm creating a Django APP with MongoDB using Djongo. When I try json.dumps(my_queryset, cls=DjangoJSONEncoder) I get the following error. Object of type ObjectId is not JSON serializable The model class Productos(models.Model): _id = models.ObjectIdField() id_anwen = models.IntegerField(help_text="Pedido Mínimo", blank=True, null=True, default=1) codigo_kinemed = models.CharField(max_length=100, blank=True, null=True) codigo_barra = models.CharField(max_length=100, blank=True, null=True) codigo_inner = models.CharField(max_length=100, blank=True, null=True) codigo_master = models.CharField(max_length=100, blank=True, null=True) item_number = models.CharField(max_length=100, blank=True, null=True) objects = models.DjongoManager() Some test If I remove _id = models.ObjectIdField() json dumps works fine but I don't get the object's ID info in the JSON. How can I serialize MongoDB's _id field for a JSON? Any clues welcome. Thanks in advance! -
how to correctly connect models in django quiz app
I am creating google form like quiz app,is this model fine that create 4 column for every answer. when i create Question also i create Answer's model 4 object it's good? How to connect better so that not many objects are created in the database and are well sorted class Quiz(models.Model): name = models.CharField( max_length=90, verbose_name=_('ქვიზის სახელი') ) image = models.ImageField( upload_to='images', verbose_name=_('ქვიზის სურათი') ) played = models.IntegerField(verbose_name=_('რამდენჯერაა ნათამაშები')) author = models.ForeignKey( User, on_delete=models.CASCADE, verbose_name=_('ქვიზის ავტორი') ) def __str__(self): return self.name class Meta: verbose_name = _('ქვიზი') ordering = ['-id'] class Question(models.Model): question = models.CharField( max_length=200, verbose_name=_('კითხვა') ) quiz = models.ForeignKey( Quiz, on_delete=models.CASCADE, verbose_name=_('ქვიზი') ) def __str__(self): return self.question class Answer(models.Model): probable_answer = models.CharField( max_length=150, verbose_name=_('სავარაუდო პასუხი') ) correct = models.BooleanField( default=False, verbose_name=_('სწორი პასუხია?') ) question = models.ForeignKey( Question, on_delete=models.CASCADE, verbose_name=_('რომელი კითხვის სავარაუდო პასუხია?') ) -
I am using a converter type in my URLs to capture a string paremeter in Django. Will it affect SEO?
I am using this URL pattern in Django to pass a string parameter for location: path('location/<str:locs>/', LocationView, name='location'), The website is a directory to more than 90 locations. I cannot add content to each location to improve the SEO performance of my site. Will it hurt the SEO performance of my website for pages that do not have content at some point? If yes, what can I do to add content to URL for location. For example, I want specific content to appear on "location/Washington" and not be repeated for other locations.