Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to reload Django context from JavaScript w/out redirect?
I am developing a dictionary application and a simple bookmark page where bookmarked definitions are displayed. I am using JavaScript to add/remove a definition to/from bookmarks through a button. The button works. However, when I am on the bookmarks page and I press it to remove a definition from my bookmarks, the definition stays there until I reload the page. I would like the definition to disappear as soon as I hit the button through JavaScript. I tried to remove the parentNode of my button (the div for definition) but it looks horrible, and that's not what I am looking for. I am now trying to send an AJAX request to my Django bookmarks view to re-load the context, but so far I haven't been able to do it. Can anybody help? Here is my Javascript code (the ? is where I am stuck): function toggleBookmark(event) { // Get definition id. let id = event.target.id.split("-")[1]; // Send AJAX request to bookmark view. $.get("/bookmarks/bookmark/" + id, function (data) { if (data.added) { alert('Definition added to your bookmarks.') event.target.innerHTML = 'Remove definition from your Bookmark'; } else if (data.removed) { alert('Definition removed from your bookmarks.') event.target.innerHTML = 'Add definition to your Bookmarks'; … -
sql query don't work in django: "not enough arguments for format string error in django"
I write a SQL query in MySQL and It runs correctly but when I use this query in Django, it runes with error. I delete space of "Title" in the database. When user enter something in the search field, I also delete space in the user text, and then start to search in the database whether the user text contains in title or not. Error: SQL query: Model: # Business (کسب و کار) Model class Business(models.Model): title = models.CharField(verbose_name = 'عنوان', max_length = 255) slug = models.SlugField(verbose_name = 'شناسه', unique = True) FK_CEO = models.ForeignKey(User, verbose_name = 'admin', related_name = 'business_admin_user', on_delete = models.SET_NULL, null = True) description = models.TextField(verbose_name = 'توضیحات', blank = True) createdate = models.DateTimeField(verbose_name = 'تاریخ ثبت', auto_now_add = True) state = models.CharField(verbose_name = 'استان', max_length = 50, blank = True) city = models.CharField(verbose_name = 'شهر', max_length = 50, blank = True) address = models.TextField(verbose_name = 'آدرس', blank = True) FK_Point = models.ManyToManyField('Point', verbose_name = 'امتیازات', related_name = 'business_point', blank = True) FK_Comment = models.ManyToManyField('Comment', verbose_name = 'نظرات', related_name = 'business_comment', blank = True) phone = models.CharField(verbose_name = 'شماره تماس', max_length = 11, blank = True) support_number = models.CharField(verbose_name = 'شماره تماس پشتیبانی', max_length = 11, … -
ValueError: Field 'id' expected a number but got 'choice'
please help when I execute python manage.py migrate I get this error Traceback: (FM) C:\projects\AM\FM\mysite>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, polls, sessions Running migrations: Applying polls.0009_auto_20200914_1002...Traceback (most recent call last): File "C:\projects\AM\FM\lib\site-packages\django\db\models\fields_init_.py", line 1774, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'choice' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\projects\AM\FM\lib\site-packages\django\core\management_init_.py", line 401, in execute_from_command_line utility.execute() File "C:\projects\AM\FM\lib\site-packages\django\core\management_init_.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\projects\AM\FM\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\projects\AM\FM\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\projects\AM\FM\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\projects\AM\FM\lib\site-packages\django\core\management\commands\migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "C:\projects\AM\FM\lib\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 "C:\projects\AM\FM\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\projects\AM\FM\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\projects\AM\FM\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\projects\AM\FM\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards schema_editor.add_field( File "C:\projects\AM\FM\lib\site-packages\django\db\backends\sqlite3\schema.py", line 328, in add_field self.remake_table(model, create_field=field) File "C:\projects\AM\FM\lib\site-packages\django\db\backends\sqlite3\schema.py", line 189, in remake_table self.effective_default(create_field) … -
Creating Login/Logout View Django REST API
My Question is: How to create a Login and Logout View, were the user is able to Login/Logout? I am using DjangoRestFramework-SimpleJWT, The user is able to obtain a JSONWebToken. Thanks. -
Is it possible to pass a list into includes variables with Django?
I'm trying to create a reusable sub template to use on my pages that's something like this: <div> <h1>{{ heading }}</h1> <p>{{ copy }}</p> <ul> {% for list_item in list %} <li>{{ list_item }}</li> {% endfor %} </ul> </div> But, I'm wondering if it's possible to pass a list into the include? Maybe something like this? {% includes 'template.html' with list="['list_item1', 'list_item2']" %} -
Change Django self describing api
I built an api using django which has a user. class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=100) address = models.CharField(max_length=100) phone = models.CharField(validators=[validate_phone_number], max_length=20) I am using ModelViewSet to automatically generate the crud methods. However, I add two new routes which are login and signup: class ClientViewSet(viewsets.ModelViewSet): queryset = models.Kindergarten.objects.all() serializer_class = serializers.KindergartenSerializer @action(detail=False, methods=['POST'], name='signup') def signup(self, request): return self.create(request) @action(detail=False, methods=['POST'], name='login') def login(self, request): serializer = serializers.UserSerializer(data=request.data) username = request.data['email'] raw_password = request.data['password'] user = authenticate(username=username, password=raw_password) login(request, user) return Response(serializer.data) Then I route like this : router = routers.DefaultRouter() router.register(r'client', views.ClientViewSet) My problem is when I open my documentation I get to fill field that I do not need : How can I better customize the self description view ? Thanks ! -
While defining method for autosaving in CreateView for ManyToMany field Error shows
I have three Models, in third models Foreign Key and ManyToMany fields are linked, which are: Personal_info Models.py class Personal_info(models.Model): gen_choices = ( ("पुरुष", "पुरूष"), ("महिला", "महिला"), ("तेस्रो", "तेस्रो"), ) pinfo_id = models.AutoField(primary_key=True) userid = models.OneToOneField(User, on_delete=models.CASCADE) nfullname = models.CharField(validators=[max_len_check], max_length=128) efullname = models.CharField(validators=[max_len_check], max_length=128) dob_ad = models.DateField() dob_bs = models.DateField() gender = models.CharField(max_length=6, choices=gen_choices) citizen_no = models.CharField(max_length=56) cissue_dist = models.ForeignKey(District, on_delete=models.CASCADE) cissue_date = models.DateField() language = models.CharField(max_length=56) p_district = models.CharField(max_length=56) p_vdc = models.CharField(max_length=56) p_ward = models.CharField(max_length=2) p_city = models.CharField(max_length=56) t_district = models.CharField(max_length=56) t_vdc = models.CharField(max_length=59) t_ward = models.CharField(max_length=2) t_city = models.CharField(max_length=56) telephone = models.BigIntegerField(null=True, blank=True) mobile = models.BigIntegerField() mother_name = models.CharField(validators=[max_len_check], max_length=128) mother_cit = models.CharField(max_length=10, null=True) father_name = models.CharField(validators=[max_len_check], max_length=128) father_cit = models.CharField(max_length=10, null=True) gfather_name = models.CharField(validators=[max_len_check], max_length=128) gfather_cit = models.CharField(max_length=10, null=True) spose_name = models.CharField(validators=[max_len_check], max_length=128, null=True) spose_cit = models.CharField(max_length=10, null=True, blank=True) image = models.FileField(upload_to="photos/", null=True, blank=True) cit_image = models.FileField(upload_to="citizens/") inclu_image = models.FileField(upload_to="inclusions/", null=True) active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager def __str__(self): return str(self.efullname) Educational Models.py class Education(models.Model): edu_id = models.AutoField(primary_key=True) userid = models.ForeignKey(User, on_delete=models.CASCADE) institute = models.CharField(max_length=255, validators=[max_len_check]) board = models.CharField(max_length=128, validators=[max_len_check1]) pexam = models.CharField(max_length=16, choices=exam_choices) faculty = models.CharField(max_length=16, choices=fac_choices) division = models.CharField(max_length=16, validators=[max_len_check2]) tmarks = models.IntegerField() percent = models.FloatField(null=True, blank=True) mainsub … -
Crispy Forms: Align dynamically
I add some forms to my page dynamically - I always start with a name field and add multiple others depending on a database entry in the data field: class ProductModelForm(ModelForm): class Meta: model = Product fields = ("name", "data") def __init__(self, user, *args, **kwargs): super(ProductModelForm, self).__init__(*args, **kwargs) user_layouts = models.Layout.objects.filter(user__id=user.id) all_fields = {} self.helper = FormHelper() self.helper.form_method = 'POST' HTML_SAVE = HTML(f"""<button type="submit" name="submit" value="save">save</button>""") NAME_FIELD = Column(Field('name'), css_class='form-row') self.helper.layout = Layout(NAME_FIELD) DATA = Field("data", type="hidden") for i in range(0,n): tmpField = Column(Field( ...), css_class=...) self.helper.layout.append(tmpField) self.helper.layout.append(HTML_SAVE) Now my problem is, that because of using column I get a new line for every entry - but I actually would like the forms to be aligned more space preserving. But I never know which kind of form I add - could be a MultipleChoiceField, a BooleanField or a simple CharField. Is there a way so cripsy will align the forms for me in the page? I could stop using Column but which other field benefits me most? -
django form validation: field error not displayed
I am lost with form validation and the way to display error messages I have a "customized" form display in my template (displayed field by field) I need validation between 2 fields so I should use clean method If the checkbox is ticked, text input can't be empty I would like to bind a error message to my text field but error message is not displayed... forms.py class CreateForm(forms.Form): def __init__(self, request, *args, **kwargs): super(CreateForm, self).__init__(*args, **kwargs) self.fields["bra_00A_act"] = forms.BooleanField(label = "", required = False) self.fields["bra_00A_lib"] = forms.CharField(label = "", required = False) def clean(self): cleaned_data = super(CreateForm, self).clean() if cleaned_data["bra_00A_act"] and cleaned_data["bra_00A_lib"] == "": raise forms.ValidationError('error') return cleaned_data template html <form id="randomization_settings_form" method="POST" class="post-form"> {% csrf_token %} <input id="new_parameters" type="hidden" name="parameters" value=""> {{ form.non_field_errors }} <table id="table_parametrage" class="table table-hover"> <thead> <tr> <th>Bras A</th> <th>-----</th> </tr> <tr> <td colspan="2"> <div class="fieldWrapper"> {{ form.bra_00A_act.errors }} {{ form.bra_00A_act }} {{ form.bra_00A_lib.errors }} {{ form.bra_00A_lib }} </div> </td> </tr> </thead> </table> ... </form> -
Passing model field as a slug to URL
models.py: class Article(models.Model): title = models.CharField('Title', max_length=99) slug = AutoSlugField(max_length=99, populate_from='title', unique=True) view_counter = models.IntegerField(default=0) topic = models.ManyToManyField('Topic', related_name='articles') country = models.ManyToManyField('Country', related_name='country', blank=True) class Country(models.Model): slug = models.CharField(max_length=50) name = models.CharField(max_length=50) urls.py: urlpatterns = [ path('', ArticlesListView, name='articles-list'), path('api/', ArticlesApiView, name='articles-api'), path('<slug:country>/', ArticlesListView2.as_view(), name='articles-list1'), path('nope/<slug:slug>/', ArticleDetailView.as_view(), name='article-detail'), ] views.py: class ArticlesListView2(ListView): model = Topic template_name = 'articles/articles-list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["topics"] = Topic.objects.values() context["countries"] = Country.objects.values() return context I want to pass manytomany model field to url. When I run this code, I get the page, but with a problem. If I write a value that doesn't exist into URL, it doesn't throw error. It shows it as it exist. How can I pass it? Giving slugfield to manytomany field gives error as well. -
django vote system failing
I am Confused. I am trying to set a vote system for a post in a blog. But Django always sums on the vote posive side, /blog/models.py class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') post_pos = models.IntegerField(default=0) post_neg = models.IntegerField(default=0) objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) /blog/urls.py urlpatterns = [ path('', views.PostListView.as_view(), name='post_list'), path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'), path('<int:post_id>/share/',views.post_share, name='post_share'), path('<int:post_id>/',views.positive_post, name='positive_post'), path('<int:post_id>/',views.negative_post, name='negative_post'), ] blog/views.py def positive_post(request,post_id): obj = Post.objects.get(pk=post_id) obj.post_pos += 1 obj.save() print ('positive') return redirect(obj.get_absolute_url()) def negative_post(request,post_id): obj = Post.objects.get(pk=post_id) obj.post_neg += 1 obj.save() print ('negative') return redirect(obj.get_absolute_url()) template: <p> <a href="{% url 'blog:positive_post' post.id %}"> VOTE UP {{ post.post_pos}} </p> <p> <a href="{% url 'blog:negative_post' post.id %}"> VOTE DOWN {{ post.post_neg}} </p> no matter if I click vote up or vote down always sums in obj.post_pos ???????? thanks to those print('positive), and print('negative') of views.py I know it is always … -
XML-RPC API with Django
I'm trying to create an API with Django using xml-rpc protocol. I actually created some basic examples on Python but when implementing them on Django I started to get lots of issues. I'm following this code, I think it's pretty old but I couldn't find any better tutorial My urls.py: urlpatterns = [ path('xml_rpc', views.rpc_handler), ] This is my django views.py: from xmlrpc.server import SimpleXMLRPCDispatcher from django.http import HttpResponse # Create a Dispatcher; this handles the calls and translates info to function maps #dispatcher = SimpleXMLRPCDispatcher() # Python 2.4 dispatcher = SimpleXMLRPCDispatcher() # Python 2.5 @csrf_exempt def rpc_handler(request): if len(request.POST): response = HttpResponse(mimetype="application/xml") response.write(dispatcher._marshaled_dispatch(request.raw_post_data)) else: response = HttpResponse() response.write("<b>This is an XML-RPC Service.</b><br>") response.write("You need to invoke it using an XML-RPC Client!<br>") response.write("The following methods are available:<ul>") methods = dispatcher.system_listMethods() for method in methods: sig = dispatcher.system_methodSignature(method) help = dispatcher.system_methodHelp(method) response.write("<li><b>%s</b>: [%s] %s" % (method, sig, help)) response.write("</ul>") response.write('<a href="http://www.djangoproject.com/"> <img src="http://media.djangoproject.com/img/badges/djangomade124x25_grey.gif" border="0" alt="Made with Django." title="Made with Django."></a>') response['Content-length'] = str(len(response.content)) return response def multiply(a, b): return a*b dispatcher.register_function(multiply, 'multiply') This code actually 'works', I mean, I can access the view if I run the server and I can send the Api request from Python with this code: import … -
Django: Pillow seems to install but is not showing in pip freeze
I'm having problems installing Pillow in a venv on AWS Linux. Pillow seems to install correctly but pip freeze doesn't list it and Django runserver fails claiming that PIL is missing. The following console output shows the problem: [root@ip-172-31-25-228 ichiba]# source venv/bin/activate (venv) [root@ip-172-31-25-228 ichiba]# pip freeze asgiref==3.2.10 Django==3.1.1 django-bootstrap-form==3.4 django-crispy-forms==1.9.2 django-filter==2.3.0 django-rest-framework==0.1.0 djangorestframework==3.11.1 pytz==2020.1 sqlparse==0.3.1 (venv) [root@ip-172-31-25-228 ichiba]# pip install Pillow Collecting Pillow Using cached Pillow-7.2.0-cp36-cp36m-manylinux1_x86_64.whl (2.2 MB) Installing collected packages: Pillow Successfully installed Pillow-7.2.0 (venv) [root@ip-172-31-25-228 ichiba]# pip freeze asgiref==3.2.10 Django==3.1.1 django-bootstrap-form==3.4 django-crispy-forms==1.9.2 django-filter==2.3.0 django-rest-framework==0.1.0 djangorestframework==3.11.1 pytz==2020.1 sqlparse==0.3.1 (venv) [root@ip-172-31-25-228 ichiba]# What am I doing wrong? Thanks and regards...Paul -
How to read a file form a Django model FileField
I have the following model in Django: class Batch(CustomModel): product = models.ForeignKey(Product, verbose_name=_("Producto"), on_delete=models.PROTECT, related_name='batchs') start_date = models.DateField(_("Fecha de Inicio"), auto_now=False, auto_now_add=False) due_date = models.DateField(_("Fecha de Vencimiento"), auto_now=False, auto_now_add=False) states = models.ManyToManyField(State, verbose_name=_("Estados")) source_file = models.FileField(_("Archivo de origen"), upload_to=None, max_length=100) class Meta: verbose_name = _("Lote") verbose_name_plural = _("Lotes") def __str__(self): return "[{}]{}/{}/{}".format(self.id, self.product.id, self.start_date, self.due_date) def save(self, *args, **kwargs): super().save(*args, **kwargs) tokens_string = self.source_file.open() tokens = tokens_string.split('\n') print(tokens) As you can see, in method save() I try to print the content of the file being uploaded to field ' source_file`. This is the file being uploaded: file.txt 867670000460 867670000693 867670001445 867670001519 867670001597 When I do print(tokens), I get a single long string: b'867670000460\r\n867670000693\r\n867670001445\r\n867670001519\r\n867670001597\r\n867670002554' I tried to split the string using tokens_string.split('\n'), but I get this error: File "/Users/hugovillalobos/Documents/Code/cinetogoproject/backend/cinetogo/inventory/models.py", line 37, in save tokens = tokens_string.split('\n') TypeError: a bytes-like object is required, not 'str' How can I get each line of the file separated? -
How to rebuild index in elasticsearch for low-memory instance
I'm trying to run python3 manage.py search_index --rebuild -f on my EC2 small instance (+500,000 documents) but the process gets killed as soon as it starts. I tried changing chunk_size, query_pagination, and parallel_indexing but I always get the same error "Killed" or sometimes I get "Memory Error". My question is how can I run this command in small chunks so it doesn't cause this error? -
How do you link form action to a view method?
In my rendered index.html, I have: <form action="???" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> In my views.py, I have: class weather(base.TemplateView): # Generates the above html def get_hours(request): # do something with request.Post return shortcuts.render(request, "index.html", {"form": form}) How do I make the form action call the get_hours? I want to post to the same page the form is on so the page won't refresh and will display the results on the same page. -
Django request header not in preflight response
my application uses angular for frontend and Django for the backend. The front end is sending data in a custom header called mobile. This are the request-headers from the frontend. Accept: application/json, text/plain, */* code: +1 Content-Type: application/json mobile: 1234678901 Referer: http://localhost:4200/ User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36 But I am getting an error like this. from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field mobile is not allowed by Access-Control-Allow-Headers in preflight response. I have also added the header to the CORS_ALLOW_HEADERS in my settings.py file. My settings.py file has something like this. from corsheaders.defaults import default_headers CORS_ALLOW_HEADERS = default_headers + ( 'mobile' ) But still I am getting the CORS error. What am I missing? Thanks in advance. -
I am trying to save attendance in my Django attendance app but keep getting TypeError, expected string or bytes-like object
I have tried everything. Checked several solutions on this platform, none have worked. Please help!! The error looks like this TypeError at /attendance/student/ expected string or bytes-like object Request Method: POST Request URL: http://127.0.0.1:8000/attendance/student/?reg_class=1 Django Version: 3.1 Exception Type: TypeError Exception Value: expected string or bytes-like object Exception Location: line 75, in parse_date Python Executable: C:\Users\Mrs Onajide\Desktop\school_management_system.venv\Scripts\python.exe Python Version: 3.8.3 My View from django.shortcuts import render, redirect from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .forms import SearchEnrolledStudentForm, AttendanceForm, DateForm from student.models import EnrolledStudent from academic.models import ClassRegistration from .models import StudentAttendance from django.forms.formsets import formset_factory def student_attendance(request): forms = SearchEnrolledStudentForm() class_name = request.GET.get('reg_class', None) if request.method == 'POST': class_info = ClassRegistration.objects.get(id=class_name) student = EnrolledStudent.objects.filter(class_name=class_name) count = student.count() attendance_formset = formset_factory(AttendanceForm, extra=count) formset = attendance_formset(request.POST) date = DateForm(request.POST) list = zip(student,formset) if formset.is_valid(): for form, student in zip(formset,student): mark = form.cleaned_data['mark_attendance'] StudentAttendance.objects.create_attendance(class_info.name, student.roll, mark, date) return redirect('home') My Model from django.db import models from academic.models import ClassRegistration from student.models import EnrolledStudent from django.utils import timezone class AttendanceManager(models.Manager): def create_attendance(self, std_class, std_roll, std_id, datel): std_cls = ClassRegistration.objects.get(name=std_class) std = EnrolledStudent.objects.get(roll=std_roll, class_name=std_cls) std_att = StudentAttendance.objects.create( class_name=std_cls, student = std, status = std_id, date = datel ) return … -
Speed of the django website after deploying it on heroku
I have deployed a django website on herokuapp (using free tier without having to pay anything) for testing.Currently when the site opens it takes a bit more time to open than the time it takes to open on localhost(127.0.0.1:8000).Also the images take a bit more time to load.My concern is that if I upload it on a platform such as digital ocean or linode or aws will I get the website to load in the same time as it is loading on heroku or there will be a better performance . Or is it the problem with the coding that is making it load slower. If that is the case please tell me ways so that I can get my website to load faster. -
I am unable to update two models at the same time in Django Views.py
I already ask questions related to this at How can I update first_name, last_name & email of Django model User and update other field in separate models But I'm not getting a proper solution. That's why I make this question similar to that one. I have pages.views.py: from django.shortcuts import render, redirect from .forms import CreateUserForm from accounts.models import Account from django.contrib import messages def signupPage(request): if request.user.is_authenticated: return redirect('/') else: form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() # focus on this line Account.objects.create(user=user) messages.success(request, 'Signup success. Now, you can login.') return redirect('login') else: messages.warning(request, 'Signup failed. Please, try again.') context = {'form':form} return render(request, 'signup.html', context) Also, I have accounts.models.py: from django.db import models from django.contrib.auth.models import User class Account(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) # This field is used for to update django model User first_name=models.CharField(max_length=30, null=True, blank=False) last_name=models.CharField(max_length=30, null=True, blank=False) email = models.EmailField(max_length=30, null=True, blank=True) profile_photo = models.ImageField(upload_to='profile', null=True) mobile_number = models.PositiveBigIntegerField(null=True) date_of_birth = models.DateField(auto_now_add=False, auto_now=False, null= True) zip_code = models.IntegerField(null=True) address = models.CharField(max_length=225, null=True) website = models.URLField(max_length=100, null=True) bio = models.CharField(max_length=225, null=True) In Accounts.view.py: from django.shortcuts import render, redirect from .forms import AccountForm from .models import Account from … -
Django primary key prefix and length
I am looking to add a custom primary key to my models. Here is what i have so far. ticket_id = models.CharField(max_length=10, primary_key=True, editable=False) I basically want the primary key for each record to look like this, auto-incrementing from 001. AB001 AB002 AB003 AB004 How would I accomplish this? Many Thanks -
Django Session isn't getting updated appropriately
Stumbled upon the error message - The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example. This error is popping up when rendering a django template (narrowed down the error to the line - return render(request, {})). This process involves uploading a file, running view logic, and presenting the results to the user. It worked for a good many files and is throwing this error for one specific file. The view logic involves a bunch of django session updates. Suspected that this error could be due to the huge session size. Ironically though, the size of the session as I checked in the DB is 120 MB, which sounds reasonable. Can you walk me through the possible issues that could have led to this error? Thanks in advance! -
Can't send API Requests from python code hosted on AWS Lightsail instance
I have a django website that is hosted on an AWS Lightsail. I am trying to add in a Speech to text tool in it. I have tried Google Cloud Speech to text as well as Microsoft Azure Speech to text APIs for this purpose and have used sample code from their websites. The code works fine when i'm running it on my localhost, but the same code does not work when hosted on that AWS Lightsail instance. There is no error, the reponse just never comes and the status stays on "pending.." Is there any log i can check for an error? Or is there any additional step required? Thank you in advance. -
Dynamic inheritance from Model
I have a Photo-Model that helps me achieve storing each image as a thumbnail aswell: class Photo(models.Model): image = models.ImageField(upload_to=upload_path, default=default_image) thumbnail = models.ImageField(upload_to=upload_path_2, editable=False, default=default_image_2) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Now I have another Model, lets call it User, which inherits from Photo: class User(Photo): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Now lets say there are multiple classes inheriting from Photo and depending on the inheriting class, I want to set another upload_path and default_image. How Do I achieve that? Can I somehow use the constructor? Thanks in Advance! -
How can I solve this problem in update crud in Django?
Well, I've been trying to solve this problem for days, at the time of performing the update crud, the form doesn't make me valid and the modified records aren't saved. Next I will show you how my code is in each module: views.py def modificarcurso(request,id): curso = Curso.objects.get(id=id) curso = CursoForm(request.POST, instance=curso) if curso.is_valid(): curso.save() return redirect("/mostrarcursos") return render(request, 'mostrarcursos.html', {'curso': curso}) forms.py class CursoForm(forms.ModelForm): class Meta: model = Curso fields=['docente','anio','paralelo','jornada'] models.py class Curso(models.Model): docente= models.ForeignKey(Docente,on_delete=models.CASCADE) anio = models.IntegerField(default=1) paralelo = models.CharField(max_length=1) jornada = models.CharField(max_length=20) user = models.CharField(max_length=100) user_mod = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) estado = models.IntegerField(default=1) # 1 es activo y 2 es eliminado class Meta: db_table ="Cursos" verbose_name ="Curso" verbose_name_plural ="Cursos" def __str__(self): return self.paralelo + ' ' + self.jornada Well, and in the html code the form is created where the records are entered with the name of each field.