Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django static file not found issue for new create static file
<!DOCTYPE html> {% load static %} <html> <head> <style> .info-container { margin-top: 6%; background-color: honeydew; text-indent: 20px; } .video-label { text-align: center; } .back-link { margin: 9px 15px; padding: 2px; } </style> <title>Coronavirus Tracker</title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <body> <nav class="navbar fixed-top navbar-expand-lg navbar-light bg-light" id="header-nav"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-nav"> <h2 class="nav-item">Weather Observations and Forecast</h2> <a class="nav-item back-link" href="/covid_tracker">Back to Coronavirus Tracker Home</a> </div> </nav> <div class="container"> <div class="row justify-content-center"> <div class="col-md-6 info-container"> <p> test </p> </div> </div> <div class="row"> <video width="480" height="360" class="video-player col-6" controls> <source src="{% static 'coronavirus_tracker/videos/wind.mp4' %}" type="video/mp4"> Your browser does not support the video tag. </video> <video width="480" height="360" class="video-player col-6" controls> <source src="{% static 'coronavirus_tracker/videos/noaatemp-usa.mp4' %}" type="video/mp4"> Your browser does not support the video tag. </video> </div> <div class="row"> <p class="col-6 video-label"> Global Wind Animation </p> <p class="col-6 video-label"> US Tempature Animation </p> </div> <div class="row"> <video width="480" height="360" class="video-player col-12" controls> <source src="{% static 'coronavirus_tracker/videos/sat-rainfall.mp4' %}" type="video/mp4"> Your browser does not support the video tag. </video> <p class="col-12 video-label"> Satellite Rainfall Observations </p> </div> </div> … -
How can I print the result I get from the algorithm in my Django project?
enter image description here I want to show my conclusion to the percentile here. enter image description here -
Install DRF 3.12 Alpha
I want to use a pre-release version of Django Rest Framework (DRF) in order to take advantage of the new JSONField feature. There doesn't appear to be a version to "pip install" for alpha 3.12. What is the appropriate way to install the alpha version into my env? -
Django template variable not accessible in javascript
The html (see below) has a <div class="choiceRadio"> that contains radio buttons and another <div class="choiceSelect"> that contains check boxes. The goal is to make the .choiceSelect div appear or disappear dependent on which radio button is selected. Note that this question may have been answered already except I have trouble applying them to my situation where the django template variable is needed to determine which radio button was selected. The buttons were created on the fly when the html is rendered from views.py. I have not been unable to get the template variable {{ selection.name }} to show up in the javascript. <script> document.addEventListener('DOMContentLoaded', () => { // hide div styled .choiceSelect when radio button #choice button is clicked document.querySelector('#choice').onclick = () => { var s = "{{ selection.name }}"; alert(s); div = document.querySelector('.choiceSelect'); if ('s' === 'special') { div.style.display = 'none'; } else { div.style.display = 'block'; } } }); </script> <body> {% for selection in category %} <div class="choiceRadio"> <ul> <li> {% if size == "small" %} <input type="radio" name="optradio" id="choice" value="{{ selecton.name }}-{{ selection.price-small }}"> <label for="{{ selecton.name }}-{{ selection.price-small }}">{{ selection.price_small }}</label> {% elif size == "large" %} <input type="radio" name="optradio" id="choice" value="{{ selecton.name }}-{{ … -
Changing API endpoint between development and production (React/Django)
I am developing a react app inside of a django project and connect them using the Django rest framework. For making API calls from within the react app I am using axios. Now in my development environment, I obviously call a localhost URL to access the API. For this, I have a file that contains an axios instance: import axios from "axios"; export const axiosInstance = axios.create({ baseURL: "http://127.0.0.1:8000/api/", timeout: 60000, }); Obviously, my API calls don't work in production as the URL differs from the one above. I am compiling my react app to a static file which I include in my django project so I don't think I could really add any code that checks for the environment. One idea that I had is that I could include a file into my project that I would not push into production and then check for whether this file exists or not and adjust the url in an if statement. However, I am not sure if that is a good solution or how I would implement this in plain Javascript. I am happy to hear any thoughts on this -
How not to display Django foreign key object source in table
I want to display date in table which is foreign key in this case and when I do this as result I see the date with information that it is object of different table. Which I don't want. I would appreciate help with this. class Factclaimcases(models.Model): idfactclaimcase = models.IntegerField(db_column='IdFactClaimCase', primary_key=True) # Field name made lowercase. idtechnican = models.ForeignKey(Dimtechnican, models.DO_NOTHING, db_column='IdTechnican') # Field name made lowercase. thedate = models.ForeignKey(Dimdate, models.DO_NOTHING, db_column='TheDate') # Field name made lowercase. description = models.CharField(db_column='Description', max_length=50) # Field name made lowercase. manufacturedef = models.TextField(db_column='ManufactureDef', blank=True, null=True) # Field name made lowercase. This field type is a guess. doc = models.BinaryField(db_column='Doc', blank=True, null=True) # Field name made lowercase. <div class="container"> <table> {% for item in query_results %} <tr> <td>{{ item.idfactclaimcase }}</td> <td>{{ item.thedate }}</td> <td>{{ item.description }}</td> </tr> {% endfor %} </table> </div> def index(request): query_results = Factclaimcases.objects.all() context = { 'query_results': query_results, } return render(request, 'index.html', context) -
How i can get all products except duplicates?
I have 2 models: class Product(models.Model): ... products = models.ManyToManyField('self', related_name='products') class OrderProduct(models.Model): """Products for Order that a user added in his cart.""" product = models.ForeignKey(Product, on_delete=models.PROTECT, related_name='order_products') I need to get all OrderProduct.product.products but without duplicates I tried to solve it like: suggestions = [product.product.products.all().distinct() for product in order_products] But I got [<QuerySet [<Product: Apple iMac Retina 5K>, <Product: iMac Pro>, <Product: Apple MacBook Air 2020>]>, <QuerySet [<Product: Apple iMac Retina 5K>, <Product: iMac Pro>]>] That's a list of querysets, not products list Please help me, I want to get result like QuerySet [Product: Apple iMac Retina 5k>, Product: iMac Pro>, Product: Apple MacBook Air 2020>] (so it looks like the result in my previous code, but in a 1 queryset and without duplicates (distinct)) -
Django Model for defining a relationship between two other models and filtering later
So am designing a REST API for a mobile blogging app, in which am trying to implement an upvote feature for the blog posts where what i want to implement is: Whenever a user U upvotes a particular blog B the client will send a POST request (with username and the blog name) which will define a relationship between them in the Database, so that later when the client wants to know that if a particular user has upvoted a particular blog or not, it can get to know by making a GET request through some filering. I have tried to create Vote model, in which i define a ManyToMany relationship with both, user and the blog post ( see the Vote Model below for better understanding) here are my models, class User(models.Model): username = models.TextField(max_length=30) def __str__(self): return self.username class Post(models.Model): headline = models.CharField(max_length=200) # the name of the blog #some other stuff like body of the blog . . def __str__(self): return self.headline The Vote model, class Vote(models.Model): user = models.ManyToManyField(User) post = models.ManyToManyField(Post) def __str__(self): return ("%s %s" %(self.user, self.post)) This does not do the job well, e.g., It requires the URL of the users and blog … -
React with Django: Internal Server Error 500
api-service.js This is my api code. Using this code, a user can login and do some operations like update, create and delete movies. All functions are working fine except for the registerUser. export class API { static loginUser(body) { return fetch(`http://127.0.0.1:8000/auth/`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify( body ) }).then( resp => resp.json()) } static registerUser(body) { return fetch(`http://127.0.0.1:8000/api/users/`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify( body ) }).then( resp => resp.json()) } static updateMovie(mov_id, body, token) { return fetch(`http://127.0.0.1:8000/api/movies/${mov_id}/`, { method: 'PUT', headers: { 'Content-Type': 'application/json', 'Authorization': `Token ${token}` }, body: JSON.stringify( body ) }).then( resp => resp.json()) } static createMovie(body, token) { return fetch(`http://127.0.0.1:8000/api/movies/`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Token ${token}` }, body: JSON.stringify( body ) }).then( resp => resp.json()) } static deleteMovie(mov_id, token) { return fetch(`http://127.0.0.1:8000/api/movies/${mov_id}/`, { method: 'DELETE', headers: { 'Content-Type': 'application/json', 'Authorization': `Token ${token}` } }) } } auth.js import React, { useState, useEffect } from 'react'; import { API } from '../api-service'; import { useCookies } from 'react-cookie'; function Auth(){ const [ username, setUsername ] = useState(''); const [ password, setPassword ] = useState(''); const [ isLoginView, setIsLoginView ] = useState(true); const [token, setToken] … -
Part of celery-beat periodic task not triggered
In django admin panel, I created about 1500 celery-beat periodic tasks, and 100 of them has the same crontab schedule 15 4 * 1 *. All of them were enabled. But at 04:15 on day-of-month 1, one of the periodic tasks was not sending due task to celery worker while all other tasks were sending. From the django admin panel, this periodic task's last_run_time is None, which indicates that it is not triggered. I tried to configure the crontab schedule to 15 * * * * and then it runs successfully at minute 15. So I wonder is there any limitation of the number of celery-beat periodic tasks? celery.py app = Celery('myapp', broker=os.getenv('BROKER_URL', None)) @signals.setup_logging.connect def setup_logging(**kwargs): """Setup logging.""" pass app.conf.ONCE = { 'backend': 'celery_once.backends.Redis', 'settings': { 'url': 'redis://localhost:6379/0', 'default_timeout': 60 * 60 } } app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) from django.utils import timezone app.conf.update( CELERY_ALWAYS_EAGER=bool(os.getenv('CELERY_ALWAYS_EAGER', False)), CELERY_DISABLE_RATE_LIMITS=True, # CELERYD_MAX_TASKS_PER_CHILD=5, CELERY_TASK_RESULT_EXPIRES=3600, # Uncomment below if you want to use django-celery backend # CELERY_RESULT_BACKEND='djcelery.backends.database:DatabaseBackend', CELERY_ACCEPT_CONTENT=['json'], CELERY_TASK_SERIALIZER='json', CELERY_RESULT_SERIALIZER='json', # Uncomment below if you want to store the periodic task information in django-celery backend CELERYBEAT_SCHEDULER = "django_celery_beat.schedulers.DatabaseScheduler", # periodic tasks setup CELERYBEAT_SCHEDULE={ 'check_alerts_task': { 'task': 'devices.tasks.alert_task', 'schedule': 300.0 # run every 5 minutes }, 'weather_request': { … -
CMS build with Python?
I'm trying to create a blog and e-commerce site. Is there an equivalent of Wordpress developed with Python ? Unfortunately I don't speak php. Thank you. -
Django Queryset returning different results for two exclude criteria and combined exclude criteria
Why django returning different results for below two exclude statements? Django Exclude Statement 1: self.fields.exclude(record_type__isnull=True, field=None).prefetch_related('field', 'field__table') Respective Django SQL Query: SELECT field1, field2, field__table FROM `table` WHERE (`table`.`t_ct_id` = 2 AND `table`.`t_id` = 32 AND NOT (`table`.`record_type` IS NULL AND `table`.`field_id` IS NULL)) Record Count: 395 Django Exclude Statement 2: self.fields.exclude(record_type__isnull=True).exclude(field=None).prefetch_related('field', 'field__table') Respective Django SQL Query 2: SELECT field1, field2, field__table FROM `table` WHERE (`table`.`t_ct_id` = 2 AND `table`.`t_id` = 32 AND NOT (`table`.`incoming_record_type` IS NULL) AND NOT (`table`.`field_id` IS NULL)) Record Count: 152 I am using django version 2.2.11 and MYSQL as database -
Django and Ajax: SyntaxError: Unexpected token D in JSON at position 0 at parse (<anonymous>)
The backend to my project is django (I am working on the 4th page of my project). I have a series of forms and inputs that take input data and then roll the inputs into a json object. I have checked to make sure that the json object is valid (pulled it from the console and used a json validator) after using stringify (var modelData_toserver = JSON.stringify(modelData). The resultant json is: {"data":[{"depth":[0]},{"temp":[1]},{"lakename":"m"},{"lakeId":"m"},{"area":"1"},{"fetch":"1"},{"maxDepth":"1"},{"lat":"1"},{"long":"1"},{"airTemp":"1"},{"shelterFactor":"1"},{"extinctCoeff":"1"},{"dispersion":"1"},{"longWave":"1"}]} My ajax code is (modelData_toserver is the json): function sendInputs(modelData_toserver, name){ var urlViews = "/beach/bmominputs/" + name + "/" console.log(urlViews) $.ajax({ url: urlViews, type:"POST", dataType: "json", data: modelData_toserver, error: function(jqXHR, textStatus, errorThrown) { alert('Lake Characteristics Data Not Delivered Properly'); $('#result').html('<p>status code: '+jqXHR.status+'</p><p>errorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>'); console.log('jqXHR:'); console.log(jqXHR); console.log('textStatus:'); console.log(textStatus); console.log('errorThrown:'); console.log(errorThrown); console.log('datatype:'); console.log(typeof data); }, success: function(data, textStatus, jqXHR) { alert('Data Sent Sucessfully'); } }); I am pretty sure my url.py is pointing properly to my view since if I input my URL directly into the browser it prints out the HttpResponse of the view -- HttpResponse("Data Posted Successfully"). I suspect that the stingify javascript is causing problems but not sure how to convert variable values to strings another way. Thank you for any … -
How to render HTML template for all nodes on-click - using Django mptt tree
I have setup a Django mptt tree which is displaying the tree correctly. The nested tree consists of 2 types of objects (reseller and customer - added in model). The reseller menu can be nested before reaching to a final customer menu at the end of a node. Based on type, both of them should render a html template on-click. But only the end node (leaf-node) is rendering html on-click. While the root-node or intermediate nodes do not respond to href menu associated. I'm stuck for almost 2 days and cannot figure out a solution. Please help. Django Model: from django.db import models from django.contrib.auth.models import User from mptt.models import MPTTModel, TreeForeignKey class Reseller(MPTTModel): reseller_name = models.CharField(max_length=40) reseller_email = models.EmailField(max_length=70,blank=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['reseller_name'] def __str__(self): return self.reseller_name class Customer(models.Model): customer_name = models.CharField(max_length=40) customer_email = models.EmailField(max_length=70,blank=True) reseller = models.ForeignKey(Reseller, on_delete=models.CASCADE, null=True, blank=True, related_name='cust_children') def __str__(self): return self.customer_name Django Url: from django.urls import path from . import views urlpatterns = [ path('dashboard/', views.dashboard, name='dashboard'), path('', views.loginpage, name='login'), path('ViewReseller/<str:pk>', views.ViewReseller, name='ViewReseller'), path('ViewCustomer/<str:pk>', views.ViewCustomer, name='ViewCustomer'), ] Django View: @login_required(login_url='login') def ViewReseller(request, pk): resellers = Reseller.objects.all() customers = Customer.objects.all() reseller_details = Reseller.objects.get(id=pk) context = { 'resellers' … -
How can i make a random default value for a django app that will change every time
I am trying to make a randomized math problem site but i cant save my random value in the database models.py class Problem(models.Model): answer = models.IntegerField() solution = models.IntegerField(default = random.randint(1,100)) correct = models.BooleanField(default = False) view.py def TedixRS_view(request, *args, **kwargs): current = Problem.objects.last() current.solution = random.randint(1,100) current.save() random_one = current.solution - random.randint(1,current.solution-1) random_two = current.solution - random_one print(current.solution) form = ProblemForm(request.POST or None) if form.is_valid(): form.save() form = ProblemForm() my_context = { 'random_one' : random_one, 'random_two' : random_two, 'form': form } -
How to change html file (front end) following the back end
I already have an html file of login user page(front end), then i follow the tutorial https://developer.mozilla.org/id/docs/Learn/Server-side/Django/Authentication I have reached stage Login Template, can you help me convert my html page (front end) following the tutorial my login page html: {% load static %} <html> <head> <title>Login Page</title> <link rel="stylesheet" type="text/css" href="{% static 'style login.css' %}"> <body> <div class="loginbox"> <img src="{% static 'avatar.png' %}" class="avatar"> <h1>Login Here</h1> <form method="post" action="{% url 'login'%}"> <p>Username</p> <input type="text" name="" placeholder="Enter Username"> <p>Password</p> <input type="password" name="" placeholder="Enter Password"> <input type="submit" name="" value="Login"> <a href="">Don't have an account</a> </form> </div> </body> </head> </html> the tutorial: {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <form method="post" action="{% url 'login' %}"> {% csrf_token %} <table> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> <input type="submit" value="login" /> <input type="hidden" name="next" value="{{ next }}" /> </form> … -
how to pass value from views to non-editable field django pyhton
i want to auto insert user to the follwing model: class Moduls(models.Model): module_name = models.CharField(max_length=255) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, db_column='created_by', blank=False, null=False , on_delete=models.CASCADE, editable = False) i have 2 cases : 1- in django admin and i solve this case by the following * add editable = False to created by field * in admin.py i used the follwoing: def save_model(self, request, obj, form, change): obj.created_by = request.user super().save_model(request, obj, form, change) but i face the problem when i try to use forms.py i can't pass user from user views.py and if i want to add created_by field to my form i have this error: 'created_by' cannot be specified for Moduls model form as it is a non-editable field -
JavaScript,Jquery, Django
is there anyway to update data in a JS file dynamically in django framework. i have a file where i want to update data in it or there is an alternative way of doing that without a js file. the data is in chart js. -
Django rest framework: added fields from one serializer do not get stored
I have two serializers IngredientSerializer and RecipeSerializer. I am trying to include the fields of the IngredientSerializer in the RecipeSerializers fields by just calling the required fields in RecipeSerializer: class IngredientSerializer(serializers.ModelSerializer): class Meta: model = Ingredient fields = ( 'ingredient', 'quantity', 'size', 'unit' ) class RecipeSerializer(serializers.ModelSerializer): ingredient = IngredientSerializer(many=True, read_only=True) quantity = IngredientSerializer(many=True, read_only=True) size = IngredientSerializer(read_only=True) unit = IngredientSerializer(read_only=True) class Meta: model = Recipe fields = ( 'cooking_time', 'degrees', 'description', 'difficulty', 'id', 'images', 'ingredient', 'mode', 'name', 'portions', 'preparation_time', 'quantity', 'size', 'total_time', 'type', 'unit' ) How ever I do not get any errors but the input values are not store in the DB. Any help is highly appreciated. -
How do you test a django webapplication's front end when it's heavy JS?
This is more of a guidance thing. Here's the general breakdown of my app: It has a backend with all the models It has an app for the API routing and the serializers/viewsets It has a frontend that takes care of the main routing (index, contact us, content, etc.) and serves the templates and the static components Part of the static components are mustache-js templates. When the user loads the page the client performs some ajax requests to the API and pulls in data, it then takes care of populating components. I currently have tests for Backend models API behavior and methods Frontend paths actually loading But how do I test the parts where it's mostly JS dependent? I've been using selenium to do this. Is this the right approach? It does seem awfully hacky. -
How to manipulate a CSV file without saving it using DJANGO
I want to add an option for uploading a CSV file and updating the database in my DJANGO project. Before updating the database I want to show the data of the file to the user. How can I do it precisely without saving the file? -
django.db.utils.OperationalError: (3780, "Referencing column '...' and referenced column '...' in foreign key constraint '...' are incompatible.")
I get this error message when I try to create a new table in my database which I in terms of values have already added to the database. The error message I get is this: Operations to perform: Apply all migrations: main Running migrations: Applying main.0113_user_accumulated_countries...Traceback (most recent call last): File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 74, in execute return self.cursor.execute(query, args) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/MySQLdb/cursors.py", line 209, in execute res = self._query(query) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/MySQLdb/cursors.py", line 315, in _query db.query(q) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/MySQLdb/connections.py", line 239, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (3780, "Referencing column 'iso_code_id' and referenced column 'iso_code' in foreign key constraint 'main_user_accumulate_iso_code_id_65d73d54_fk_main_hs_c' are incompatible.") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 31, in <module> execute_from_command_line(sys.argv) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 231, in handle post_migrate_state = executor.migrate( File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/5knnbdwm/Python_env/lib/python3.8/site-packages/django/db/migrations/executor.py", line 147, in … -
Django: Invalid literal error when trying to use a basic ranking algorithm based on views
hey guys I am following a tutorial and they have this view for ranking images based on the number of views. I had followed it almost the same way, but I am getting an error like this. invalid literal for int() with base 10: b'nature' this is my code: def image_ranking(request): # get image ranking dictionary image_ranking = r.zrange('image_ranking', 0, -1, desc=True)[:10] image_ranking_ids = [int(id) for id in image_ranking] # get most viewed images most_viewed = list(Image.objects.filter(id__in=image_ranking_ids)) most_viewed.sort(key=lambda x: image_ranking_ids.index(x.id)) context = {'most_viewed':most_viewed} return render(request, 'images/trial.html', context) I have these 2 lines along with my detail view, where I use only the slug and not the id. # increment total image views by 1 image_views = r.incr(f'image:{image.slug}:views') r.zincrby('image_ranking', 1, image.slug) #to store views ranking How to resolve the error and have the ability to use id and slug depending on the application and not just the slug. -
Django form for writing blogs
As a beginner in Django I know how to create basic website for blogs, using a Django model of fields title and content... that's it. But now I want to create a real dynamic blog form, which can have multiple sub headings, code blocks, text blocks, and images. Or basically a blog form which can have random number of these kinds of blocks (field like code, text, image). And the user can add as many number of these blocks as required. Also these blocks (or fields) which would be the part of the blog post, should be saved in the dataset in the same order as the user created. How can I achieve this? Thanks for your time. -
Pictures are not getting updated in database even after submitting using DJANGO Model Forms
I intend to make a user profile model with profile picture in django. Everything works fine but I can't update the profile picture of the user. The form is being displayed on the website but on clicking submit, no changes are visible in the database and the image is also not getting uploaded. Below is my code for the form in HTML. <form method="POST" action="{% url 'profile' %}" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <br><br> <div class="mb-3"><button class="btn btn-primary btn-sm" name="_picture" type="submit">Change Photo</button></div> </form> Below is the code models.py, for creating user profile model. class UserProfileInfo(models.Model): # Create relationship (don't inherit from User!) user = models.OneToOneField(User, on_delete=models.CASCADE) isInstructor = models.BooleanField(default=False) department = models.ForeignKey(Department,on_delete=models.CASCADE) role = models.ManyToManyField(Role) profile_picture = models.FileField(upload_to='static/profile_pic/'+str(time.time()),default='d.jpeg') address = models.TextField(max_length=256) city = models.TextF class UpdateProfilePic(ModelForm): class Meta: model = UserProfileInfo fields = ['profile_picture'] Below is the code for forms.py @login_required def profile(request): current_user_profile = UserProfileInfo.objects.get(user=request.user) current_user = request.user form = UpdateProfilePic(instance=current_user_profile) context = {'current_user':current_user,'current_user_profile':current_user_profile,'form':form} if request.method=='POST': if '_user' in request.POST: temp_user = request.user temp_user.username = request.POST.get('username') temp_user.e Help me with the code, please!