Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
HTMX parsing JSON response issue
I have a page that posts some data to the Django back-end and JSON response is returned. I have an issue parsing this using templates. Any help would be appreciated. Thank you in advance. <div class="card-body"> <form> {% csrf_token %} <div class="input-group mb-3"> <label class="input-group-text">Command</label> <select class="form-select" name="run_show_command" id="run_show_command"> <option selected disabled>Choose...</option> <option value="{{ data.version.id }}:1">show ip interface brief</option> <option value="{{ data.version.id }}:2">show interfaces description</option> <option value="{{ data.version.id }}:3">show ip arp</option> <option value="{{ data.version.id }}:4">show ip route</option> <option value="{{ data.version.id }}:5">show ip cef</option> <option value="{{ data.version.id }}:6">show version</option> </select> <button type="submit" class="btn btn-sm btn-success" hx-post="{% url 'inventory:device_run_command' %}" hx-target="#command_output" mustache-template="m_template" hx-indicator="#loader_bars"> <i class="fas fa-terminal"></i> Run </button> </div> </form> <div class="d-flex justify-content-center" hx-ext="client-side-templates" id="command_output"> <img id="loader_bars" class="htmx-indicator" alt="Loading..." src="{% static 'images/loaders/bars.svg' %}"/> <template id="m_template" type="text/mustache"> {% for data in dataset %} {% for key, value in data.items %} <li>{{ key }} {{ value }}</li> {% endfor %} {% endfor %} </template> </div> </div> JSON: [{ "intf": "GigabitEthernet1", "ipaddr": "10.10.20.48", "status": "up", "proto": "up" }, { "intf": "GigabitEthernet2", "ipaddr": "unassigned", "status": "administratively down", "proto": "down" }, { "intf": "GigabitEthernet3", "ipaddr": "unassigned", "status": "administratively down", "proto": "down" }, { "intf": "Loopback1", "ipaddr": "10.10.10.100", "status": "up", "proto": "up" }, { "intf": "Loopback123", "ipaddr": "unassigned", … -
I am getting some problem while login from jwt token, I can get token but getting some problem as authentication not provided ? In Django from API
Hello Everyone Can Anyone Please Help me I am getting some problems while logging the user. I can get proper tokens also but can't authenticate that. I am Getting an Error as Below also while getting the token too. HTTP 401 Unauthorized Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: JWT realm="api" { "detail": "Authentication credentials were not provided." } In setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'webapi.apps.WebapiConfig', 'corsheaders', 'rest_framework', 'ratings', # 'rest_framework.authtoken', 'rest_framework_simplejwt', 'rest_framework_simplejwt.token_blacklist', 'rest_auth', 'phone_field', 'phonenumber_field', 'djoser', 'users.apps.UsersConfig', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('JWT',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } At urls.py from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, TokenVerifyView, ) urlpatterns = [ path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('token/verify/', TokenVerifyView.as_view(), name='token_verify'), ] -
How to read env vars from settings in django unittest?
I am new to unittesting. I want to read some env vars in django unittests, but I am having some troubles when trying to read the env var from django.conf.settings, but I can read the env var using os.environ.get(). How can I access the current env var from django.conf.settings? The test code looks like the following: from unittest.mock import patch def test_functionality_in_non_production_environments(self): with patch.dict('os.environ', { 'ENVIRONMENT': 'local', 'ENV_VALUE': 'test_env_value', }): from django.conf import settings print(settings.ENV_VALUE) # --> DOES NOT PRINT 'test_env_value' print(os.environ.get('ENV_VALUE')) # --> PRINTS 'test_env_value' I am trying to test the correct behaviour of the code depending on the env var. In some parts of the code there is some logic like: if settings.ENV_VALUE and setting.ENVIRONMENT == 'local': # do some stuff -
ImportError: cannot import name from partially initialized module Django
I'm facing an issue which I don't know why the error occurs, please help me to resolve this error: error: ImportError: cannot import name 'User' from partially initialized module 'authentication.models' (most likely due to a circular import) (/app/authentication/models.py) User model: from projects.models import Organization class User(AbstractBaseUser, PermissionsMixin): organization = models.ForeignKey(Organization, on_delete=models.CASCADE, null=True) the error occurs after this ^ import Project models: from django.db import models from authentication.models import User class Organization(models.Model): OWNER = 1 CONTRACTOR = 2 DISTRIBUTOR = 3 MANUFACTURER = 4 CONSULTANT = 5 ORG_TYPES = [ (OWNER, 'Owner'), (CONTRACTOR, 'Contractor'), (DISTRIBUTOR, 'Distributor'), (MANUFACTURER, 'Manufacturer'), (CONSULTANT, 'Consultant'), ] name = models.CharField(max_length=255, default='') created_at = models.DateTimeField(auto_now=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) is_active = models.IntegerField(default=1, null=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True) org_type = models.CharField(max_length=1, choices=ORG_TYPES) class Meta: db_table = 'organizations' class Project(models.Model): name = models.CharField(max_length=255, default='') description = models.CharField(max_length=255, default='') created_at = models.DateTimeField(auto_now=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) is_active = models.IntegerField(default=1, null=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True) account = models.ManyToManyField(User, related_name='account') contractor = models.ForeignKey(Organization, related_name="contractor", on_delete=models.CASCADE) distributor = models.ForeignKey(Organization, related_name="distributor", on_delete=models.CASCADE) manufacturer = models.ForeignKey(Organization, related_name="manufacturer", on_delete=models.CASCADE) consultant = models.ForeignKey(Organization, related_name="consultant", on_delete=models.CASCADE) owner = models.ForeignKey(Organization, related_name="owner", on_delete=models.CASCADE) class Meta: db_table = 'projects' -
show_name() missing 1 required positional argument: 'obj'
I am whant to use a function that I have in a different admin, but it gives me an error. this is the function I whant to use: def show_data_user(self, obj): if obj.is_individual(): return self.show_owner(obj) obj = obj.get_real_instance() return mark_safe('<br>'.join( filter( None, [ self.show_name(obj), self.show_second_name(obj), self.show_business(obj), self.show_country(obj), self.show_position(obj), self.show_money(obj), ] ) ) ) and I've puted in another admin like this: def show_employer(self, obj): from employerdata.admin import Titular if obj.titular and isinstance(obj.titular, Employer): return Titular.show_data_user( Titular.show_name(obj), Titular.show_second_name(obj), Titular.show_business(obj), Titular.show_country(obj), Titular.show_position(obj), Titular.show_money(obj) ) How should I fix it? -
Single data from the relation m2m field - Django
In my signal (post_save), I would like to send a single email to a single person who has been assigned using the m2m relationship. One-to-many, the message goes to the user, but m2m nothing happens. specials = models.ManyToManyField(User, related_name='special_users') I've tried everything, searched the topics, but still nothing happens. I have included the pseudocode to illustrate the situation. all_users_from_m2m = instance.specials.all() for single_user in all_users_from_m2m: message = ('Subject', 'Here is message', 'from@example.com', [single_user.email]) send_mass_mail(message, fail_silently=False) -
Jupyter Notebook crashes every time there is an error
I am using the Django Shell Plus notebook on mac. Every time there is an execution error, the Jupyter Notebook crashes without showing the error on the notebook, but showing it on the Shell Plus prompt. It forces me to restart the notebook and execute all the cells each time. -
Django - Return multiple columns in subquery
I have objects that are made up of multiple other objects - specifically an event, that can have multiple dates, and multiple appointments on those dates. Any changes to any event, date or appointment are logged using Django Auditlog. I need to make a query that shows all events and the first and last edit on the event or any children objects related to it. I can create the query that will go through the auditlogs but I wondered if it was possible to return both the first and last edit timestamp in a single subquery? It looks like it is only possible to return one. Otherwise I suppose I could call the query once (which seems clunky) or to drop into raw sql but that was something that I wanted to avoid. -
Import Err in Django [closed]
I'm facing an issue which I don't know why the error occurs, please help me to resolve this error: error: ImportError: cannot import name 'User' from partially initialized module 'authentication.models' (most likely due to a circular import) (/app/authentication/models.py) User model: from projects.models import Organization class User(AbstractBaseUser, PermissionsMixin): organization = models.ForeignKey(Organization, on_delete=models.CASCADE, null=True) the error occurs after this ^ import Project models: from django.db import models from authentication.models import User class Organization(models.Model): OWNER = 1 CONTRACTOR = 2 DISTRIBUTOR = 3 MANUFACTURER = 4 CONSULTANT = 5 ORG_TYPES = [ (OWNER, 'Owner'), (CONTRACTOR, 'Contractor'), (DISTRIBUTOR, 'Distributor'), (MANUFACTURER, 'Manufacturer'), (CONSULTANT, 'Consultant'), ] name = models.CharField(max_length=255, default='') created_at = models.DateTimeField(auto_now=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) is_active = models.IntegerField(default=1, null=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True) org_type = models.CharField(max_length=1, choices=ORG_TYPES) class Meta: db_table = 'organizations' class Project(models.Model): name = models.CharField(max_length=255, default='') description = models.CharField(max_length=255, default='') created_at = models.DateTimeField(auto_now=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) is_active = models.IntegerField(default=1, null=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True) account = models.ManyToManyField(User, related_name='account') contractor = models.ForeignKey(Organization, related_name="contractor", on_delete=models.CASCADE) distributor = models.ForeignKey(Organization, related_name="distributor", on_delete=models.CASCADE) manufacturer = models.ForeignKey(Organization, related_name="manufacturer", on_delete=models.CASCADE) consultant = models.ForeignKey(Organization, related_name="consultant", on_delete=models.CASCADE) owner = models.ForeignKey(Organization, related_name="owner", on_delete=models.CASCADE) class Meta: db_table = 'projects' -
How to make search in combinations of fields available in Django Haystack
Suppose I have a Search index like this for a model of a Chapter within a book. class ChapterIndex(indexes.ModelSearchIndex, indexes.Indexable): # Normal document field - most often searched text = indexes.EdgeNgramField(document=True, use_template=True) # Other fields Id like to be searchable title = indexes.EdgeNgramField() author = indexes.EdgeNgramField() Now suppose a user selects a search within title and author fields and enters the following text: "titlepart author_lastname", which is not an unlikely search. I build my searchquerys like this: SQ(title=AutoQuery(query)) | SQ(author=AutoQuery(query)) The problem is, that the full text is now in neither of the fields author (misses the titlepart) and title (misses the authors last name). Therefore a correct chapter (where the author field contains the last name and the titlepart is in the title) is not selected by django-haystack. I am using the whoosh backend for this, but I guess it is independent of that. Here is the different solutions I have tried. Splitting up search terms. Splitting up the terms and searching for everything by itself yields a too generous search behavior. For example, the search for "foo" yields 10 results. Too general, specify more and enter "foo bar". The search still yields 10 results, as the word "foo" … -
Django - Group by two columns to create a stacked column chart with Highcharts
I have a Student model for my Django app, like this: from django.db import models class Student(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) major = models.CharField(max_length=100) year = models.IntegerField() And I'm trying to create a stacked column chart, using Highcharts. So the output is like this: The idea is that I want to show the number of students that we have in each year, stacked with majors. This is all the data for this example, excluding the names: [{'major': 'Computer Science', 'year': 1394}, {'major': 'Electrical Engineering', 'year': 1394}, {'major': 'Computer Science', 'year': 1394}, {'major': 'Chemistry Engineering', 'year': 1395}, {'major': 'Computer Science', 'year': 1396}, {'major': 'Computer Science', 'year': 1394}, {'major': 'English Literature', 'year': 1395}, {'major': 'English Literature', 'year': 1394}, {'major': 'Computer Science', 'year': 1395}, {'major': 'Chemistry Engineering', 'year': 1397}, {'major': 'Art', 'year': 1397}, {'major': 'Electrical Engineering', 'year': 1398}, {'major': 'Electrical Engineering', 'year': 1399}, {'major': 'English Literature', 'year': 1399}, {'major': 'Computer Science', 'year': 1400}, {'major': 'Chemistry Engineering', 'year': 1397}, {'major': 'English Literature', 'year': 1397}, {'major': 'Physics', 'year': 1393}, {'major': 'Physics', 'year': 1393}, {'major': 'Chemistry Engineering', 'year': 1392}, {'major': 'Persian Literature', 'year': 1392}, {'major': 'Computer Science', 'year': 1392}] I grouped the two major and year columns, grouped = (Student.objects .values("major", "year") .annotate(count=Count("id")) .order_by("major", … -
Bonjour comment changer une variable dans settings.Py à partir de l'interface admin de Django aci' de fournir les clefs D'api et de les changer merci [closed]
Bonjour, je voudrais savoir comment changer les variables dans settings.Py avec l'interface admin de Django. Exemple changer les clefs D'api à la volée sans avoir à passer par un éditeur de code/texte. J'ai une piste peut être en passant par un model... Et faire appel à ce model dans settings ... Qu'en pensez vous ? Merci -
django automatic creation of the form from the model
is there a possibility from a model like: class foo(models.Model): a = models.CharField(max_length=64) b = models.ForeignKey(foo2, on_delete=models.CASCADE, blank=True, null=True) c = models.DateField(name='c', blank=True, null=True) d = models.EmailField(name='d') e = models.BooleanField(default=False, name='e') automatically generate a form like: where for all attributes (self-written) an attribute must be in the form. the name parameter could then be the label. class fooform(forms.ModelForm): a = models.CharField(name='a1', max_length=64) b = models.ForeignKey(foo2, name='b1', on_delete=models.CASCADE, blank=True, null=True) c = models.DateField(name='c1', blank=True, null=True) d = models.EmailField(name='d1') e = models.BooleanField(default=False, name='e1') class Meta: model = foo fields = ['a', 'b', 'c', 'd', 'e'] labels = { 'a': 'a1', 'b': 'b1', 'c': 'c1', 'd': 'd1', 'e': 'e1'} I found out that I can run through all attributes attributes = [i for i in dir(foo)] and that the wsgi.py is called with runserver. but I can't find a way to generate an attribute / field in the form for each attribute of the model. -
I find problem in importing django in vscode
PS C:\Users\siruvani\projectsss\sshafeeq> workon try PS C:\Users\siruvani\projectsss\sshafeeq> python manage.py startapp calxx Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main()`enter code here` File "manage.py", line 17, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
Django snackbar like message
What's the best way to have a custom tag with Django messages which disappears after a few seconds This is how I did it I know i am late, but i did it as follows views.py CRITICAL = 50 def my_view(request): messages.add_message(request, CRITICAL, 'A serious error occurred.') messages.html {% if message.level == 50 %} <div class="snackbar">{{message}}</div> </div> {% else %} {{ message }} CSS .snackbar { display: block; min-width: auto; margin-left: auto; background-color: #333; color: #fff; text-align: center; border-radius: 2px; padding: 16px; position: fixed; z-index: 1; left: 74%; bottom: 30px; -webkit-animation: cssAnimation 8s forwards; animation: cssAnimation 8s forwards; } @keyframes cssAnimation { 0% { opacity: 1; } 90% { opacity: 1; } 100% { opacity: 0; } } @-webkit-keyframes cssAnimation { 0% { opacity: 1; } 90% { opacity: 1; } 100% { opacity: 0; } } Tho this works, looking if there's any better way out there -
ModelForm is not rendering on browser
I am creating a form for users to be able to create listings for an auction page however when I click the link from my index page to take me to the create page, i get redirected to the create page but on the browser, the form does not show. INDEX.HTML <p>You can create your first auction here <a href={% url 'create_listing' %}>Add new</a></p> URLS.PY path("create/", views.create_listing, name="create_listing") MODELS.PY from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Auction(models.Model): title = models.CharField(max_length=25) description = models.TextField() current_bid = models.IntegerField(null=False, blank=False) users_bid = models.IntegerField(null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title VIEWS.PY from django.shortcuts import render, redirect from django.template import context from .forms import AuctionForm from .models import User def create_listing(request): form = AuctionForm() if request.method == 'POST': form = AuctionForm(request.POST) if form.is_valid: form.save() return redirect('index') context = {'form': form} return render(request, 'auctions/create-listing.html', context) FORMS.PY from .models import Auction from django.forms import ModelForm class AuctionForm(ModelForm): class Meta: model = Auction fields = ['title', 'description', 'current_bid'] CREATE-LISTING.HTML {% extends "auctions/layout.html" %} {% block content %} <form action="" method="post" class="ui form"> {% csrf_token %} {{form.as_p}} <input type="submit" class="ui button primary teal" value="Submit"> </form> {% endblock %} -
Trying to create an object in Django's database with React using User as foreign key (rest-framework)
I'm trying to register Club with owner (ForeignKey) and name fields via form in React. Everything works untill I submit the form. This gives me 401 Unauthorized error: const onSubmit = (event) => { event.preventDefault(); if (checkExistingClubNames(clubName, clubs)) { const owner = isAuthenticated().user; const name = clubName; createClub({owner, name}) .then((data) => { if (data.name === clubName) { setClubName(''); setNameTaken(false); navigate('/'); } }) .catch((error) => console.log(error)); } else { setNameTaken(true); } } clubName is a text variable from an input form (useState, ofc), checkExistingClubNames(clubName, clubs) just checks if a club with the same name exists, isAuthenticated().user returns currently logged user, nameTaken is just for displaying some text it does not matter in this case. The problem lies within createClub function, at least I think so: export const createClub = (club) => { return fetch('http://127.0.0.1:8000/api/clubs/', { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", }, body: JSON.stringify(club), }) .then((response) => { return response.json(); }) .catch((error) => console.log(error)); }; On the backend part it's just serializer: class ClubSerializer(serializers.ModelSerializer): class Meta: model = Club fields = 'id', 'owner', 'name' And viewset: class ClubViewSet(viewsets.ModelViewSet): queryset = Club.objects.all() serializer_class = ClubSerializer So as I said it gives me 401 Unauthorized error, I use basically the same … -
there is short api of loan calculator python code executed but the value of MonPayment is not showing on front end plzzz check the code below
this is the html file {% csrf_token %} Enter Years Enterest rate Enter Amount <button type='submit' class="btn btn-primary">calculate</button> <input type='text' value="{{MonPayment}}" class="form-control"> </form> my views.py is below def calculator(request): try: if request.method=='POST': year=eval(request.POST.get('year')) print(year) rate=eval(request.POST.get('rate')) print(rate) principal=eval(request.POST.get('Principal')) print(principal) year=year*12 rate=(rate/100)/12 MonPayment=(rate*principal*((1+rate)**year)-1) print(MonPayment) context={''} context={'rates' :'rate', 'years': 'year', 'Principal': 'principal'} except: MonPayment='invalid operation...' return render(request, 'calculator.html',context) -
Custom lookup in Django (filter parameter different type than field type)
I have a simple model in Django. class Books(models.Model): title = models.CharField(max_length=255) page_size = models.IntegerField(null=True) An example instance of this model may look like this: ("Alice's Adventures in Wonderland", 70). I would like to create a lookup which would allow users to filter the books by page sizes in the following form if the user types (inside the filter box) >n Django filter would return only books which have more pages than n, if the user types <n Django filter would return only books with less pages than n. To sum up I would need a lookup __cmp which would be capable of joining the queryset before executing it. So I would like to have an if-else block implemented somewhere inside. filter_param, value = filter_param, filter_value = list(user_filter) if filter_param == ">": qr = Books.objects.filter(page_size__gt=n) else: qr = Books.objects.filter(page_size__lt=n) Is it possible to create a custom lookup which would implement such logic? -
datetimefield only show time in html template
I have a datetime field but in the html code I would like to show only the time, how can I do? I tried {{ data|time }}, {{ value|time:"H:i" }} but nothing views from django.shortcuts import render from .models import Count import datetime # Create your views here. def contatore(request): settaggio = Count.objects.get(attivo = True) data = settaggio.data.strftime("%m %d, %Y %H:%M:%S") context = {'data':data} return render(request, 'count.html', context) models class Count(models.Model): data = models.DateTimeField() html <h5 style="color: #fff">{{ data }}</h5> -
How to dockerize Django project already created in anaconda?
I have a Django application that is already created and running in anaconda, now I want it to be dockerized, can you please help me so that I can dockerize my Django project. -
Custom TruncFunc in Django ORM
I have a Django model with the following structure: class BBPerformance(models.Model): marketcap_change = models.FloatField(verbose_name="marketcap change", null=True, blank=True) bb_change = models.FloatField(verbose_name="bestbuy change", null=True, blank=True) created_at = models.DateTimeField(verbose_name="created at", auto_now_add=True) updated_at = models.DateTimeField(verbose_name="updated at", auto_now=True) I would like to have an Avg aggregate function on objects for every 3 days. for example I write a queryset that do this aggregation for each day or with sth like TruncDay function. queryset = BBPerformance.objects.annotate(day=TruncDay('created_at')).values('day').annotate(marketcap_avg=Avg('marketcap_change'),bb_avg=Avg('bb_change') How can I have a queryset of the aggregated value objects for each 3-days interval with the index of the second day of that interval? -
Want to upload an image using a custom upload image function python djano
This is my custom image upload function def upload_image(file, dir_name, filename): try: target_path = '/static/images/' + dir_name + '/' + filename path = storage.save(target_path, file) return storage.url(path) except Exception as e: print(e) and this is my model class MenuOptions(models.Model): name = models.CharField(max_length=500, null=False) description = models.CharField(max_length=500, null=True) image_url = models.ImageField(upload_to=upload_image()) def __str__(self): return f'{self.name}' I want to upload the image using my upload_image function, and as you can see it is taking 3 parameters file,dir_name, and the file_name. how can I pass these parameters in my model.ImageField() Also, I want to store the image_url to my database as returned by the upload_image function will it store the file in DB or the URL? -
Heroku Django request.POST giving wrong values
I have deployed an app in heroku build using django.In my django views.py iam getting some value using request.POST and storing in a global variable so that i can access that value in another function which is then rendered into the template. Eveything worked fine on devolopment server but when i deployed it on heruko,request.POST is not retriving the correct value. views.py: serv='--' def home(request): global serv if request.method=='POST': dayCheck.clear() serv=request.POST['service'] return HttpResponseRedirect('func') def func(request): global serv #Doing something,does not involve serv return render(request,'index.html',{'service':serv}) When i try to log serv in home() it gives correct value but different value in func and the same is rendered,mostly it will be value which i previously clicked or sometimes it would be just -- as declared. Please help me! Thanks in Advance -
mysql 8 gives error on creating table ( running migrate command in django )
Django3.2 mysql 5.7 I have a model name BlackboardLearnerAssessmentDataTransmissionAudit and its length is 48 characters and it has 1 not null field. On mysql5.7 it is working fine. But when try to upgrade with mysql8+ migrations throws error Identifier name is too long. This model generates following name in mysql8.5 blackboard_blackboardlearnerassessmentdatatransmissionaudit_chk_1 it has 65 characters. mysql8 limit info I have a question what are the possible solutions to fix this issue on mysql8 ?