Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make a for loop break on counter in jinja2?
How can I make the for product in products loop break after the if condition is fulfilled 3 times. I have been trying to set up a counter but that isn't working... because set is not accepted inside of for loops. Though testing it out a bit more it isn't being accepted anywhere. When I use set it throws this exception or a variation of it: Invalid block tag on line 11: 'set', expected 'endblock'. Did you forget to register or load this tag? I am aware that I should put all the logic I'm using jinja2 for inside of the view and then pass it through the dictionary but it would take too much time to research everything about that and i just want to be done with this. Honestly I am really tired it is 6am and idk what to do. Thank you for your help in advance. :) HTML {% for category in categories %} <div> <h5 class="text-line"><a href="" class="store-category"><span>{{category.name}}</span></a></h5> </div> <!-- Cards Container --> <div class="shop-cards"> {% set counter = 0 %} {% for product in products %} {% if product.category.categoryID == category.categoryID %} <!-- CARD 1 --> <div class="card"> <image class="product-image" src="{% static 'images/product-4.png' %}"></image> … -
Django Vs Laravel for Web Development
I saw this But I am still confused. I started web development with vanilla PHP and was recently informed about a Python framework Django. So my question is, what's the point and benefit of using Django, PHP is designed directly to plug into a web page, whereas Django goes around the bush, and if you prefer a framework, there is Laravel, but for some reason, PHP is getting disrespected by developers. I understand that Python might be a more simple syntax, so easier to write and read, but is there anything else? And is worth learning Python, just for making web apps? Please trow your opinion and your advice will be very appreciated. Thanks -
Django for loop only parsing first row from json data on html template
I am able to access the entire json data when I make the call to the themoviedb api in the DOM, but when I try to loop/print it as an html template, it only parses the first row of the json object. How do I access the entire search results from the json object? def index(request): post = Show.objects.all().order_by('title') for lists in post: data = requests.get(F"https://api.themoviedb.org/3/search/tv?api_key={api_key}&language=en-US&page=1&include_adult=false&query={lists}") r = data.json() pprint(r) -
where is going data from <select> box
ive wrote a code to practice html and python i used django to build a add music page its for uploading musics the whole form used models and i know wheni i want to save sth its all related together but i added another option today for tags this option is not in form nor models its just in html file so what will happen if i choose and press submit and also if i want to make same in model how should i do {% extends 'pages/base.html' %} {% block content %} <!DOCTYPE html> <head> <meta name="description" content="page of adding music"> <meta name="keywords" content="music,upload_music"> <title>adding music</title> </head> <body> <p>here you can upload music</p> <form action="{% url 'pages:add_music' %}" method='post' enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p}} <div> <h3 style="border:2px blue; color:blue;">tags:</h3> <select style="padding: 4px;" id="tags" name="tags" multiple required="required" size='6'> {% for tag in tags %} <option value="{{tag}}">{{tag}}</option> {% endfor %} </select><br> </div> <button type='submit' value="submit" style="margin: 20px; background-color: yellow; color: green;">add</button> </form> </body> {% endblock %} -
Secure way to accept payments on Django Heroku?
I'm trying to accept payments on Django using Heroku. I've had a ton of issues using Stripe because I don't know much about client-side/server-side and every time I get something that works, I have to expose my private key. I feel like there's no resource out there for this. Does anyone have something that can help? -
Django inspectdb lost comment
I use mysql to test model.with django_comment_migrate save help_text to sql comment. Original model.py below: from django.db import models class Foo(models.Model): name = models.CharField(max_length=20, verbose_name='alias_name', help_text='alias_name') Run python manage.py inspectdb got result below, lost help_text. class App1Foo(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=20) class Meta: managed = False db_table = 'app1_foo' -
Django class variable to instance variable
It seems like name and tagline would be class variables, how have they managed to define name and tagline as instance variables. Creating an instance of blog would be like Blog(name='...', tagline='...'). Wouldnt the variable be available like so, Blog.name and Blog.tagline class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def __str__(self): return self.name -
DateField Django default does not apply to database:
When doing the basic models on my django app, I have encountered this issue: The model for a Product stands like this in my app: main_color = models.CharField(max_length=15) secondary_color = models.CharField(max_length=15) brand = models.CharField(max_length=30) catalog_inclusion_date = models.DateTimeField(default=datetime.now, blank=True) image_url = models.URLField(max_length=200) description = models.TextField() But the catalog_inclusion_date isn't working as intended. After migrating the models to the MySQL database and attempting to insert an entry on the table with this SQL sentence: INSERT INTO shoppingcart_cap(main_color, secondary_color, catalog_inclusion_date, brand, image_url, description, logo_color) VALUES ('Red', 'Black', 'Adidas', 'https://www.rekordsport.es/uploads/photo/image/4920/gallery_A02506_1.JPG', 'Kid cap', 'White') I get the following output: ERROR 1364 (HY000): Field 'catalog_inclusion_date' doesn't have a default value Thanks in advance. Edit: In MySQL, after doing DESCRIBE cap_table;, I get the following output: CREATE TABLE `shoppingcart_cap` ( `id` bigint NOT NULL AUTO_INCREMENT, `main_color` varchar(15) NOT NULL, `secondary_color` varchar(15) NOT NULL, `brand` varchar(30) NOT NULL, `catalog_inclusion_date` date NOT NULL, `image_url` varchar(200) NOT NULL, `description` longtext NOT NULL, `logo_color` varchar(20) NOT NULL, PRIMARY KEY (`id`) ) -
AttributeError: transform not found in Countvectorizer , using sklearn
Trying to load my spam text detection Machine Learning model in API using Django framework. My error when sending request with text:"Ahmed,,, Awwad.. Test" File "path/to/API.py", line 39, in predict_text vector = selector.transform(clean_text) File "/usr/lib/python3/dist-packages/scipy/sparse/base.py", line 687, in __getattr__ raise AttributeError(attr + " not found") AttributeError: transform not found [30/Jun/2022 00:11:23] "POST /api/spamurai HTTP/1.1" 500 103644 This my model: #convert a collection of text to amatrix of tokens (Bag of words) from sklearn.feature_extraction.text import CountVectorizer from joblib import dump import pickle #process_text previously defined function to preprocess text in model msg_vector= CountVectorizer(analyzer=process_text) message_bow = msg_vector.fit_transform(df['text']) pickle.dump(message_bow, open("vector_text.pkl", "wb")) dump(MultinomialNB,'spam_model_text.joblib') I was using joblib in both dumping but i got many errors with countervectorizer and joblib so i am trying pickle and joblib In my API.py file I load my text vector and MultinomialNB file as follows: from joblib import load from nltk.corpus import stopwords from sklearn.feature_extraction.text import CountVectorizer MultinomialNB_file = os.path.join(BASE_DIR, 'tutorials/data', 'spam_model_text.joblib') CountVectorize_file = os.path.join(BASE_DIR, 'tutorials/data','vector_text.pkl') txt_model = load(MultinomialNB_file) selector = pickle.load(open(CountVectorize_file, "rb")) # # pre processing email text to be used in ML Model without affecting accuracy of model def process_text(text): #processing_code return clean_text # # function uses trainig utilities used in TEXT ML Model def predict_text(text): # … -
if statement for a specific field in django template
I'm rendering a form in a django template using this model: class Group(models.Model): name = models.CharField(max_length=100) description = models.TextField() members = models.IntegerField(default=0) has_max = models.BooleanField(default=False) max_size = models.IntegerField(default=10) DAYS = [ ('Sundays', 'Sundays'), ('Mondays', 'Mondays'), ('Tuesdays', 'Tuesdays'), ('Wednesdays', 'Wednesdays'), ('Thursdays', 'Thursdays'), ('Fridays', 'Fridays'), ('Saturdays', 'Saturdays'), ] meeting_day = MultiSelectField( verbose_name = 'Meeting day(s)', choices=DAYS, max_choices=6, max_length=100 ) start_time = TimeField(widget=TimePickerInput) end_time = TimeField(widget=TimePickerInput) def __str__(self): return self.name And onto this template: <form method="POST"> {% csrf_token %} {{form.as_p}} <button>POST</button> </form> I have a couple of issues going forward: My first issue is that I only want to have max_size be displayed in my template form if the user clicks has_max. Like a conditional, where once the user checks the box, changing has_max to True then they can enter in the max size of the group. My second issue is that the start_time and end_time to render in my template or on the admin side. I'm not sure how TimePickerInput works, but right now, there are no fields in my template form or admin form that have those time fields. Also, last thing, if I have both names the exact same (i.e., ('Sundays', 'Sundays'), is it necessary to have both? Or can … -
How to adjust the Django PymemcacheCache limit to be over 1MB
A similar question was posted here regarding adjusting the 1mb limit of memcached storage in Django settings. However, the answer was referring to django.core.cache.backends.memcached.MemcacheCache, which has since been deprecated. I tried implementing to provided solution with the django.core.cache.backends.memcached.PyMemcacheCache backend but the provided OPTIONS ('server_max_value_length') is unrecognizable. I can't find the available list of Options for the newer PyMemcache backend from django (at least not any that allow me to adjust the storage limit. My Settings looks like this: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.PyMemcacheCache', 'LOCATION': 'cache:11211', 'OPTIONS': { 'server_max_value_length': 1024*1024*10 } } } I am deploying the app in a Python 3 Docker image with a docker-config.yml configuration. The config file relative to memcached looks like: cache: image: memcached ports: - "11211:11211" entrypoint: - memcached - -m 64 - -I 10m When caching views that return JSON Responses with < 1MB data, the caching works great and greatly improves speed. The main objective here is to speed up response times. As far as optimizing the query, its just a simple GET that filters off the authenticated users company. I think pagination would help speed up response time as well, seeing as this is a large list of data being … -
cant get CORS enabled on app inside django
I pip installed django-cors-headers it works on my base application, but wont work on my "rest_api" app. Access to fetch at 'http://localhost:8000/api/groups' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. Settings: INSTALLED_APPS = [ 'rest_framework', 'corsheaders', 'rest_api', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] -
How to add the entry, which has foreign key, from frontend having only the pk of fk
Probably not the best heading, but I will try my best to explain the question. I have two models set up in my Django app: class Category(models.Model): class Meta: verbose_name_plural = "Categories" name = models.CharField(max_length=20) def __str__(self): return self.name def get_absolute_url(self): return reverse('home') class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) body = models.TextField() post_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title + " | " + str(self.author) def get_absolute_url(self): return reverse('post-details', args=(str(self.id))) with respective serializers: class UserSerializer(ModelSerializer): class Meta: model = User fields = ['id', 'username', 'first_name', 'last_name'] class CategorySerializer(ModelSerializer): class Meta: model = Category fields = ['id', 'name'] class PostSerializer(ModelSerializer): category = CategorySerializer() author = UserSerializer() class Meta: model = Post fields = ['id', 'title', 'author', 'category', 'body', 'post_date'] and a default ViewSet for Post: from rest_framework.viewsets import ModelViewSet class PostViewSet(ModelViewSet): serializer_class = PostSerializer queryset = Post.objects.all().order_by('-post_date') I want to add a new entry by sending an axios POST request to my Django app from the Vue frontend and I would like to do it in such way: const formData = { title: this.title, category: this.category, body: this.body, author: this.$store.state.user_id, } axios({ method: "POST", url: '/api/blog/posts/', headers: {"Content-Type": "application/json"}, data: formData }) .then(response => … -
how can I transform this sql query for use in Django?
SELECT fija.id, concat(fija.nombres," ", fija.apellido1, " ", fija.apellido2) as Nombre, fija.rfc, fija.telefono, fija.fecha_inicio, puesto.puesto, puesto.codigo, group_concat(decl.id) as declaraciones FROM declaracionesSiDeclara.declaracion_infopersonalfija as fija INNER JOIN declaracionesSiDeclara.declaracion_catpuestos as puesto on puesto.id = fija.cat_puestos_id LEFT JOIN declaracionesSiDeclara.declaracion_declaraciones as decl on decl.info_personal_fija_id = fija.id group by fija.id; -
Django 'memoryview' object has no attribute '_committed'
I am writing app for students project and encountered problem when saving modified model object Model: class Appointments(models.Model): id = models.IntegerField(primary_key=True) patient_pesel = models.ForeignKey('Patients', models.DO_NOTHING, db_column='patient_pesel') appointment_date = models.DateTimeField(blank=True, null=True) department = models.ForeignKey('Departments', models.DO_NOTHING, db_column='department') room = models.ForeignKey('Rooms', models.DO_NOTHING, db_column='room', blank=True, null=True) doctor = models.ForeignKey('HospitalStaff', models.DO_NOTHING, db_column='doctor', blank=True, null=True) appointment_type = models.ForeignKey('DAppointmentType', models.DO_NOTHING, db_column='appointment_type') suggested_date = models.DateField() referral = models.FileField(upload_to='referrals', blank=True, null=True) nfz = models.BooleanField() recommendations = models.TextField(blank=True, null=True) accepted_at = models.DateTimeField(blank=True, null=True) accepted_by = models.ForeignKey('HospitalStaff', models.DO_NOTHING, db_column='accepted_by', blank=True, null=True, related_name='accepted_HospitalStaff') updated_at = models.DateTimeField(blank=True, null=True, auto_now=True) updated_by = models.ForeignKey('HospitalStaff', models.DO_NOTHING, db_column='updated_by', blank=True, null=True, related_name='updated_HospitalStaff') class Meta: managed = True db_table = 'appointments' View: def staff_accept_single_appointment_2(request): app_id = request.POST.get("appointment_id") date = request.POST.get("app_date") time = request.POST.get("app_hour") doctor = request.POST.get("doctor") room = request.POST.get("room") date_time_obj = datetime.strptime((str(date)+' '+str(time)).replace('-','/'), '%Y/%m/%d %H:%M') doctor_object = HospitalStaff.objects.get(id=doctor) room_object = Rooms.objects.get(room_name=room) app_object = Appointments.objects.get(id=app_id) app_object.appointment_date=date_time_obj app_object.doctor=doctor_object app_object.room=room_object app_object.save() return HttpResponseRedirect('/staff/registration/accept_appointments/accept_single_appointment') also checked much simpler version of view: def staff_accept_single_appointment_2(request): app_object = Appointments.objects.get(id=1) app_object.save() and i am still encountering 'memoryview' object has no attribute '_committed' error and can not go around it. Tried also using objects.filter().update() . It does not throws an error, but it does not affect database eighter. Tried searching solutions, maybe it is connected with FileField in … -
In Django Tables2, how do you make a column show text from a table referenced by a foreign key?
After reading all the docs and answers I can find, and burning a whole day, I still can't make this work. Using Django Tables2, I want to show a list of instruments; the instruments table includes a foreign key to an instrumentsType table. When I list the instruments and their attributes, I want to use the foreign key to substitute the textual instrument type description from the other table. I have tried every combination of double underscores and other accessor techniques, but so far all I get is the dreaded -- in the column. (Displaying just the record ID works). from .models import Instrument from django_tables2 import A from instrumenttypes.models import InstrumentType class InstrumentTable(tables.Table): id = tables.LinkColumn('instrument_details', args=[A('station_id')]) class Meta: model = Instrument template_name = "django_tables2/bootstrap.html" fields = ("id", "instrument", "nickname", "serialNo", "instrument__instrumenttype_id__instrumenttypes__id_instrumentType" ) The models involved are: Instruments model.py from django.db import models from instrumenttypes.models import InstrumentType from stations.models import Station # Create your models here. class Instrument(models.Model): instrument = models.CharField(max_length=40) instrumenttype = models.ForeignKey(InstrumentType, on_delete=models.CASCADE, null=True) station = models.ForeignKey(Station, on_delete=models.CASCADE, default=1) serialNo = models.CharField(max_length=60, null=True, blank=True) dateAdded = models.DateTimeField("Date Added", null=True, blank=True) dateRemoved = models.DateTimeField("Date Removed", null=True, blank=True) status = models.CharField(max_length=10, null=True, blank=True) nickname = models.CharField(max_length=40, null=True, blank=True) InstrumentTypes … -
Sum of column values inside Json array with group by
I have next Django model. class StocksHistory(models.Model): wh_data = models.JsonField() created_at = models.DateTimeField() I store JSON data in wh_data. [ { "id":4124124, "stocks":[ { "wh":507, "qty":2 }, { "wh":2737, "qty":1 } ], }, { "id":746457457, "stocks":[ { "wh":507, "qty":3 } ] } ] Note: it's data for one row - 2022-06-06. I need to calculate the sum inside stocks by grouping them by wh and by created_at so that the output is something like this [ { "wh":507, "qty":5, "created_at":"2022-06-06" }, { "wh":2737, "qty":1, "created_at":"2022-06-06" }, { "wh":507, "qty":0, "created_at":"2022-06-07" }, { "wh":2737, "qty":2, "created_at":"2022-06-07" } ] I know how to group by date, but I don't understand how to proceed with aggregations inside JsonField. StocksHistory.objects.extra(select={'day': 'date( created_at )'}) .values('day') .annotate( ??? ) A solution is suitable, both through Django ORM and through RAW SQL. -
Django admin - create user without set password
I need to set the admin user creation to let register an user but without request the password. password1 and password2 fields are required in admin forms. does anybody know how to achieve it? thanks! -
Django built in filter truncatewords ,how to get the left words?
I have a string named message equals to "Hello word how are you", In the Django template if I use: <div>{{message|truncatechars:2 }}</div> Then I will have: <div>Hello word</div> My question is except using {{message|slice:'11:'}},is there anyway I can get the rest words in message by using truncatechars or other django buit in template ? the output need be : how are you -
Toggle is_superuser in django admin
How to toggle a boolean field is_superuser in the django admin panel which enables a user to become superuser? I am using AbstractUser for my user model. -
Google Analytics Measurement Id as Environment Variable
I just started using Google Analytics and I have my code in my base html file for a Django web app. <!-- Global site tag (gtag.js) - Google Analytics --> <script nonce="{{ CSP_NONCE }}" async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXX"></script> <script nonce="{{ CSP_NONCE }}"> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag("config","G-XXXXXXXXX"); </script> <!-- end GA --> My question is, for the measurement id (G-XXXXXXXXX) is this something that needs to be a secret? I keep all my keys, etc in the env file and though I could do the same with this id but I keep running into errors. I tried {% 'GOOGLE_ID' %} but that didn't work. Is there a good way to implement this? -
How to count the total non-distinct many-to-many relationships across objects of a model?
Assume I have the following models: class Tag(Model): name = CharField() class Book(Model): title = CharField() tags = ManyToManyField(Tag) Now suppose I have 3 books, and each book has 3 tags. Some of the tags might be the same for some of the books, it doesn't matter. Book 1 (Tags = "tag1", "tag2", "tag3") Book 2 (Tags = "tag1", "tag4", "tag5") Book 3 (Tags = "tag4", "tag5", "tag6") How can I count all non-distinct tags in a Django ORM query so that I get 9 as a result? -
How to run a backend script on Django from html page
I'm trying to process apple pay payments on my Django site. While I understand that this is better off in the back end, I currently am running the scripts in a JS static file, which means that that info is public. How can I set up my project to run a back-end python script when the apple pay button is clicked? Please discuss file organization in your answer. (For simplicity, you can just assume I am trying to run a script that loads another website instead of going through the whole apple pay process.) I came across this resource and it looked like it could be along the right track, but I think it might be overcomplicating things. https://github.com/Jason-Oleana/How-to-run-a-python-script-by-clicking-on-an-html-button -
Is there a method to pass react sessionStorage data to django rest framework backend?
I have a variable named hostwhich stores a session id for a user who visits my site. The variable is stored in sessionStorage of my react frontend. Is there a way of passing this variable to my backend without having to fetch for an API view root from the backend? -
Django is not fetching another app static file but fetching the main app static file?
Django is fetching the main app static files but it is not fetching the other app static files how to solve it ?? Error in CC is: Main File : Html Link Of CC : Main html link : Folder structure :