Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Continue after |truncatechar or break model.TextField() into multiple parts?
Is there a way to chop text into different bits using django? I have a model field that is a TextField(), and I want to output it into a nicely formatted way, based on certain lengths, and if there have been images uploaded an so forth. Is there a way to take this text: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. and chop it into multiple pieces? I want to be able to do something like this: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do <image> eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea <chart> commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat <link> non proident, … -
Django RunTest() missing 2 required positional arguments: 'connection' and 'testSettings'
I'm trying to pass form data on a create_test template to a run_test template but continually get a positional argument error. It's being caused by the form data not actually posting but I'm not entirely sure how to overcome. It would seem if I were to pass parameters through the URLconf path it wouldn't know what it is because it's not stored in the database. Any help would be appreciated: urls.py: urlpatterns = [ path('', views.TestCreate, name='create_test'), path('run_test', views.RunTest, name='run_test',), ] models.py: class ApiGateway(models.Model): name = models.CharField(max_length=50) gatewayip = models.GenericIPAddressField() def __str__(self): return self.name class ChassisIP(models.Model): name = models.CharField(max_length=50) chassisip = models.GenericIPAddressField() def __str__(self): return self.name forms.py: class SiteForm(forms.Form): chassis = ModelChoiceField(queryset=ChassisIP.objects.order_by('name').values_list('chassisip', flat=True).distinct()) class ApiForm(forms.Form): gateway = ModelChoiceField(queryset=ApiGateway.objects.order_by('name').values_list('gatewayip', flat=True).distinct()) views.py: def RunTest(request, connection, testSettings): # RunTest View Code Here def TestCreate(request): if request.method == 'GET': form1 = ApiForm() form2 = SiteForm() return render(request, 'create_test.html', {'form1' : form1, 'form2' : form2} ) else: if request.method == 'POST': testSettings = TestSettings.IxLoadTestSettings() form1 = ApiForm() if form1.is_valid(): testSettings.gatewayServer = form1.cleaned_data['gatewayip'] form2 = SiteForm() if form2.is_valid(): testSettings.chassisList = form2.cleaned_data['chassisip'] connection = RestUtils.getConnection( testSettings.gatewayServer, testSettings.chassisList, ) return render(request, 'create_test.html', connection=connection, testSettings=testSettings ) template: {% block content %} <h1>Test Create Page</h1> <form method='post'> <h2>Select API Gateway</h2> … -
ERROR:root:code for hash md5 was not found. (get this error upon installing django, creating django project and creating app)
I created a virtualenv with python3 -m venv env, activated env and then went to install django with pip install django and it returned the following error(warning?) but did install django: ERROR:root:code for hash md5 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type md5 ERROR:root:code for hash sha1 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type sha1 ERROR:root:code for hash sha224 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type sha224 ERROR:root:code for hash sha256 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type sha256 ERROR:root:code for hash sha384 was not found. Traceback (most recent call last): File … -
Django full calendar
I'm trying to show the data from model in fullcalendar, here is my code: $(document).ready(function () { $('#calendar').fullCalendar({ events: [ {% for i in eventlist %} { title: "{{i.visit_patient_pesel}}", start: "{{i.visit_start}}", end: "{{i.visit_end}}", }, {% endfor %} ] }); }); The problem is that I've got several errors. In this line {% for i in eventlist %} error is: indentifier or string literal or numeric literal expected (error is highlighted just where % is) and after "for" I've got ": or , exected". Can anyone help? -
Django form values not inserted in sqlite3 database tables
I am a newbie in web development using Django. I have created 3 models and correspondingly their forms. Even makemigrations and migrate commands did not report any problem and tables are also created in the SQLite DB file. But still, values are not getting inserted in the DB file. Empty QuerySet is getting received i.e. <QuerySet []>. Could anyone please let me know why values do not get inserted? Thanks in advance. The program snippet:- model.py class User(models.Model): name = models.CharField(max_length=100, default='ABC') password = models.CharField(max_length=50, default='ABC') def __str__(self): print("self.name:", self.name) return self.name class Faculty_Info(models.Model): fid = models.IntegerField(default='123') fname = models.CharField(max_length=50, default="ABC") femail = models.EmailField(max_length=50, default='abc@gmail.com') fcontact = models.IntegerField(default='123') faddress = models.TextField(max_length=50, default='ABC') fsalary = models.IntegerField(default='123') def __str__(self): return self.fname class Student_Info(models.Model): sid = models.IntegerField(default='123') sname = models.CharField(max_length=50, default='ABC') semail = models.EmailField(max_length=50, default='abc@gmail.com') scontact = models.IntegerField(default='123') saddress = models.TextField(max_length=50, default='ABC') def __str__(self): return self.sname views.py def faculty_info_section(request): faculties = Faculty_Info.objects.all() print("faculties", faculties) return render(request, "faculty_info_section.html", {'faculties': faculties}) def add_faculty(request): if request.method == "POST": faculty_form = Faculty_Info_Form(request.POST) print("faculty_form", faculty_form) if faculty_form.is_valid(): try: faculty_form.save() print("faculty_form:", faculty_form) return redirect('/faculty_info_section') except: pass else: faculty_form = Faculty_Info_Form() print("faculty_form_2", faculty_form) return render(request, 'add_faculty.html', {'faculty_form': faculty_form}) faculty_info_section.html {% for faculty in faculties %} <tr> <td>{{ faculty.fid }}</td> <td>{{ … -
"user with this username already exists" in DRF ModelSerializer if not specified explicitly
I'm trying understand why this error occurs even though I know how to resolve. Just trying to understand DRF and Django better. JSON in this format comes from the FE: { "username": "username_here", "password": "password_here" } I have this view: class UserSigninTokenAPIView(APIView): permission_classes = [AllowAny] serializer_class = UserSigninTokenSerializer def post(self, request): data = request.data serializer = UserSigninTokenSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data return Response(new_data, status=HTTP_200_OK) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) Which uses this serializers: class UserSigninTokenSerializer(ModelSerializer): username = CharField() class Meta: model = USERS fields = [ 'username', 'password', 'id' ] def validate(self, data): username = data['username'] password = data['password'] user_qs = USERS.objects.filter(username__iexact=username) if user_qs.exists() and user_qs.count() == 1: user_obj = user_qs.first() password_passes = user_obj.check_password(password) if password_passes: """ A number of checks here I removed to keep this clean, otherwise would just use /api/token/ to get a token. I want user checks to pass before issuing a token, because having the token is what indicates they are logged in successfully. """ token = RefreshToken.for_user(user_obj) return { 'refresh': str(token), 'access': str(token.access_token) } else: Services.user_attempts(user_obj) raise ValidationError({'error': ''' The credentials provided are invalid. <br>Please verify the username and password are correct. '''}) The username = CharField() seems redundant to me. The documentation says: The … -
get user to model from view/form
I created a simple app where you can create poll, after login and see your polls in view. Everything worked fine when i had Question and Choice in separate views and forms but i wanted to make something where user can add forms by clicking button and i wanted to have Question and Choice forms in one view. I'm not very sure how to do it. I found some tutorial for dynamic forms and i came up with that: forms.py class CreateChoiceForm(forms.ModelForm): choice_0 = forms.CharField(required=True) choice_1 = forms.CharField(required=True) class Meta: model = Question fields = ['question_text'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) choice = Choice.objects.filter( question=self.instance ) for i in range(len(choice) + 1): field_name = 'choice_%s' % (i,) self.fields[field_name] = forms.CharField(required=False) try: self.initial[field_name] = choice[i].choice except IndexError: self.initial[field_name] = "" field_name = 'choice_%s' % (i+1,) self.fields[field_name] = forms.CharField(required=False) def save(self, commit=True): question = self.instance question.author = self.request.user question.question_text = self.cleaned_data['question_text'] question.choice_set.all().delete for i in range(2): choice = self.cleaned_data['choice_text'] Choice.objects.create(question=question, choice=choice) def get_interest_fields(self): for field_name in self.fields: if field_name.startswith('choice_'): yield self[field_name] The problem is that now i've got this error when i'm trying to submit my forms: https://i.imgur.com/uw2e8jM.png Environment: Request Method: POST Request URL: http://127.0.0.1:8000/polls/createPoll/ Django Version: 2.2.5 Python Version: 3.6.10 … -
Does a graphene django Endpoint expects a X-Csrftoken and CsrfCookie at the same time?
Using: Django 3.x [ Django-Filters 2.2.0, graphene-django 2.8.0, graphql-relay 2.0.1 ] Vue 2.x [ Vue-Apollo ] I am testing single page vue app´s with Django, GraphQL & Vue-Apollo. If i use csrf_exempt on my view everything works in the frontend. urlpatterns = [ <...> path("graphql", csrf_exempt(GraphQLView.as_view(graphiql=True))), <...> Now i wanted to CSRF protect my request. Within the process of understanding the CSRF protection, i thought all Django GraphQLView needs is to receive the "value" of the X-Csrftoken in the Request Header. So i focused on sending the csrf Value in different ways...via a single view like this path('csrf/', views.csrf), path("graphql", GraphQLView.as_view(graphiql=True)), or by ensure a cookie with ensure_csrf_cookie Afterwards in my ApolloClient i fetch thes Value and send him back with the request Header . This i what Django prints when i send a GraphQL request from a Django-Vue page. Forbidden (CSRF token missing or incorrect.): /graphql Parallel i always test with thegraphiql IDE and these requests still working. I also print everytime the info.context.headers value of my query resolver. {'Content-Length': '400', 'Content-Type': 'application/json', 'Host': 'localhost:7000', 'Connection': 'keep-alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache', 'Accept': 'application/json', 'Sec-Fetch-Dest': 'empty', 'X-Csrftoken': 'dvMXuYfAXowxRGtwSVYQmpNcpGrLSR7RuUnc4IbIarjljxACtaozy3Jgp3YOkMGz', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 … -
Django Form in ListView, error on POST of Form
Im trying to implement a chat-function for my website. In order to do that, i followed the following tutorial: https://channels.readthedocs.io/en/latest/tutorial/ I've then changed the code a little bit in order to implement it. Until here, everything works just fine. Now I want to store the form-data inside of a database, and thats where the problem appears. But first my code: urls.py: from django.urls import path from .views import ChatOverView urlpatterns = [ path('<int:pk>/', ChatOverView.as_view(), name='chat-explicit'), path('', ChatOverView.as_view(), name='chat-home'), ] views.py (theres much code here that is probably not needed for this question, but since i dont know what part of it i can ignore, im just posting the whole file-content): from django.views.generic import ListView from django.views.generic.edit import FormMixin, FormView from django.db.models import Q from django.urls import resolve from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from .models import Message from .forms import MessageRegisterForm class ChatOverView(ListView, FormMixin): model = Message template_name = 'chat/home-chat.html' form_class = MessageRegisterForm success_url = '/thanks/' def form_valid(self, form): form = self.get_form() if form.is_valid(): data = form.cleaned_data return super().form_valid(form) def get_context_data(self, *args, **kwargs): context = super(ChatOverView, self).get_context_data(*args, **kwargs) messages_raw = reversed(Message.objects.filter(Q(sender=self.request.user) | Q(receiver=self.request.user))) messages = {} for mes in messages_raw: # i am receiver if mes.sender != self.request.user: … -
Keeping track of Push Notifications
I've recently implemented push notifications into my Angular app. Everything works as expected. I ask the user for their permission and send the SubscriptionInfo to my django backend, where I store it in a database for actual notifications. The SubscriptionInfo looks something like this: { "endpoint": "https://fcm.googleapis.com/fcm/send/cbx2QC6AGbY:APA91bEjTzUxaBU7j-YN7ReiXV-MD-bmk2pGsp9ZVq4Jj0yuBOhFRrUS9pjz5FMnIvUenVqNpALTh5Hng7HRQpcUNQMFblTLTF7aw-yu1dGqhBOJ-U3IBfnw3hz9hq-TJ4K5f9fHLvjY", "expirationTime": null, "keys": { "p256dh": "BOXYnlKnMkzlMc6xlIjD8OmqVh-YqswZdut2M7zoAspl1UkFeQgSLYZ7eKqKcx6xMsGK7aAguQbcG9FMmlDrDIA=", "auth": "if-YFywyb4g-bFB1hO9WMw==" } } Now during testing, the backend threw an error 410 GONE when sending the subscription (I dont know why, deleting the row in the backend and re-allowing notifications in the frontend fixed the issue), indicating that the subscription is no longer valid and should be deleted. Of course I have to somehow inform the frontend about this, delete the 'local' notification token and re-ask for permission from the user. Informing the frontend is not a problem, however, as one user can have multiple devices (or browsers) to recieve notifications, I have to somehow check in the frontend, which subscription has to be 'renewed'. Therefore, I thought about using some kind of uid (consisting of the browser name, version etc), however, that presents several issues: What if the browser gets updated? The subscription object should not be affected by this, it would still be valid, … -
How do I tell my serializer it's fine for a field to be blank?
Using Django 2.0, Python 3.7, and the django-phonenumber-field (v 4.0.0) module. I have a model with my phone number field, that I don't want to be required ... from phonenumber_field.modelfields import PhoneNumberField ... class Coop(models.Model): name = models.CharField(max_length=250, null=False) type = models.ForeignKey(CoopType, on_delete=None) address = AddressField(on_delete=models.CASCADE) enabled = models.BooleanField(default=True, null=False) phone = PhoneNumberField(null=True) email = models.EmailField(null=True) web_site = models.TextField() I have created this web/maps/views.py file to handle the POST request ... class CoopDetail(APIView): """ Retrieve, update or delete a coop instance. """ def get_object(self, pk): try: return Coop.objects.get(pk=pk) except Coop.DoesNotExist: raise Http404 def get(self, request, pk, format=None): coop = self.get_object(pk) serializer = CoopSerializer(coop) return Response(serializer.data) def put(self, request, pk, format=None): coop = self.get_object(pk) serializer = CoopSerializer(coop, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and then I have this web/maps/serializers.py call ... class CoopSerializer(serializers.ModelSerializer): type = CoopTypeField() address = AddressTypeField() class Meta: model = Coop fields = ['id', 'name', 'type', 'address', 'enabled', 'phone', 'email', 'web_site'] def to_representation(self, instance): rep = super().to_representation(instance) rep['type'] = CoopTypeSerializer(instance.type).data rep['address'] = AddressSerializer(instance.address).data return rep def create(self, validated_data): """ Create and return a new `Snippet` instance, given the validated data. """ return Coop.objects.create(**validated_data) def update(self, instance, validated_data): """ Update and return an existing `Coop` instance, … -
My database already have 20 row but when i save new row they start with id from 1
Curently, I import data to my database table with 20 rows already When I use save() method to that table they start saved data with pk=1 lead to Error And they come true when pk=21 Can anyone help me with this although id column in my model is default I dont overwrite it -
django create client user
I try to call create a client user so i have toc call create_client method from the client model to create a client user, I can create superuser but I don't know how to create client user I really don't understand how it works if someone can explain to me and I will be thankful view.py : def signup(request): form = RegisterForm(request.POST or None) if form.is_valid(): form.save() return render(request, 'accounts/signup.html', {'form': form}) form.py class UserAdminCreationForm(forms.ModelForm): """ A form for creating new users. Includes all the required fields, plus a repeated password. """ password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('email','full_name') def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super(UserAdminCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserAdminChangeForm(forms.ModelForm): """A form for updating users. Includes all the fields on the user, but replaces the password field with admin's password hash display field. """ password = ReadOnlyPasswordHashField() class Meta: model = User fields = ('email','full_name','password', 'active', 'admin') def … -
Sum aggregated value django ORM
I have a very simple database with two classes: class Contact(models.Model): nombre = models.CharField(max_length=50) class Address(models.Model): contact = models.ForeignKey(Contact, on_delete=models.PROTECT, related_name='addresses') quantity = models.FloatField() What I am trying to achieve is to get the sum of quantity grouping by the number of addresses for each contact, so I get the sum of quantity for all contacts that have 0 addresses, the sum of quantity for all contacts that have 1 address and so on. This is what I have tried so far: Contacto.objects.all() \ .annotate(num_contact=Count('nombre')) \ .values('num_contact','addresses__quantity') \ .annotate(sum_quantity=Sum('addresses__quantity')) but no luck, I'm not even sure I can do it with ORM -
Django OnToOne key to parent class given invalid name
My Django 2.2 model (trimmed to include only what I believe are the relevant sections) is as follows: class DataSet(models.Model): name = models.CharField(..) ::: class Meta: abstract = False class SurveyRunDataSet(DataSet): status = models.CharField(..) ::: class Meta: app_label = 'dataset' class RestrictedDataSet(SurveyRunDataSet): date_start = models.DateField(null=True) date_end = models.DateField(null=True) ::: # Spoonfeed DJango with parent link # parent_link = models.OneToOneField('SurveyRunDataSet', parent_link=True, db_column='dataset_ptr'), class Meta: app_label = 'dataset' After clearing all migration files and running "django-admin makemigrations", the relevant classes in the 0001_initial.py file are as follows: operations = [ migrations.CreateModel( name='DataSet', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(..)), ::: ], options={ 'abstract': False, }, ), migrations.CreateModel( name='SurveyRunDataSet', fields=[ ('dataset_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='dataset.DataSet')), ('status', models.CharField(..)), ::: ], bases=('dataset.dataset',), ), migrations.CreateModel( name='RestrictedDataSet', fields=[ ('surveyrundataset_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='dataset.SurveyRunDataSet')), ('date_start', models.DateField(null=True)), ('date_end', models.DateField(null=True)), ::: ], bases=('dataset.surveyrundataset',), ), But when I then run "django-admin migrate", it fails with the error : FieldError: Cannot resolve keyword 'surveyrundataset_ptr' into field. Choices are: dataset_ptr, dataset_ptr_id, datasets, flush_date, id, name, primary_dataset, report, report_id, source_data_set where these field names list all those included in the classes DataSet and SurveyRunDataSet (some omitted above for brevity). I understand Django creates a OneToOneField automatically, and for this … -
JWT access tokens: How to continually regenerate?
As I understand it, a new access token should be generated every time the user makes an API call. My question is about how exactly that access token should be generated. I have an endpoint to do that: api/token/refresh/. Does this mean: a) After every regular API call I make, I make a second call to that endpoint? (Doubling the number of API calls from what it would be without authentication) b) Use one API call (the regular one) and have Python make the second call from Django. Then send back the new access token within the response? c) Other? I am using: Vue.js, Django Rest Framework, and djangorestframework_simplejwt. -
Table doesn't exist after deleting database in Django
I wanted Django database to be rebuilt from scratch and did the following : delete migrations from my apps delete db.sqlite3 from my project folder dropped database create database Now when I try to run makemigrations, I got an error : MySQLdb._exceptions.ProgrammingError: (1146, "Table 'my_db.my_table' doesn't exist") How do I let django know i want to make a brand new database ? -
Django - Ajax call outputting nothing
In my project, I use AJAX to return a message to the user if a form is invalid without them having to refresh their page. I make the AJAX call however the outcome is not what is expected: HTML FORM: <div id="testDiv"> </div> AJAX: $('#signupForm input[type=text]').keyup(function() { var usernameField = $('#usernameField').val(); // Retrieved from SignUpForm in forms.py, and has id of usernameField var emailField = $('#emailField').val(); // Retrieved from SignUpForm in forms.py, and has id of emailField var passwordField = $('#passwordField').val(); // Retrieved from SignUpForm in forms.py, and has id of passwordField var confirmPasswordField = $('confirmPasswordField').val(); // Retrieved from SignUpForm in forms.py, and has id of confirmPasswordField $.ajax({ url: '/users/signupval/', data: { 'usernameField': usernameField, 'emailField': emailField, 'passwordField': passwordField, 'confirmPasswordField': confirmPasswordField, }, dataType: 'json', success: function(data) { $('#testDiv').text(data['message']); console.log("Worked!") }, error: function(err) { console.log(err) } }) }) views.py: def signupval(request): form = SignUpForm(request.GET) if form.is_valid(): usernameField = form.cleaned_data.get('usernameField') emailField = form.cleaned_data.get('emailField') passwordField = form.cleaned_data.get('passwordField') confirmPasswordField = form.cleaned_data.get('confirmPasswordField') if len(usernameField) > 7: return JsonResponse({'message': 'Username field > 7'}) elif len(emailField) > 5: return JsonResponse({'message': 'Email field > 7'}) elif len(passwordField) > 6: return JsonResponse({'message': 'Password field > 7'}) elif len(confirmPasswordField) > 6: return JsonResponse({'message': 'Password field > 7'}) else: return JsonResponse({'error': 'Something … -
Accessing dictionary keyed by object in django template
I am trying to access dict values in my django template. The dict keys are objects. Here is a snippet of my codebase: models.py class ProductCategory(models.Mode): name = models.CharField(max_length=64, blank=False, null=False, unique=True) slug = models.SlugField(blank=False, null=False, unique=True) class Product(models.Model): category = models.ForeignKey(ProductCategory, on_delete = models.CASCADE) # other fields pass def __str__(self): return self.title views.py def index(request): products = Product.objects.all() categorized_products = {} for p in products: prod_category = p.category temp = categorized_products.get(prod_category,[]) temp.append(p) categorized_products[prod_category] = temp context = {'products_dict': categorized_products, 'categories': categorized_products.keys() } return render(request,'product/index.html', context=context) mytemplate.html (relevant snippet) <div class="tab-content"> {% for category in categories %} {% if not forloop.counter0 %} <div class="tab-pane fade in active" id="{{ category.slug }}"> {% else %} <div class="tab-pane fade in" id="{{ category.slug }}"> {% endif %} <div > <h4>{{ category.description }}</h4> <div class="container-fluid"> <div class="row"> <div class="col-md-3" style="border:1px solid red;"> {% for product in products_dict.category %} {{ product }} {% endfor %} When I step through the code with a debugger, I can see that the variable products_dict is a dict and correctly populated by the view. However, when I run the code, the for loop code is not executed. Similarly, when I run the same code I have in views.py in the … -
Pipfile.lock (d67565) out of date, updating to (4f9dd2)
Can somoene explain why i get this error Pipfile.lock (d67565) out of date, updating to (4f9dd2)…when i try to install packages using pipenv .Altoough i have used pipenv install enter image description here -
Can't insert data to the model from a CSV file upload in Django
After I click submit nothing happens, I think because it can't import Mobile from .models so that the from .models import Mobile from forms.py is unused. How to import it so that I can upload a CSV file successfully and insert the data to Mobile model. forms.py looks like this import io import csv from django import forms from .models import Mobile class DataForm(forms.Form): data_file = forms.FileField() def clean_data_file(self): f = self.cleaned_data['data_file'] if f: ext = f.name.split('.')[-1] if ext != 'csv': raise forms.ValidationError('File Type not supported') return f def process_data(self): f = io.TextIOWrapper(self.cleaned_data['data_file'].file) Mobile = csv.DictReader(f) for i in Mobile: Mobile.objects.create_data(i['mobile_owner'], i['mobile_number']) views.py looks like this: from .models import Mobile from django.views.generic import TemplateView from .forms import DataForm from django.views.generic import FormView class DataView(FormView): template_name = 'sms/mobile.html' form_class = DataForm success_url = '/upload/' def form_valid(self, form): form.process.data() return super().form_valid(form) mobile.html looks like this {% extends 'base/base.html' %} {% block title %}Add SMS Data{% endblock title %} {% block scripts %} {% endblock scripts %} {% block content %} <form action="{% url 'mobile' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <label>Upload mobile numbers</label> <input type="file" name="data_file"> <input type="submit" value="submit"> </form> {% endblock content %} urls.py looks like this: from django.urls import path, … -
Key value map between django microservices
I am working on microservice architecture and I need to create a common key value map where I can add key value pairs from 1 service and consume it in another. How can I do this? Is there any package that can already do this? -
Why can't I use @staticmethod here?
I'm using django-fsm to implement a state machine. The code looks like def user_ok_to_check_me( instance, user): ... class Job( models.Model): # ... many screenfulls of code @transition( field=state, target=BOOKING, source=CHECKING, permission=user_ok_to_check_me) def fail_checking(self, **kwargs): ... and it's working. Code readability is impaired by having that little utility function outside the class it belongs with, so I tried class Job( models.Model): # ... many screenfulls of code @staticmethod def user_ok_to_check_me( instance, user): ... @transition( field=state, target=BOOKING, source=CHECKING, permission=user_ok_to_check_me) def fail_checking(self, **kwargs): which does not work. Not sure what user_ok_to_check_me does now do, it behaves like a no-op function always returning True even when all it does is return False Why? And is there any way to declare this little function inside the class? (It's just a little bit too long to use lambda instance, user: ) -
Django - libssl.1.1.dylib library not loading error - Why is this occuring?
I am trying to migrate my changes in my existing Django project to mysql database using command python3 manage.py migrate. I transferred to a new MacBook with Catalina OS and installed everything from scatch. When I try to run the command I keep on getting this error trace stack: Traceback (most recent call last): File "/Users/vincegonzales/Documents/Anteriore/Project Apps/bonggakaday_api/venv/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Users/vincegonzales/Documents/Anteriore/Project Apps/bonggakaday_api/venv/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/vincegonzales/Documents/Anteriore/Project Apps/bonggakaday_api/venv/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so, 2): Library not loaded: libssl.1.1.dylib Referenced from: /Users/vincegonzales/Documents/Anteriore/Project Apps/bonggakaday_api/venv/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-darwin.so Reason: image not found The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/vincegonzales/Documents/Anteriore/Project Apps/bonggakaday_api/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/vincegonzales/Documents/Anteriore/Project Apps/bonggakaday_api/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/Users/vincegonzales/Documents/Anteriore/Project Apps/bonggakaday_api/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/vincegonzales/Documents/Anteriore/Project Apps/bonggakaday_api/venv/lib/python3.7/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Users/vincegonzales/Documents/Anteriore/Project Apps/bonggakaday_api/venv/lib/python3.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, … -
MultiValueDictKeyError at / 'username' - login at mainpage
I'm making a simple homepage with a login system, which redirects user to another page if he's authenticated. I found a tutorial with custom possibility to make a login view but it shows me the above mentioned error. from django.shortcuts import render, redirect, reverse from django.contrib.auth import logout, login, authenticate def main(request): if request.user.is_authenticated: return redirect(reverse('game')) logout(request) username = password = '' if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) redirect(reverse('game')) return render(request, 'game/main.html')