Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django API status code 200 but data is not updating in Database
I am Using Django framework to create an Update-API. I have used Pymongo library, I am making a POST request from my react app using Axios, The response shows a status code of 200, but there is no change in the database. Points to Note: *The API works fine with POSTMAN. *I have written the same API in flask which works well. * I am working with other POST requests too in Django like /signup which works well. -
Wanted to implement action Buttons in the Table using Modal
I'am trying to implement action buttons into a html table. Each row action button should open a same modal but with different content according to the table row where it has been triggered. The table data is got from the database and is sent to html with django in JSON format. I'm new to web development tried searching for solution everywhere but could'nt find one working for me. Please help. HTML: <table id="company1" class="table table-striped table-bordered no-wrap" style="width:100%;"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Email</th> <th>Mobile No.</th> <th>Address</th> <th>Status</th> <th>Actions</th> </tr> </thead> <tbody> {%for customer in customer_data%} <tr> <td class="kt-datatable__cell"> <span style="width: 130px;"> <div class="kt-user-card-v2"> <div class="kt-user-card-v2__details"> <a class="kt-user-card-v2__name" href="javascript:;"> {{customer.company_name}} </a> <span class="kt-user-card-v2__desc"> Creates Limitless steel </span> </div> </div> </span> </td> <td>{{customer.company_name}}</td> <td>{{customer.customer_email}}</td> <td>{{customer.mobile}}</td> <td>{{customer.address_customer}}</td> <td> <label class="input-toggle"> <input type="checkbox" class="statuschange"> <span></span> </label> </td> <td> <span data-toggle="tooltip" data-placement="top" title="View Company Details"> <a href="javascript:;" data-toggle="modal" data-id={{forloop.counter}} data-target="#viewCompanyModal"> <i class="fas fa-eye mr-1"></i> </a> </span> </td> </tr> {%endfor%} </tbody> </table> Model: <div id="viewCompanyModal" tabindex="-1" role="dialog" aria-labelledby="viewCompanyModalLabel" aria-hidden="true" class="modal fade text-left"> <div role="document" class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <div class="kt-user-card-v2"> <div class="kt-user-card-v2__pic"> <img alt="photo" src="/../static/assets/img/3.png"> </div> <div class="kt-user-card-v2__details"> <a id="vcmname" class="kt-user-card-v2__name" href="javascript:;"> Nexa </a> <span class="kt-user-card-v2__desc"> Creates Limitless possibilities </span> </div> </div> <button type="button" data-dismiss="modal" … -
AttributeError: __name__ while importing pandas in django
I have installed Django pandas but while importing in views.py it is throwing attribute error. Could someone help me out? error snippet -
How to send specific data from form with POST request in AJAX?
So i am currently working on one project that form contains two submit button. form contain 3 field(contact number, contact name, message) and two button(search , send). after send button click i just want to send contact_number field and message field with ajax post request . but it's send all field with ajax request. Can you help me how to send specific field data with ajax post request. form image ajax script var KTLoginGeneral = function () { // var success= $('#success'); // var error = $('#fail'); var handleSignInFormSubmit = function () { $('#send_msg_submit').click(function (e) { e.preventDefault(); var btn = $(this); var form = $(this).closest('form'); console.log("send submit"); form.validate({ rules: { number: { required: true, }, message: { required: true } } }); if (!form.valid()) { return; } btn.addClass('kt-spinner kt-spinner--right kt-spinner--sm kt-spinner--light').attr('disabled', true); form.ajaxSubmit({ type: 'POST', url: 'msg/single', data: { number: $('#number').val(), message: $('#message').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, success: function (response, status, xhr, $form) { // similate 2s dela console.log(response); var result = response['success']; if (result) { btn.removeClass('kt-spinner kt-spinner--right kt-spinner--sm kt-spinner--light').attr('disabled', false); error.hide(); success.show(); success.text(response['error_msg']); $('#message_form').resetForm(); } else { console.log("else error"); success.hide(); error.show(); error.text(response['error_msg']); setTimeout(function () { btn.removeClass('kt-spinner kt-spinner--right kt-spinner--sm kt-spinner--light').attr('disabled', false); }, 2000); } }, error(response, e) { btn.removeClass('kt-spinner kt-spinner--right kt-spinner--sm … -
Authorization header is stripped down in put request from browser but working fine in Postman
Mine Authorization token in getting stripped down from request from browser(reactjs using axios) to Django server and hence getting 401(unauthorized) but the same request is working fine with the postman. code for the request const config = { headers:{ 'Content-Type': 'application/json', 'Authorization': `Token ${localStorage.token}` } } console.log(config.headers.Authorization) console.log(localStorage.token) axios.put('http://localhost:8000/user-registration/', config).then( res => { console.log(res.status) } ) } Djnago method class UserRegistrationEvent(APIView): permission_classes = (IsAuthenticated,) authentication_classes = (TokenAuthentication, ) def get_object(self, username): try: return User.objects.get(username = username) except MyUser.DoesNotExist: raise Http404 def put(self, request, format=None): print(request.headers) User = self.get_object(request.user) serializer = UserRegistrationEventSerializer(User, data=request.headers) if serializer.is_valid(): serializer.save() return Response({'alert': 'registration successful'}) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) as in the method i used print method to find out the headers(for debugging i removed the permission class). CORS setting is not a problem -
How to properly use filter method with foreign key in django details view with multiple models
I have two model one model is being used for storing the blog posts and another model is being used for taking the ratings and comments. Below are two my models # Models Code class Products(models.Model): name = models.CharField(max_length=50) img = models.ImageField(upload_to='productImage') CATEGORY = ( ('Snacks','Snacks'), ('Juice','Juice'), ) category = models.CharField(max_length=50, choices=CATEGORY) description = models.TextField() price = models.FloatField() review = models.TextField() # Rating Model class Rating(models.Model): product = models.ForeignKey(Products, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) stars = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)]) comment = models.TextField() #Views Code class ProductListView(ListView): model = Products template_name = 'products.html' context_object_name ='Products' class ProductDetailView(DetailView): model = Products def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) context['Rating'] = Rating.objects.filter(self.product_id) # How can i get the comments only for that specific product? return context In details-view how should I filter to fetch the comments for that specific product only ? -
Django forms with variable "required" fields
I have a multi-tenant app where each "tenant" (Company model object) have multiple clients. Each tenant may set up which required fields they need for their app. class Client(models.Model): """ Client information """ company = models.ForeignKey(Company, blank=True, null=True, default=1, on_delete=models.SET_NULL) name = models.CharField(max_length=150, blank=True) email = models.EmailField(max_length=255, unique=True) phone_number = models.CharField(max_length=50, blank=True, null=True) class RequiredClientFields(models.Model): """ Let each business decide how to enforce the data filling requirements for its staff/clients. 0 - dont even show it 1 - show it, but dont require (default) 2 - require field for either staff or client 3 - require for clients when self-filling their form, but not the staff members """ company = models.ForeignKey(Company, db_index=True, on_delete=models.CASCADE) field_name = models.CharField(max_length=50) status = models.PositiveSmallIntegerField(choices=FIELD_STATUS_CHOICES, default=1) So, when creating the django forms to use on the template, whats to best way to display (and validate) each field according to the Company's policies? thanks -
what is the proper way to handle IOS images rotation issue in different browsers?
There is two conditions browsers behave to IOS images The browser will automatically rotate images while uploading by checking EXIF data, so images will be uploaded correctly, but the browsers will not change the EXIF orientation even if it is already rotated. Browser discard the EXIF data and upload an image directly, (in this condition we can process the image and rotate from the backend ) the rotation in the backend should be based on that, whether the browser is already rotated the image or not In fact, I didn't find any method to check the browser performed this action so the backend no need to process the image again. -
Trying to create a form
At the moment I have the following as my model class Customer(models.Model): TITLE = ( ('Mr', 'Mr'), ('Mrs', 'Mrs'), ('Miss', 'Miss'), ('Ms', 'Ms'), ('Dr', 'Dr'), ('Sir', 'Sir'), ('Madam', 'Madam'), ) STATUS = ( ('Active', 'Active'), ('On hold', 'On hold'), ) GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) ROLE = ( ('Customer', 'Customer'), ('Admin', 'Admin'), ) title = models.CharField(max_length=200, null=True, choices=TITLE) first_name = models.CharField(max_length=200, null=True) middle_name = models.CharField(max_length=200, blank=True,default='') last_name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) country = CountryField() birth_year = models.CharField(max_length=4, null=True) gender = models.CharField(max_length=200, null=True, choices=GENDER) email = models.CharField(max_length=200, null=True) password = models.CharField(max_length=200, null=True) status = models.CharField(max_length=200, null=True,choices=STATUS) date_created = models.DateTimeField(auto_now=True, null=True) profile_pic = models.ImageField(null=True, blank=True, default='images/default.png') role = models.CharField(max_length=200, null=True, choices=ROLE) def __str__(self): return self.first_name And below is my form class CustomerProfileForm(ModelForm): class Meta: model = Customer fields = ['id', 'title','first_name','middle_name','last_name','phone','country','birth_year','gender','email','password'] The views are below def NewCustomerProfile(request): forms = CustomerProfileForm(request.POST) if request.method == 'GET': forms = CustomerProfileForm(request.POST) if forms.is_valid(): forms.save() return redirect('/') Below shows the template prior to the template of the form <a class="btn btn-primary" name = 'new_customer' href="{% url 'new_customer_profile' %}" role="button">NEW</a> and below shows the template on where the form will contain <div class="row"> <div class="col-md-6"> <div class="card card-body"> <form action="" method="POST"> <form … -
Setting static file in elastic beanstalk
Trying to have django look for static files in the right directory, when hosting with elastic beanstalk. Config file: option_settings: "aws:elasticbeanstalk:container:python:staticfiles": "/static/": "static" Getting error message: ERROR Invalid option specification (Namespace: 'aws:elasticbeanstalk:container:python:staticfiles', OptionName: '/static/'): Unknown configuration setting. Tried following code from the documentation as a test. option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: production.settings aws:elasticbeanstalk:container:python:staticfiles: /html: statichtml /images: staticimages Getting the same 'unknown configuration settings' error. -
Django restrict foreign key options
So I have three models: class Session(models.Model): id = models.UUIDField('ID', default=uuid.uuid4, primary_key=True, editable=False) start_time = models.TimeField('Start Time', default=None) end_time = models.TimeField('End Time', default=None) def __str__(self): return "{}-{}".format(str(self.start_time), str(self.end_time)) class Slot(models.Model): id = models.UUIDField('ID', default=uuid.uuid4, primary_key=True, editable=False) timings = models.ForeignKey('Session', on_delete=models.DO_NOTHING, related_name='slot_timings') available_counsellors = models.ManyToManyField(User, limit_choices_to={'role': 'COUNSELLOR'}, related_name='available_counsellors') def __str__(self): return str(self.timings) class ChatSession(models.Model): def get_access_code(): while True: access_code = get_random_string(length=6, allowed_chars=('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')) if not ChatSession.objects.filter(access_code=access_code).exists(): return access_code id = models.UUIDField('ID', default=uuid.uuid4, primary_key=True, editable=False) client = models.ForeignKey(User, limit_choices_to={'role': 'CLIENT'}, on_delete=models.DO_NOTHING, related_name='client_user') counsellor = models.ForeignKey(User, limit_choices_to={'role': 'COUNSELLOR'}, on_delete=models.DO_NOTHING, related_name='counsellor_user') access_code = models.CharField('Access Code', default=get_access_code, max_length=6) topic = models.CharField('Topic', default=None, blank=True, null=True, max_length=255) slot = models.ForeignKey(Slot, on_delete=models.DO_NOTHING, default=None) def __str__(self): return str(self.topic) In the chat session model, I want to limit the options for counsellor field to the available_counsellors list in slot model. How can I do this?? I want the same to reflect in my admin view also. -
Attribute error This QueryDict instance is immutable
@login_required def fileTag(request): #print("yay we made it to file tag!!") if request.method == "POST": #print("found a filetag post request!") c = {} c.update(csrf(request)) #print("POST length: " + str(len(request.POST))) #print("printing request.POST (new data)") for e in request.POST: print(e + " : " + request.POST[e]) #print("File Tags: " + str(request.POST['file_tags'])) request.session['initial_post']['file_tags'] = request.POST['file_tags'] # add the file tags to the initial post file_instance = request.session['initial_files'] I am getting the error in the line request.session initial post file tags... I am using python 3.6.9, and django 2.2.7 . The app was originally in django 1.8 and python 2, and migrating it. once migrated it crashes at that line. -
Render template in Django view after AJAX post request
I have managed to send & receive my JSON object in my views.py with a POST request (AJAX), but am unable to return render(request, "pizza/confirmation.html"). I don't want to stay on the same page but rather have my server, do some backend logic on the database and then render a different template confirming that, but I don't see any other way other than AJAX to send across a (large) JSON object. Here is my view: @login_required def basket(request): if request.method == "POST": selection = json.dumps(request.POST) print(f"Selection is", selection) # selection comes out OK context = {"test": "TO DO"} return render(request, "pizza/confirmation.html", context) # not working I have tried checking for request.is_ajax() and also tried render_to_string of my html page, but it all looks like my mistake is elsewhere. Also I see in my terminal, that after my POST request, a GET request to my /basket url is called - don't understand why. Here is my JavaScript snippet: var jsonStr = JSON.stringify(obj); //obj contains my data const r = new XMLHttpRequest(); r.open('POST', '/basket'); const data = new FormData(); data.append('selection', jsonStr); r.onload = () => { // don't really want any callback and it seems I can only use GET here anyway … -
django detail view - (PostDetailView ) is not working as i want. Not returning write context for like button .i.e, is is_liked in my case
**post_detail.html** {{post.total_likes}} <form class="" action="{%url 'like_post' %}" method="post"> {%csrf_token%} {% if is_liked %} <button type="submit" value="{{post.id}}" name="post_id" class="btn btn-danger">DisLike</button> {% else %} <button type="submit" value="{{post.id}}" name="post_id" class="btn btn-primary">Like</button> {% endif %} </form> **views.py** def like_post(request): post = get_object_or_404(Post,id=request.POST.get('post_id')) is_liked=False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) is_liked=False else: post.likes.add(request.user) is_liked=True return HttpResponseRedirect(post.get_absolute_url()) class PostDetailView(DetailView): model = Post fields = ['likes'] def get_context_data(self,**kwargs): post = self.get_object() request = self.request is_liked = False context = super().get_context_data(**kwargs) context['total_likes','is_liked'] = [post.total_likes(),is_liked] return context **urls.py** from django.urls import path from django.conf.urls import url from .views import ( PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView, UserPostListView, SearchResultView ) from . import views urlpatterns = [ path('', PostListView.as_view(), name='Blog-home'), path('search/', SearchResultView.as_view(), name='search-result'), path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('about/', views.about, name='Blog-about'), path('like/',views.like_post,name="like_post"), ] **models.py** from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) ikes = models.ManyToManyField(User,related_name='likes',blank=True) def __str__(self): return self.title def total_likes(self): return self.likes.count() def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) This is my code. It do not have any error the only problem is that the like button remain unchanged i.e, is … -
Save social login data in a existing user
I'm using email as my username therefore email has an unique propertie. Problem is there will be cases that an existing user has attempted to social login and then allauth receives a integrity database error. Goal is, to change the behavior and instead of attempt to create a new user, use the existing user for saving related social stuff. To achieve that, I'm extending the Default Social Account Adapter, although it's not working properly yet. class SocialAccountAdapter(DefaultSocialAccountAdapter): def save_user(self, request, sociallogin, form=None): """ Save a newly signed up social login. In case of auto-signup, the signup form is not available. """ existing_user = User.objects.filter(email=sociallogin.user.email).first() if existing_user: sociallogin.user = existing_user u = existing_user else: u = sociallogin.user u.set_unusable_password() if form: get_account_adapter().save_user(request, u, form) else: get_account_adapter().populate_username(request, u) sociallogin.save(request) return u -
Does Azure Web Services support Django 3.0
I've started Django project with Azure Starter Project. It created Web Services, CI/CD pipeline and template project, which I cloned from Azure DevOps. The project from Azure has Django dependency in "requirements.txt" django<2,>=1.9 Now I need to change the dependency to Django==3.0.6. I've changed "requirements.txt" accordingly. When I push my code to Azure DevOps it run Pipeline jobs and during "Install Dependencies" gives me and error ERROR: Could not find a version that satisfies the requirement Django==3.0.6 (from -r Application/requirements.txt (line 1)) (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.8.19, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, … -
Django tries to write to a generated column
I've added GIN index to my db ALTER TABLE mtn_order ADD COLUMN textsearchable_index_col tsvector GENERATED ALWAYS AS (to_tsvector('english', coalesce(descr, '') || ' ' || coalesce(descrrep, ''))) STORED; CREATE INDEX textsearch_idx ON mtn_order USING GIN (textsearchable_index_col); and textsearchable_index_col = SearchVectorField(null=True) to my model and now when i'm trying to save new instance i get: ProgrammingError at /order/create/ cannot insert into column "textsearchable_index_col" DETAIL: Column "textsearchable_index_col" is a generated column. How to stop Django trying to write None to that field -
How do I pass an additional object to a Django form so I can render some fields in the template?
I have a form in Django where site visitors can submit "gear" to be included in a person's set of gear. Here's the URL to the change form: # urls.py path('person/<slug:slug>/gear/submit/', GearSubmitView.as_view(), name='forms/submit_gear'), You can see that the person for whom the gear is being submitted is represented by a slug in the URL. Here's the first part of the CreateView: # views.py class GearSubmitView(LoginRequiredMixin, CreateView): """Allows for third-party submissions for a pro's gear collection.""" template_name = 'forms/submit_gear.html' form_class = GearSubmitForm success_message = 'Success: Submission added.' And the form: # forms.py class GearSubmitForm(forms.ModelForm): class Meta: model = PersonProduct fields = ['product', 'version', 'setup_note', 'usage_start_date', 'evidence_link', 'evidence_text'] where PersonProduct is a junction table between my Person and Product models. And the template: # submit_gear.html {% extends '_base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="container"> <h2 id="content-header">Submit Gear For {{ person.full_name }}</h2> {% crispy form %} </div> {% endblock content %} where you can see what I'm trying to do. I want to insert the name of the person represented by the slug in the URL in the form template. How can I do it? -
Django: display only the items available in an admin form | OneToOneField
I have 2 class models: class Buy(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) buy_price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return f'{self.id}' class Sell(models.Model): item = models.OneToOneField(Buy, related_name='sell', on_delete=models.CASCADE) total_paid = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return f'{self.buyer}' In the form admin page, the item field (Sell class) shows all the items available in the Buy model, regardless they've already been chosen before. As this items belongs to OneToOneField it doesn't make sense to display them because they can't be added anymore. Example: Buy id category buy_price 6 ring 20 7 ring 30 8 ring 40 Sell item total_paid 6 80 7 100 What the admin form is displaying: What I was expecting is to be shown only the item 8, the one who has not been added before. In this way, how can I display only the items, in the admin form, that hasn't been chosen yet? Thank you! -
I am beginners of django I am trying to create mcq i create dynamic buttons for each question how to display respective question of button
this is i created dynamic buttons in template <input type="button" name='q_no' value= '{{i.id}}' class="tablinks1" onclick="openQuestion1(event, '{{i.id}}')" > {% endfor %} {% for i in a ques %} <div id='{{i.id}}' class="show"> {{i.Ques}} {{i.ans1}} {{i.ans2}} {{i.ans3}} {{i.ans4}} </div> {% endfor %} that really i am asking for how call respective question using button that how to do when i click button 1 it show only 1st question with ans respectively if i click button 3 it need to display only 3rd ques with ans how to da it?? -
Django authenticate() always returning None and UserAuthenticationForm raises ValidationError
I have a custom User called MyUser. Even with the correct email(I am using email for authentication instead of username) and password, authenticate returns None and UserAuthenticationForm raises ValidationError. I have tried a lot of ways from Googling and from Stackoverflow but to no avail. models.py, from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db import models # Create your models here. class MyAccountManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError("Users must have an email address.") if not username: raise ValueError("Users must have a username.") user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user=self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.user_type = 1 user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) class MyUser(AbstractBaseUser): # required to include email = models.EmailField(verbose_name='email', unique=True, max_length=60) username = models.CharField(max_length=60, unique=True) date_joined = models.DateField(verbose_name='date joined', auto_now_add=True) last_login = models.DateField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) # new first_name = models.CharField(max_length=60, verbose_name='first name') last_name = models.CharField(max_length=60, verbose_name='last name') USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username',] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True forms.py, from django import forms from django.contrib.auth.forms import … -
Do a django filter with a string field
I would like to do the following in the django ORM: field = 'name' value = 'patrick' Asset.objects.filter(field=value) Is this possible to using the object, as I have about 50k items to update based on an enumerate field/value that's provided by the user. -
Passing Form Querystring (custom queryset) to Django Detailview
I have a form: class MyTestForm(forms.Form): options = ( ("1", "deck1"), ("2", "deck2"), ("3", "deck3"), ("4", "deck4"), ) choices = forms.MultipleChoiceField(choices = options, widget=forms.CheckboxSelectMultiple, required = False) and a views.py which passes the querystring of the form: class NewFormView(LoginRequiredMixin, View): def get(self, request, *args, **kwargs): form = MyNewForm() context = {'form':form } return render(request, 'testformv2.html', context) def post(self, request, *args, **kwargs): form = MyNewForm(data=request.POST) if form.is_valid(): data=form.cleaned_data base_url = reverse('newcombined', kwargs={'pk':24}) ## change this querystring = '{}?'.format(base_url) myqueries = [query for query in data if data[query] != []] # take the non-empty selections of the form for query in myqueries: if len(data[query]) == 1: query_arguement = str(query)+'='+str(data[query][0]) +'&' querystring += query_arguement elif len(data[query])>1: query_argument = str(query)+'='+','.join(data[query])+'&' querystring += query_argument else: print('error occured for some reason') url = querystring[:-1] #takes the last character & sign off return redirect(url) return render(request, 'testformv2.html', {'form':form}) so i will end up with a url that looks like "/v2/test/25/?Decks=2,4" ... my problem is I want to use the querystring filters to filter for a specific queryset, however, i must provide DetailView with a primary key in the URL. I am wondering if i should be processing the queryset in the post request of the form (when … -
Django Object doesn't save
I am running a script to save objects in my database (in Django) The script that is giving problems is running in a for loop where basically all values differ each iteration, I want to save each iteration's values as an object in my database. (this script is located in views.py and is triggered each time the page is refreshed): ses = Sessions(db=row['DB_ID'], sessionId=session['sessionId'], dataSource=session['dataSource'], deviceCategory=session['deviceCategory'], platform=session['platform'], sesTime=activit, hostname=host) ses.save() my model: class Sessions(models.Model): db = models.CharField(max_length=100, null=True) sessionId = models.CharField(max_length=200) dataSource = models.CharField(max_length=200) deviceCategory = models.CharField(max_length=200) platform = models.CharField(max_length=200) sesTime = models.DateTimeField(default=datetime.now()) hostName = models.CharField(max_length=200, default="U") Where the values that vary are always in the following format (this is if I print the values before trying to save: activit = 2020-05-13T07:45:21.933659Z host = company.customer.location I don't know where my mistake is, because I don't get any errors, but the object won't save. I have migrated several times. Please help -
apache can't see my wsgi_module and wouldn't start
I was following this to set up Django on windows. I'm using wamp 3.2 Django 2.1 windows server 2016 python 3.6 when I installed wamp it was working normally but when I ever edit the httpd.conf started getting errors when I open the event viewer see this The Apache service named reported the following error: >>> httpd.exe: Syntax error on line 566 of C:/wamp64/bin/apache/apache2.4.41/conf/httpd.conf: Cannot load c:/users/administrator/envs/my_application/lib/site-packages/mod_wsgi/server/mod_wsgi.cp36-win_amd64.pyd into server: The specified module could not be found. when I right-click the wamp >> apache icon I see that the wsgi_module is not found when I open the apache error log file i get this Fatal Python error: initfsencoding: unable to load the file system codec ModuleNotFoundError: No module named 'encodings' Current thread 0x00000ca0 (most recent call first): [Thu May 14 22:33:40.331236 2020] [mpm_winnt:crit] [pid 2856:tid 492] AH00419: master_main: create child process failed. Exiting. when i run the test for port 80 i get this ***** Test which uses port 80 ***** ===== Tested by command netstat filtered on port 80 ===== Test for TCP Port 80 is not found associated with TCP protocol Port 80 is not found associated with TCP protocol ===== Tested by attempting to open a socket on …