Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django address input field that updates google map and can be uploaded to data base
I'm creating a Django blog style application that involves a user inputting a few fields, one of which is an address. What I want to do is when the user begins typing their address, address options begin to show up, like you'd see if you were to type on google maps. When the user then decides on the correct address and clicks the post button I want the address to be stored into the data base. This is because when another user clicks on the blog post I want a google map to show up with a marker on the address that the post creator submitted. I've tried to achieve this using Mapbox but couldn't quite get it to work so I'm trying to do it using google map JavaScript API. I found something that I think will help me on https://developers.google.com/maps/documentation/javascript/examples/places-searchbox but for some reason when I copy the javascript code onto my Django Project I get errors like 'Unresolved variable or type google' and 'Deprecated symbol used, consult docs for better alternative ' and nothing shows up on the page, which leads me to believe that I should have installed some package or should have added something to … -
getting url slug django
i am wanna get url slug to show selected category by user on breadcumb. how can i get it? i found only wordpress and php solves. template <div class="breadcumb_area bg-img" style="background-image: url({% static 'img/bg-img/breadcumb.jpg' %});"> <div class="container h-100"> <div class="row h-100 align-items-center"> <div class="col-12"> <div class="page-title text-center"> <h2>dresses</h2> </div> </div> </div> </div> </div> -
I cant seem to push code to heroku on vsc
I'm reading Django for Beginners and in the book you need to push your code to heroku but when I try to push it to heroku im getting an error that looks something like this Enumerating objects: 26, done. Counting objects: 100% (26/26), done. Delta compression using up to 4 threads Compressing objects: 100% (25/25), done. Writing objects: 100% (26/26), 3.85 KiB | 171.00 KiB/s, done. Total 26 (delta 2), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: ! No default language could be detected for this app. remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. remote: See https://devcenter.heroku.com/articles/buildpacks remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: 49cd9b70adce6b44ee89a1fddec675d04bc4300d remote: ! remote: ! We have detected that you have triggered a build from source code with version 49cd9b70adce6b44ee89a1fddec675d04bc4300d remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! remote: ! … -
How to get multiple select values from my own Django form
I would like to know how to get values from a jquery plugin from select multiple. This is my form. <form action="{% url 'agregar_solicitud' %}" method="post"> {% csrf_token %} <select name="producto[]" class="form-control" multiple="multiple" > {% for row in rows %} <option value="{{row.nombre}}">{{row.nombre}}</option> {% endfor %} </select> {% load static %} <script src="{% static 'js/BsMultiSelect.min.js' %}"></script> <script> $("select").bsMultiSelect({cssPatch : { choices: {columnCount:'3' }, }}); </script> <input type="submit" name="agregar" value="Agregar Productos" class="btn btn-success"> </form> [That is the image of the form] 1 And this is my view. def agregar(request): pr= request.POST["producto[]"] data = request.POST.get('producto[]') print(pr,data) return redirect('inicio_solicitud') But by none of the methods I can obtain the value of the product field by its position, such as: request.POST["producto1"]. In Laravel I had no problem doing the following: $request->producto1. Beforehand thank you very much. -
How to implement extended auth-User model in SignUp form in Django?
I want to add more fields in auth-User model. So, according to this docs(https://docs.djangoproject.com/en/3.2/topics/auth/customizing/#extending-the-existing-user-model) I created a 'UserProfile' model in one-to-one relation with auth-user. But it's not working in forms.py. Actually, I couldn't implement it in forms.py Here is my code: models.py class UserProfile(models.Model): user = models.OneToOneField(User, related_name='userprofile', on_delete=models.CASCADE) profile_picture = models.ImageField() forms.py class CustomSignupForm(SignupForm): profile_picture = forms.ImageField() def signup(self, request, user): up = user.userprofile user.userprofile.profile_picture = self.cleaned_data['profile_picture'] up.profile_picture = self.cleaned_data['profile_picture'] user.save() up.save() return user Even after SignUp I don't get any object in 'UserProfile'.