Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'posts' in Django
when i run python manage.py makemigrations,no module error found occur, plz help me settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'posts' ] urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from posts.views import index, blog, post urlpatterns = [ path('admin/', admin.site.urls), path('', index), path('blog/', blog), path('post/', post), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) post> models.py from django.db import models from django.contrib.auth import get_user_model # Create your models here. User =get_user_model() class Author(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField() def __str__(self): return self.user.username class Category(models.Model): title = models.CharField(max_length=20) def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=100) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) comment_count = models.IntegerField(default = 0) author = models.ForeignKey(Author, on_delete=models.CASCADE) thumbnail = models.ImageField() categories = models.ManyToManyField(Category) def __str__(self): return self.title (env) C:\Users\Dell\project4\src>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Dell\Envs\env\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Dell\Envs\env\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\Dell\Envs\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Dell\Envs\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Dell\Envs\env\lib\site-packages\django\apps\config.py", line 90, in create module … -
TypeError at /filter Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Int64Index'
my project in weather data is fetch by data base in django framework after that data is convert daily to weekly that web page in error is TypeError at /filter Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Int64Index' '''django view html in fetch `def filter(request): date_min = request.POST.get('date_min','') date_max = request.POST.get('date_max','') qs = weather_data.pdobjects.filter(DATE__range=(date_min,date_max)) df = qs.to_dataframe(fieldnames=['id','DATE','ET','EP','BSS','RF','WD','WD1','WS','DT1','WT1','DT2','WT2','MAXT','MINT','RH11','RH22','VP11','VP11','CLOUDM','CLOUDE','SOIL1','SOIL2','SOIL3','SOIL4','SOIL5','SOIL6','MinTtest','MaxTtest1','MaxTtest2'],index='id') df = df.resample('W').agg({'ET':'sum','EP':'sum','BSS':'sum','RF':'sum','WD':'sum','WD1':'sum','WS':'sum','DT1':'sum','WT1':'sum','DT2':'sum','WT2':'sum','MAXT':'sum','MINT':'sum','RH11':'sum','RH22':'sum','VP11':'sum','VP11':'sum','CLOUDM':'sum','CLOUDE':'sum','SOIL1':'sum','SOIL2':'sum','SOIL3':'sum','SOIL4':'sum','SOIL5':'sum','SOIL6':'sum','MinTtest':'sum','MaxTtest1':'sum','MaxTtest2':'sum'},loffset = pd.offsets.timedelta(days=-6)) return render(request,"reports.html",locals()) ''' {% for data in df %} <td>{{data.ET}}</td> <td>{{data.EP}}</td> {% endfor %} ''' -
Render text from a dictionary/query in Django
When I render my queryset onto my Django template it renders the whole queryset with the curly brackets.Image below I just need value of the dictionary not the key. I'm not sure if it's printing it because the whole queryset is a string. this is my context in my view, I am joining 2 sentences into a list and then trying to render them to the template eng_sentance_flash = model.objects.filter(show_sentance = True).values('sentance_eng')[:1] #limit 1 esp_sentance_flash = model.objects.filter(show_sentance = True).values('sentance_esp')[:1] zip_flash_sentances = list(zip(eng_sentance_flash,esp_sentance_flash)) return render(request, template_name, {'sentances_list': user_sentances,'zip_flash_sentances':zip_flash_sentances}) And here is the code where I am trying to print it to the screen {% for rand in zip_flash_sentances %} <p>{{ rand.0 |safe }}</p> <p>{{ rand.1 |safe }}</p> {% endfor %} And the output looks like this on the screen {'sentance_eng': 'Croagh Patrick is the sacred mountain of Ireland, where St. Patrick is supposed to fast for 44 days when he came to Christianize Ireland in the 5th century'} {'sentance_esp': 'Croagh Patrick es la montaña sagrada de Irlanda, donde se supone que San Patricio ayunó durante 44 días cuando vino a cristianizar Irlanda en el siglo V'} -
TypeError when I run collectatic to save the static in S3 bucket using django
I'm a bit new to django and I'm trying to run collectstatic from the terminal (python manage.py collectstatic) in order to collect the static files in the S3 bucket but I getting the following error: $ python manage.py collectstatic C:\Users\Elena\Desktop\Curso\4th Module\ecommerce2.venv\lib\site-packages\storages\backends\s3boto3.py:282: UserWarning: The default behavior of S3Boto3Storage is insecure and will change in django-storages 2.0. By default files and new buckets are saved with an ACL of 'public-read' (globally publicly readable). Version 2.0 will default to using the bucket's ACL. To opt into the new behavior set AWS_DEFAULT_ACL = None, otherwise to silence this warning explicitly set AWS_DEFAULT_ACL. "The default behavior of S3Boto3Storage is insecure and will change " You have requested to collect static files at the destination location as specified in your settings. This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\Elena\Desktop\Curso\4th Module\ecommerce2.venv\lib\site-packages\django\core\management__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\Elena\Desktop\Curso\4th Module\ecommerce2.venv\lib\site-packages\django\core\management__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Elena\Desktop\Curso\4th Module\ecommerce2.venv\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Elena\Desktop\Curso\4th Module\ecommerce2.venv\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Users\Elena\Desktop\Curso\4th Module\ecommerce2.venv\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 199, in … -
how to display foreign key values instead of its ID
how to display foreign key value instead of its ID models.py class Product(models.Model): product_name = models.CharField(unique=True, max_length=50) pass def __str__(self): return self.product_name class Order(models.Model): id = models.AutoField(primary_key = True) products = models.ManyToManyField(Product ,through='ProductOrder') pass def __str__(self): return str(self.products.all()) class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) ordering = models.ForeignKey(Order, on_delete=models.CASCADE,blank=True,null=True) pass def __str__(self): return str(self.product) my views.py class ListOfOrder(ListView): template_name = 'order/product_group.html' context_object_name = 'productss' def get_queryset(self): return ProductOrder.objects.all() show.html {% for product in productss %} <tr class=""> <td style="text-align: center;">{{ product.product }}</td> {% endfor %} and also tried this <td style="text-align: center;">{{ product.product.product_name }}</td> is there a way to achieve this goal? thanks for any advice ! -
NoReverseMatch for user profile view
I need two different views for the user: a view user_details, it show the details of model User; a view user_profile, it show the details of model UserProfile models.py from django.contrib.auth.models import User from django.db import models from django.urls import reverse class UserProfile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, related_name='profile_user', ) many_other_fields.... views.py from django.contrib.auth.models import User from django.shortcuts import get_object_or_404, HttpResponseRedirect, redirect, render from .models import UserProfile def user_details(request, username): user_details = get_object_or_404(User, username=username) template = 'usermanager/reading/user_details.html' context = { 'user': user_details, } return render(request, template, context) def user_profile(request, username): profile = get_object_or_404(UserProfile, username=profile_user.username) template = 'usermanager/reading/user_profile.html' context = { 'user_profile': profile, } return render(request, template, context) urls.py path('account-manager/<username>/', views.user_details, name="user_details"), path('account-manager/<username>/profile/', views.user_profile, name="user_profile"), template.html <a href="{% url 'user_details' username=user.username %}">User Details</a> <a href="{% url 'user_profile' username=userprofile.profile_user.username %}">User Profile</a> With this approach I see the error below: NoReverseMatch at /account-manager/max/ Reverse for 'user_profile' with keyword arguments '{'username': ''}' not found. 1 pattern(s) tried: ['account\-manager\/(?P[^/]+)\/profile\/$'] How I can solve this problem? Can you suggest me another approach? -
Django, is it mandatory to have USERNAME_FIELD?
One type of user authenticate with phone number Another type of user authenticate with email. So some users don't have phone, and some don't have email. Can I specify USERNAME_FIELD to be id ? or don't have it at all? -
django-elasticsearch-dsl Mapping for completion suggest field not working
This problem has been driving me crazy for days with not solution. I create a document as follows from my django model. from django_elasticsearch_dsl import fields @registry.register_document class QuestionDocument(Document): complete = fields.CompletionField(attr='title') class Index: name = 'questions' class Django: model = QuestionModel fields = ['text', 'title'] Now i want to perform a completion query like this: matched_questions = list(QuestionDocument.search().suggest("suggestions", word, completion={'field': 'complete'}).execute()) But i keep getting the following error: elasticsearch.exceptions.RequestError: RequestError(400, 'search_phase_execution_exception', 'Field [complete] is not a completion suggest field') I think the problem is that The mapping for this field is not created correctly, but i don't know how to fix it. Can anybody help with this it is literally driving me crazy. -
Why can i use requests in Python shell but i get the error no module found in Django?
I get the error module not found when trying to import requests in Django. I cannot get python module requests to work in Django. I have installed the module using pip in python and can import in the python terminal. ModuleNotFoundError: No module named 'requests' if I run the commands in python shell: import requests test = requests.get(url="http://192.168.9.186:2480/connect/test") i get a htto 204 response but in django I just get the module error -
Django DATE_FORMAT weekday name
I want to format date object in Django. Specifically, I want to use DATE_FORMAT in settings.py. Using Django Documentation, I set it as: DATE_FORMAT = 'l, m F Y'. Lowercase l means weekday name. In the template I use {{ value|date:"DATE_FORMAT" }}, but it never renders the weekday name. If I do the: {{ value|date:"l, m F Y" }}, I get the results expected. Are there any limitations which built-in date filters are allowed in settings.py? Thank you! -
How to paginate bootstrap cards with django
I am getting my query results based on user selection and showing them on bootstrap cards in django. I am using django Paginator to display at max 6 results per page (currently set to 1 for testing). The problem is my Paginator is showing all the results on all the pagination pages. Could someone please help me?? View: def results(request): results = [] query_city = request.GET.get('city') print(query_city) all_records = hotel.objects.all() for states in all_records: if states.confirm_approval and states.space_state == query_city: print(states) results.append(states) paginator = Paginator(results,1) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) index = items.number - 1 max_index = len(paginator.page_range) start_index = index - 5 if index >= 5 else 0 end_index = index + 5 if index <= max_index - 5 else max_index page_range = paginator.page_range[start_index:end_index] context = { 'results':results, 'items':items, 'page_range':page_range, } return render(request, 'results/results.html', context) Html Template: % for result in results %} {% if forloop.counter0|divisibleby:3 %} <div class="row"> {% endif %} <div class="col"> <div class="card-deck" id="cardholder"> <div class="card" style="max-width: 20rem;"> <img class="card-img-top" src="{% static 'mainpage/img/bg/books.jpg' %}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ result.hotel_name }}</h5> </div> <div class="card-footer"> <a href="#" class="btn btn-primary">Show more</a> </div> </div> </div> … -
How do you call a javaScript function inside a Django template?
I want to call the javaScript function defined inside the same template in Django. How can I do it? {% extends 'base.html' %} {% block content %} {% if error %} showAlert() {% endif %} <script> function showAlert() {alert ("Please select at least one option");}</script> {% endblock %} I want to call showAlert() if there is error present. I have handled the error in the view. I do not a method about how to call the function here? It is showing the function name. -
django-rest-auth "userprofile with this email address already exists." in login
I'm using django rest auth for auth in my rest api. I use custom user model with no username field. So, I've to use custom login serializer. But when I log in, django rest auth says "userprofile with this email address already exists.". How to solve this problem? my settings: REST_USE_JWT = True REST_AUTH_SERIALIZERS = { 'LOGIN_SERIALIZER': 'accounts.api.serializers.RestAuthLoginSerializer', 'REGISTER_SERIALIZER': 'accounts.api.serializers.RestAuthRegisterSerializer', } ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USER_MODEL_USERNAME_FIELD = 'email' ACCOUNT_USERNAME_REQUIRED = False serializers.py from rest_framework import serializers from accounts.models import UserProfile class RestAuthLoginSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('email', 'password') class RestAuthRegisterSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('email', 'password', 'first_name', 'last_name', 'business_name', 'is_business_account') models.py class UserProfile(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True, null=True) last_name = models.CharField(_('last name'), max_length=30, blank=True, null=True) avatar = models.ImageField(upload_to='avatars/', null=True, blank=True) # business profile related data business_name = models.CharField(_('business name'), max_length=30, blank=True, null=True) business_phone = models.CharField(_('business phone'), max_length=20, blank=True, null=True) is_business_account = models.BooleanField(verbose_name=_("is business account"), default=False) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_active = models.BooleanField(_('active'), default=True) is_admin = models.BooleanField(_('staff status'), default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] -
Django: One function, two class-based views
I am currently struggling to find a better solution for get_survey_state(self, context). It is in both CBVs and I think there is a better solution than mine. Can you advise me on that? views.py class SurveyExpectations(AdminPermissionRequiredMixin, TemplateView): template_name = 'admin/surveys/expectations.html' def get_survey_state(self, context): survey = self.request.event.surveys.active_pre_event().first() answers = Answer.objects.filter(question__survey=survey).exists() context['survey_is_active'] = survey context['answers_exist'] = answers def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) self.get_survey_state(context) context['questions_and_answers'] = self.request.event.surveys.get_results( settings.SURVEY_PRE_EVENT ) return context class SurveyFeedback(AdminPermissionRequiredMixin, TemplateView): template_name = 'admin/surveys/feedback.html' def get_net_promoter_score(self) -> float: [...] return netpromoterscore(scores) def get_average_age(self) -> int: [...] return int(answers['avg']) if answers['avg'] else None def get_survey_state(self, context): survey = self.request.event.surveys.active_post_event().first() answers = Answer.objects.filter(question__survey=survey).exists() context['survey_is_active'] = survey context['answers_exist'] = answers def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) self.get_survey_state(context) context['questions_and_answers'] = self.request.event.surveys.get_results( settings.SURVEY_POST_EVENT ) context['netpromoterscore'] = self.get_net_promoter_score() context['average_age'] = self.get_average_age() return context models.py class SurveyQuerySet(models.QuerySet): def active_pre_event(self): return self.filter(is_active=True, template=settings.SURVEY_PRE_EVENT) def active_post_event(self): return self.filter(is_active=True, template=settings.SURVEY_POST_EVENT) def get_results(self, template): return ( self.get(template=template) .questions.exclude(focus=QuestionFocus.EMAIL) .all() .prefetch_related('answers') ) class Survey(TimeStampedModel): id = models.UUIDField([...]) is_active = models.BooleanField([...]) template = models.CharField([...]) objects = SurveyQuerySet.as_manager() -
Serializers - one to many relation with user limit input
I have a problem with drf. I have device serializer: from rest_framework import serializers from smarthome.models import Device class DeviceSerializer(serializers.Serializer): id = serializers.ReadOnlyField() name = serializers.CharField(max_length=80) address = serializers.CharField(max_length=17) def create(self, validated_data): return Device.objects.create(**validated_data) def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.address = validated_data.get('address', instance.address) instance.save() return instance Also, i have result serializer: from rest_framework import serializers from smarthome.models import Result from smarthome.models import Device class ResultSerializer(serializers.Serializer): temperature = serializers.CharField(max_length=80) moisture = serializers.CharField(max_length=80) light = serializers.CharField(max_length=80) conductivity = serializers.CharField(max_length=80) battery = serializers.CharField(max_length=80) date = serializers.ReadOnlyField() device = serializers.PrimaryKeyRelatedField(queryset=Device.objects.all()) def create(self, validated_data): print(validated_data) return Result.objects.create(**validated_data) I dont know how to add device results to device serializer. Also i want to have possibility to use limit send from user to limit number of results in response. There is my models: class Device(models.Model): name = models.CharField(max_length=80) address = models.CharField(max_length=17) class Result(models.Model): temperature = models.CharField(max_length=80) moisture = models.CharField(max_length=80) light = models.CharField(max_length=80) conductivity = models.CharField(max_length=80) battery = models.CharField(max_length=80) date = models.DateTimeField(auto_now_add=True) device = models.ForeignKey('Device', related_name='statuses', on_delete=models.CASCADE) Now, in response i got: { "id": 1, "name": "name", "address": "c4:7c:8d:6a:fb:27" } i want something like this: { "id": 1, "name": "name", "address": "c4:7c:8d:6a:fb:27", "results": { { "temperature": "21.5", "moisture": "61", ... }, { ... } } … -
QuerySet is empty when try to get User from multiple databases
I have a project with multiple databases. I'm trying to fetch all users from one of databases like this: users = User.objects.using('mydb').all() or this: users = User.objects.db_manager('mydb').all() but get an empty query list instead. <QuerySet [<User: >]> I've test this with some other models but they are working grate. Also when I've get the count of my records, return the correct number of records. Am I doing wrong? -
How to correclty setup Django Rest Framework social login and register, alongside local auth with jwt
I have to create API endpoints for user login and registration with facebook, twitter and local auth. I also want to connect social accounts with local one. Have used django-rest-auth and different packages and most of them are garbage. For example, django-rest-auth has issues with custom login serializers etc. How should it be done without writing messy code and without use of "bugfull" packages? -
Problem Using Bootstrap Navbar With For Loop In Template
Now I am trying to create a navbar for each intern profile in my website. To do that I used for loop and tried to create profiles as dynamically. The main issue is when clicking on tabs, every tab opens first models instances. As you understand only first model tabs work correctly I have tried to change href property of tabs but It does not work <!--Code part for calling tabs --> {% for intern in all_interns %} ....some part of codes before... <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a class="nav-link active" style="margin-bottom: 5px" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true" >Kişisel Bilgiler</a> </li> <li class="nav-item"> <a class="nav-link" id="profile-tab" data-toggle="tab" href="#profile" role="tab" aria-controls="profile" aria-selected="false">İş Bilgileri</a> </li> ...some part of codes after... {% endfor %} <!--Code part for each tabs --> <div class="col-md-8"> <div class="tab-content profile-tab" id="myTabContent"> <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab"> "<div class="row"> <div class="col-md-6"> <label>Kullanıcı Adı</label> </div> <div class="col-md-6"> <p>{{ intern.user.username }}</p> </div> </div> <div class="row"> <div class="col-md-6"> <label>Şehir</label> </div> <div class="col-md-6"> <p>{{ intern.user.city }}</p> </div> </div> <div class="row"> <div class="col-md-6"> <label>Üniversite</label> </div> <div class="col-md-6"> <p>{{ intern.university }}</p> </div> </div> <div class="row"> <div class="col-md-6"> <label>Cinsiyet</label> </div> <div class="col-md-6"> {% if intern.user.gender == "Male" %} <p>Erkek</p> {% … -
How to Send Single request using ajax inside a loop
I create a simple mailer for our updates into client emails, But how can I send the data one by one and process each data on server side html: <p class="response"></p> <form id="send_updates"> {% csrf_token %} <textarea name="mail-list" class="mails" id="mails"></textarea> <button type="submit"> start sends </button> </form> javascript: let mails = $('#mails').val().split('\n'); for(let i = 0; i <= cc.length; i++){ $.ajax({ cache: false, type: 'post', url: "{% url 'send_mail' %}", data: {'email': mails[i]}, async: true, beforeSend:function(xhr, settings){ xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}"); }; success: function(data){ if (data.success) == true{ $('.response').append(mails[i] + ' sent!') }else{ $('.response').append(mails[i] + ' not sent!') }; } }); BUT! It Sends All Request without waiting if it Success or Not! -
ValueError: save() prohibited to prevent data loss due to unsaved related object form - Create model with form obj as fk
I try to do the following class CaseCreateView(BSModalCreateView): template_name = 'orders/create_case_modal.html' form_class = NewCaseModal success_message = 'Success: Case was created.' success_url = reverse_lazy('scan_to_cart') def form_valid(self, form): case_num = random_string_generator() obj = form.save(commit=False) obj.user = self.request.user obj.case_number = case_num mess_obj = MessageEntry.objects.create(user=obj.user, message_fk=obj, mess_obj=obj.initial_memo) return super(CaseCreateView, self).form_valid(form) Which gives me the following error. ValueError: save() prohibited to prevent data loss due to unsaved related object 'message_fk'. This is a bootstrap_modal_forms window where I save a form. I want to create an object with a FK field (message_fk) hooked to the form obj. I can't save() the obj before assign it to the message_fk, because in that case the form saves twice. (don't know why) I never worked with class based views before and can't find a way to do this properly. -
How to prevent creating new object for existing ones when editing in inlineformset?
While editing a record in inline formset, after the submission new objects is created for existing ones also(duplicates). How to prevent that? I deleted the all objects in the model and reinserted it after checking is_valid(). Everything works fine but media files is not getting saved. views.py def edit_frm(request,id): ob = DynamicMain.objects.get(id=id) if request.method == 'POST': formsety = DocumentsUploadFormset(request.POST,request.FILES, prefix='formsety') formsetz = DocumentsDownloadFormset(request.POST,request.FILES, prefix='formsetz') if formsety.is_valid() and formsetz.is_valid(): del_up_ob = DocumentsUpload.objects.filter(title=ob).delete() #delete all objects del_dwn_ob = DocumentsDownload.objects.filter(title=ob).delete() for i in formsety: name = i.cleaned_data.get('name') mandatory = i.cleaned_data.get('mandatory') types_doc = i.cleaned_data.get('types_doc') location = i.cleaned_data.get('location') DocumentsUpload( title=ob, name=name, mandatory=mandatory, types_doc=types_doc, location=location, ).save() for i in formsetz: name = i.cleaned_data.get('name') mandatory = i.cleaned_data.get('mandatory') types_doc = i.cleaned_data.get('types_doc') location = i.cleaned_data.get('location') DocumentsDownload( title=ob, name=name, mandatory=mandatory, types_doc=types_doc, location=location, ).save() return redirect('app-admin:home') uploadformset = inlineformset_factory(DynamicMain, DocumentsUpload,extra=0,fields=('name','mandatory')) downloadformset = inlineformset_factory(DynamicMain, DocumentsDownload,extra=0, fields=('name','mandatory','types_doc')) formsety = uploadformset(prefix='formsety',instance=ob) formsetz = downloadformset(prefix='formsetz',instance=ob) context = { 'formsety' : formsety, 'formsetz' : formsetz, } return render(request,'app/edit_form.html', context) edit_form.html <h3>Upload</h3> <br> <div class="content formElements add_item_container six formsety hide_add_button"> <table cellpadding="0" cellspacing="0" class="table"> <tr> <th>Name</th> <th>Mandatory</th> </tr> {% for f in formsety.forms %} <tr class="form_up"> <td> <span class="p5name1"> {{ f.name }} </span> </td> <td> <span class="p5name1"> {{ f.mandatory }} </span> </td> <td>{% if f.instance.pk %}{{ f.DELETE … -
Django server and android not communicating correctly
Django Server and Android are not communicating correctly. In the test code, the onMassage method executes correctly when the websocket.send () method is executed. But if you change the url, after onOpen () is executed, it goes directly to onClose () without going through onMassage (). import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.WebSocket; import okhttp3.WebSocketListener; import okhttp3.logging.HttpLoggingInterceptor; import okio.ByteString; public class MainActivity extends AppCompatActivity { private Button start; private TextView output; private OkHttpClient client; private final class EchoWebSocketListener extends WebSocketListener { private static final int NORMAL_CLOSURE_STATUS = 1000; @Override public void onOpen(WebSocket webSocket, Response response) { webSocket.send("Hello, it's SSaurel !"); webSocket.send("What's up ?"); webSocket.send(ByteString.decodeHex("deadbeef")); webSocket.close(NORMAL_CLOSURE_STATUS, "Goodbye !"); } @Override public void onMessage(WebSocket webSocket, String text) { Log.e("asd", "on message"); output("Receiving : " + text); } @Override public void onMessage(WebSocket webSocket, ByteString bytes) { Log.e("asd", "on message"); output("Receiving bytes : " + bytes.hex()); } @Override public void onClosing(WebSocket webSocket, int code, String reason) { Log.e("asd", "on closing"); webSocket.close(NORMAL_CLOSURE_STATUS, null); output("Closing : " + code + " / " + reason); } @Override public void onFailure(WebSocket webSocket, Throwable t, Response response) { Log.e("asd", "on fail"); output("Error : " + … -
Django: presave signal to get file extension in Model
In Django, for file field, its possible to use callable for example user_directory_path in the code below. def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename) class MyModel(models.Model): upload = models.FileField(upload_to=user_directory_path) extension = models.CharField(max_length=100, null=False, blank=False, default=get_filename_ext) However, for the extension field I want to use the get_filename_ext function so that extension of the file gets saved. def get_filename_ext(filepath): base_name = os.path.basename(filepath) name, ext = os.path.splitext(base_name) return name, ext Is there something similar in Django model? Or do I have to do this in Django view? -
How to pass selected value from one form to another without storing
I'm trying to send selected value from one form to another, then take that value as an int and use in a loop VIEW: def Base(request, *args, **kwargs): template_name = 'Base.html' odd = [1, 3, 5, 7, 9] form = Base_form(request.POST) if request.method == 'POST': if form.is_valid(): no_of = request.POST.get('odd') return HttpResponseRedirect("loopthru.html") return render(request, template_name, {'odd': odd}) def loopthru(request, *args, **kwargs): template_name = 'loopthru.html' print(request.POST.get('odd')) form = P2_NexusLeafPair_form(request.POST or None) ... How to pass the value from one form to another and then ran the function loopthru automatic and render the html data. -
Error while accessing request.session['key'] inside forms. [using CheckboxSelectMultiple]
I have two forms named GoodAtForm and PaidForForm. What these do is as follows... GoodAtForm Takes an input from a list in request.session['love'] and presents it to the user. Then user is presented with a CheckboXSelectMultiple fields so that users can select. After The form is submitted in the view, the user choices are then stored inside another list request.session['good']. 4.Another Form named PaidForForm uses that list for further asking of questions from users using CheckBocSelectMultiple and the selections are from the list ```request.session['good']. My problem is that I am unable to access output data inside the Forms to provide it to view. Input is working fine when initialised. My forms renders from the given list but the problem is that Form is not providing output. It says 'QueryDict' object has no attribute 'session' This is my GoodAtForm class GoodAtForm(forms.Form): def __init__(self, request, *args, **kwargs): super(GoodAtForm, self).__init__(*args, **kwargs) input_list = request.session['love'] self.fields['good'] = forms.MultipleChoiceField( label="Select Things You are Good At", choices=[(c, c) for c in input_list], widget=forms.CheckboxSelectMultiple ) View For the GoodAtForm def show_good_at(request): if request.method == 'POST': form = GoodAtForm(request.POST) #it is showing problem here. Throws an exception here if form.is_valid(): if not request.session.get('good'): request.session['good'] = [] request.session['good'] = …