Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Cannot assign "2": "Wallet.coin" must be a "Coins" instance
This my code and i see error "Django - Cannot assign "2": "Wallet.coin" must be a "Coins" instance." , please help. I’ve been looking for a reason for 10 hours, I can’t decide. And maybe there are still mistakes? Thanks views.py def load_user_balance(request, wallet_id, imei): try: user = User.objects.get(imei=imei) except ObjectDoesNotExist: create = User.objects.create(imei=imei, wallet_mx=wallet_id) create.save() url_wallet = f"https://explorer-api.minter.network/api/v1/addresses/{wallet_id}" response_wallet=requests.get(url_wallet).json()['data'] for coin in response_wallet['balances']: coin_w = coin['coin'] amount_w = coin['amount'] coin_id_1 = Coins.objects.get(symbol=coin_w) coin_id = coin_id_1.id user_id = User.objects.get(imei=imei) user_id_1 = user_id.id obj, created = Wallet.objects.update_or_create(user_id_id=user_id_1, coin=coin_id, amount_w=amount_w, defaults={'user_id_id': user_id_1, 'coin': coin_id, 'amount_w': amount_w}, ) obj.save() models.py class Coins(models.Model): name = models.CharField(max_length=150) symbol = models.CharField(max_length=45) crr = models.CharField(max_length=3) class User(models.Model): imei = models.CharField(max_length=100) wallet_mx = models.CharField(max_length=50) class Wallet(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) coin = models.ForeignKey(Coins, on_delete=models.CASCADE) amount_w = models.DecimalField(max_digits=19, decimal_places=4) amount_d = models.DecimalField(max_digits=19, decimal_places=4) cap_w = models.DecimalField(max_digits=19, decimal_places=4) cap_d = models.DecimalField(max_digits=19, decimal_places=4) -
Django problem , loss filter data in view
I have a problem. When I send an email in my control view I lost the filter data in this view. I use python Thread to send the mail, but when the thread executes his function, returns a empty filter parameters. Any solutions? In views.py def enviarmail(request,pk): d = Donador.objects.get(pk=pk) subject = 'DONAR SANGRE' message = 'mensaje' email_from=settings.EMAIL_HOST_USER recipient_list=[d.user.email] send_mail(subject,message,email_from,[recipient_list,]) return redirect('lista_donante') def hilo(request, pk): t = Thread(target=enviarmail,args=(request,pk)) t.start() return redirect("lista_donante") class DonadorLista(ListView): model = Donador template_name = 'donante/donante_list.html' queryset = Donador.objects.order_by('-activo') success_url = reverse_lazy('lista_donante') def get_queryset(self): queryset = super(DonadorLista, self).get_queryset() filter1 = self.request.GET.get("grupo") filter2 = self.request.GET.get("factor") if filter1 == 'A' or filter1 == 'B' or filter1 == 'AB' or filter1 == '0': queryset = queryset.filter(grupo_sanguineo=str(filter1)) if filter2 == '+' or filter2 == '-': queryset = queryset.filter(factor_sanguineo=str(filter2)) return queryset -
Accessing values of multiple lists using an index in Django template tags
So I have three list of the same length a, b and c and another list d that are just numbers from 0 to len(a). I want to display the first three lists in an html table. So I wrote: {% for i in d %} <tr> <td>{{a.i}}</td> <td>{{b.i}}</td> <td>{{c.i}}</td> </tr> {% endfor %} For some reason this doesn't work but if change i to any number (like 0) it correctly display the first item of each list in every row. How do I use indexes in template tags to show what I want? -
HTTP code 500 on Django when I try to put a queryset on context
I'm trying to get a queryset on my IndexView on Django, when I try it, I have a HTTP code 500. I checked my template and it's path, and it's ok. Django: 3.0.5 Python 3.8.1 My views.py: from django.shortcuts import render from django.views import generic from .models import * from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes, force_text from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.template.loader import render_to_string from django.core.mail import EmailMessage from datetime import datetime class IndexView(generic.ListView): template_name = "index.html" def get(self, request, **kwargs): domain = get_current_site(request) v = Visits(domain_name=domain, date=datetime.now()) v.save() def get_queryset(self): return Domains.objects.all().only('domain').order_by('domain') def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['domains'] = Domains.objects.all().only('domain').order_by('domain') return context When I remove the get_queryset,def_context function and put redenring return, it's works fine. Probably I'm doing something wrong on context and queryset jobs. But, I don't know what. Somebody can help me. Thank you and Stay home! -
ckeditor Youtube plugin.js returns 404 error on not display when extraPlugins add?
youtube plugin installed location is /static/ckeditor/ckeditor/plugins/youtube/youtube/ i get this error when i run that configurations 'extraPlugins': ','.join(['youtube']), if returns "GET /static/ckeditor/ckeditor/plugins/youtube/plugin.js?t=JB9C HTTP/1.1" 404 1863 error and ckeditor is not display models.py from ckeditor_uploader.fields import RichTextUploadingField from django.db import models class Article(models.Model): title = models.CharField(max_length=100) content = RichTextUploadingField(blank=True) def __str__(self): return self.title settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) CKEDITOR_UPLOAD_PATH = 'article/' CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_CONFIGS = { 'default': { 'width': 'auto', 'extraPlugins': ','.join(['youtube']), # return "GET /static/ckeditor/ckeditor/plugins/youtube/plugin.js?t=JB9C HTTP/1.1" 404 1863 error and ckeditor is not display 'toolbar': [ ['Bold', 'Italic', 'Underline'], ['Font', 'FontSize', 'TextColor', 'BGColor'], ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ['Link', 'Unlink'], ['RemoveFormat', 'Source', 'Image', 'Youtube'] ], } } config.js CKEDITOR.editorConfig = function (config) { config.extraPlugins = 'youtube'; }; -
django get dropdown value on change
in django admin i have a thre models first model have city field from type char second model have feild country from type char every city have many countries third model have person_name field from type char and have field city forgin key and contry field forgin key the problem that is in admin panel when i create person i choose city from cities but it show all countries i want only to show countries for choosen city and on change dropdown change countries not on submit Note i add person from admin not form from html page code example pls -
Getting Attribute error on using icontains
my two model class: class Bank(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Branch(models.Model): ifsc = models.CharField(max_length=200) name = models.CharField(max_length=200) address = models.TextField(max_length=200) city = models.CharField(max_length=200) state = models.CharField(max_length=200) bank = models.ForeignKey(Bank, on_delete=models.CASCADE,max_length=200) def __str__(self): return f"{self.name}" serializer classes, class BankSerializer(serializers.ModelSerializer): class Meta: model = Bank fields = '__all__' class BranchSerializer(serializers.ModelSerializer): bank = serializers.CharField(source='bank.name', read_only=True) class Meta: model = Branch fields = ["ifsc","name","address","city","state","bank"] and Views.py class CityBankNameView(APIView): def get_object(self, bank_name, city_name): try: bank = Bank.objects.get(name=bank_name) branches = Branch.objects.filter(bank__icontains=bank, city=city_name) #<-- icontains return branches except: return HttpResponse(status=status.HTTP_404_NOT_FOUND) def get(self,request, bank_name, city_name): branches = self.get_object(bank_name, city_name) serializer = BranchSerializer(branches, many=True) return Response(serializer.data) I am getting attribute error when using bank__icontains exact error: AttributeError at /branches/DELHI/AXIS BANK Got AttributeError when attempting to get a value for field ifsc on serializer BranchSerializer. The serializer field might be named incorrectly and not match any attribute or key on the bytes instance. Original exception text was: 'bytes' object has no attribute 'ifsc'. I am trying for hours but cannot find any solution to it. I seen various answers but none of them helps solve this one -
What should be returned by the view function to display a newly created object instance in DetailView
I'm new to Django. I'm trying to modify this example. What should be retured by the create_book_wiht_authors to the DetailView to display newly created Book with Author? views.py class BookCreateView(CreateView): model = Book form_class = BookModelForm def get_success_url(self): return reverse('store:create_book_with_authors', kwargs={'pk': self.object.pk}) class BookDetailView(DetailView): model = Book context_object_name = 'book' def create_book_with_authors(request, pk): template_name = 'store/create_with_author.html' if request.method == 'GET': bookform = BookModelForm(request.GET or None) formset = AuthorFormset(queryset=Author.objects.none()) elif request.method == 'POST': bookform = BookModelForm(request.POST) formset = AuthorFormset(request.POST) if formset.is_valid(): book = Book.objects.get(pk=pk) for form in formset: author = form.save(commit=False) author.book = book author.save() return redirect(reverse('store:book_detail', kwargs={'pk':book})) return render(request, template_name, { 'bookform': bookform, 'formset': formset, }) This gives me the NoReverseMatch error. -
Cannot import function from mysite.views in Django
mysite is the app name i created in my django project. below is the hierarchy of my app. mysite --- views.py --- tasks.py --- urls.py I have a normal function(there is no request parameter, hence no entry in urls.py as well) in views.py as shown below. def function1(param1,param2): return something I am trying to import this function1 in tasks.py by using from .views import function1 but its throwing an error saying ImportError: cannot import name 'function1' from 'mysite.views' Is there any way to get rid of this error. -
Why is the current user not being passed to my template?
Ok, so I am querying 'messages' and attempting to display 'request.user' messages on the right side of the page and the messages of the user who messaged the request.user on the left side of the page. However, request.user is not being passed to the template and it's displaying ALL the messages on the left side of the page. What am I doing wrong here? Also, I specified a custom user model called Profile for user. views.py/messages def messages(request): messages = InstantMessage.objects.all() return render(request, 'dating_app/messages.html', {'messages': messages}) messages.html <div id="msg-list-div" class="panel-body"> <ul id="msg-list" class="list-group"> {% for obj in messages %} {% if obj.user == request.user %} <li class="text-right list-group-item">{{ obj.message }}</li> {%else%} <li class="text-left list-group-item">{{ obj.message }}</li> {%endif%} {% empty %} <li class="text-right list-group-item">No messages yet...Keep mingling!</li> {% endfor %} </ul> </div> models.py class ProfileManager(BaseUserManager): def create_user(self, username, email,description,photo, password=None): if not email: raise ValueError("You must creat an email") if not username: raise ValueError("You must create a username!") if not description: raise ValueError("You must write a description") if not photo: raise ValueError("You must upload a photo") user = self.model( email=self.normalize_email(email), username = username, description= description, photo= photo, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email,description,photo, password): user = self.create_user( email=self.normalize_email(email), … -
AttributeError: 'str' object has no attribute 'decode' || related to django user creation
*i am getting AttributeError: 'str' object has no attribute 'decode'* from django.utils.http import urlsafe_base64_encode seld.uid = urlsafe_base64_encode(force_bytes(user.pk)).decode()``` -
Django - Multi Model Search
I am working on a search app that queries data from multiple tables. I can search for the fields of the model Post, but when I try to query the username from a user of a post, I get this error: sub-select returns 19 columns - expected 1 This is what I have: class PostQuerySet(models.QuerySet): def search(self, query=None): qs = self if query is not None: profile = UserProfile.objects.select_related('user', 'user__profile') or_lookup = (Q(title__icontains=query) | Q(genre__icontains=query) | Q(user__username__icontains=profile)) qs = qs.filter(or_lookup).distinct() return qs Thank you for any suggestions -
How to save formset data
I try to save a formset data, I have the see() method with slug parameter to get the client contacts, after that, i display the contacts using a formset, but the issue is how to edit and save the displayed data, so how to call the see method again so that the request.POST will be true and i can edit the formset data ?? views.py def see(request,slug): data = dict() print(request.POST) ProductFormSet = modelformset_factory(Contact, fields=('Nom','post','Tel','email','contact_type','client'), extra=0) client = get_object_or_404(Client_Data, slug=slug) attig = request.POST or None formset = ProductFormSet(data=attig, queryset=Contact.objects.filter(client=client)) for form in formset: form.fields['client'].queryset = Contact.objects.filter(client=client.id) if request.method == 'POST': print('hello') print(formset.is_bound) if formset.is_valid(): formset.save() context = {'form': formset} template_name = 'Client_Section/partial_client_contact.html' data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) form.py class Contact_Form(forms.ModelForm): class Meta: model = Contact fields = ('Nom','post','Tel','email','contact_type','client') def __init__(self,*args, **kwargs): super(Contact_Form, self).__init__(*args, **kwargs) self.fields['client'].queryset = Client_Data.objects.all() parital_client_contact.html if i add action="{% url 'see' form.instance.slug %}" i get an error ("NoReverseMatch: Reverse for 'see' with arguments '('',)' not found. 1 pattern(s) tried: ['client/see/(?P[-a-zA-Z0-9_]+)$'] ") <form method="post" class="js-book-create-form"> {% csrf_token %} <div class="modal-body" > {% include 'Client_Section/partial_client_contact_form.html' %} </div> <br><br> <div style="pos"> <button style="float : right" type="submit" class="btn btn-primary ">Update Contacts</button> <button style="float : right" type="button" class="btn btn-default" data-dismiss="modal">Close</button> … -
How to get previous path in Django View request method> [duplicate]
I have a simple Django app where users can access the index page through /login and through /signup. In my views, I want to add a measure to check which page the user is coming from. How do i do so? Thanks -
How could django manage to point the right static file among two angular projects if both projects contain similar file names?
I've created two angular projects (Project1 and Project2) for frontend. Django is used for the backend. After building both of the angular projects It's been copied to static folder in django by using python manage.py collectstatic and I've created two separate paths for the two angular projects in urls.py. Some of the file names are matching in both angular projects(especially js files like main-es5.js, polyfills-es5.js etc.). So django is unable to distinguish them. It's required to point Django at the right one. What's the best solution for this? Directory view is as shown below Click here to view Directory list -
How to do post signup actions depending on user type with custom forms in Django AllAuth
I am really struggling to keep DRY with AllAuth when I have custom SignUpForms and SocialAuth enabled, specially considering that depending on the user type; the authentication paths be different, and only one type of user (ie. customers) should be allowed to use social sign-up. My user model is setup as follows: custom user model Person extending AbstractUser Person has a boolean field is_customer (False equates "staff") With that in mind, I have setup two paths for authentication so I can control SocialAccount being present depending on user type # urls.py urlpatterns = [ path('business/signup/', BusinessSignUpView.as_view(), name='business-signup'), # custom signup form for businesses path('business/', include("allauth.account.urls")), # override settings.py and ignore `socialaccount` paths path('customer/', include("allauth.urls")), # As per settings.py, include `socialaccount` ] I want some additional info on business/signup so have overridden it as follows # models.py class BusinessSignUpForm(SignupForm): field_a = CharField(max_length=30, label='Label A', required=False) field_b = CharField(max_length=30, label='Label B', required=False) def save(self, request): person = super(BusinessSignUpForm, self).save(request) person.is_customer = False person.save() return person #views.py class BusinessSignUpView(SignupView): template_name = 'account/signup.html' # Keep DRY, use only 1 template irrespective of user type form_class = BusinessSignUpForm view_name = 'business-signup' However in my mind, that where the problem starts. I originally also created a … -
AttributeError: '_thread._local' object has no attribute 'value'
Totally new to deep learning can't figure out what is happening. I'm implementing a django app to recognize face in real time. Installed packages using pip and conda in two different envs but didn't get any success. Here I'm using MTCNN to detect faces after that I've model to recognize face. While things are running fine without django they are not working with django. enter image description here import cv2 import pickle from PIL import Image from numpy import load from numpy import expand_dims from numpy import asarray from mtcnn.mtcnn import MTCNN from tensorflow.keras.models import load_model from sklearn.preprocessing import LabelEncoder class RealTimeFaceDetection: def __init__(self): self.stroke = 1 self.detector = MTCNN() self.video_cap = cv2.VideoCapture(0) self.color = (255, 0, 0) print("Loading pre-trained Keras model for face recognition") self.keras_model = load_model('facenet_keras.h5', compile=False) print("Face recognition model loaded successfully...") print("Loading pre-trained SVC model") self.svc_model = pickle.load(open('FACENET_MODEL.sav', 'rb')) print("Loading successful...") self.emb_data = load('5-celebrity-faces-embeddings.npz') def img_to_array(self, face_img_pixels, required_size=(160, 160)): image = Image.fromarray(face_img_pixels) image = image.resize(required_size) return asarray(image) # Get the face embedding for one face def get_embedding(self, model, face_pixels): face_pixels = face_pixels.astype('float32') mean, std = face_pixels.mean(), face_pixels.std() face_pixels = (face_pixels - mean) / std samples = expand_dims(face_pixels, axis=0) yhat = model.predict(samples) return yhat[0] def get_encoder(self): trainy = … -
Django development cors settings with credentials
I'm struggling with my django-cors-headers settings for my development environment. I'm requesting a django api from a React client application, using axios with withCredentials set to true. The use of withCredentials implies that the Access-Control-Allow-Origin response header can't be set to *. And here's the weird thing: in my settings.py, I have: CORS_ORIGIN_ALLOW_ALL = False # should be useless while a whitelist is set, but still... CORS_ORIGIN_WHITELIST = ['http://localhost:3000'] I can verify that the value of Access-Control-Allow-Origin is indeed http://localhost:3000 if I write a simple middleware and print the header: class LocalSettingsMiddleware(MiddlewareMixin): def process_response(self, request, response): print(response['Access-Control-Allow-Origin']) return response >>> Django version 3.0.5, using settings 'mydjangoapp.settings' >>> Starting development server at http://127.0.0.1:8000/ >>> Quit the server with CONTROL-C. >>> http://localhost:3000 >>> [10/Apr/2020 19:54:02] "OPTIONS /authent/token/obtain/ HTTP/1.1" 200 0 But on the client side, the preflight request fail and I get the following CORS error: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. On the production server, everything works just fine, the problem seems to occur only when localhost is set in the cors whitelist. -
How to remove djnago-allauth from cookiecutter-django
I am using cookiecutter-django to create a boilerplate codebase right out the box. However, as great as this is the setup uses django-allauth for its authentication purposes right out of the box. I feel django-allauth is too tightly coupled with the project and it is very diificult and error prone to remove this library and use another auth library. I wanted to use djoser library for the authentication. Also, let me know if the changes are irreversible once the initial migrations of the boilerplate are applied. I wanted to know what is advisable here? Can this library be replaced with another auth library or another cookiecutter project needs to be started from scratch with the compatible library. -
Is it okay for the rest endpoint to be public? [closed]
I have this architecture that uses rest API to get comments according to the object. Is is safe for it to be public ? rest api code -
Unable to store all the data into Django database, using Python Requests
Unable to store all the data into Django database. Its printing the correct list of data from an open API but not storing. def get_alldata(): url1 = "http://dummy.restapiexample.com/api/v1/employees" url = "http://127.0.0.1:8000/employee/" my_response = requests.get(url1) token = get_token() header = {'Authorization' : f'Token {get_token()}'} data1 = [ my_response.json() ] for d in range(len(data1)): payload = data1[d] res = requests.post(url, data=data1[d] , headers=header ) print(data1[d]) get_alldata() -
How do I create a single-page application in Django using a websocket?
I'm making a site with Django and I'm a bit stuck with how to implement a single-page app part of the site, where the client asks the server via a websocket for different HTML-pages that it then renders. What I'm unsure of is where I would store the HTML that the client requests on the server. Note that the whole site isn't a single-page app, so the HTML I'm talking about here is separate from what is stored in the templates folder in my Django app. I was thinking about storing the HTML-files in the static folder, but couldn't figure out how to access that outside a template. In a template you could say this for example: {% load static %} <script src="{% static 'myapp/index.js' %}"></script> That isn't possible outside the template though, so I would appreciate help with that too. This wouldn't be a problem if I'd use a HTTP-request to get the HTML-files. If i'd use a HTTP-request I could just make a view that returns a template, but I wanna use a websocket and Django Channels since that, as far as I know, is faster. Maybe it's a bad idea to use a websocket for this though. -
Any way to exclude first form in formset from validation?
I'm using formsets and so far everything works well. However, in the clean_dr(self) method below I only want to validate that the DR field is empty if the form being check is not the first form in the formset. Ie if it's the first form in the formset then the DR field CAN be empty. Otherwise it cannot. Thank you forms.py class SplitPaymentLineItemForm(ModelForm): # Used to validate formset lineitems when creating or updating split payments ledger = GroupedModelChoiceField(queryset=Ledger.objects.filter((Q(coa_sub_group__type='e')|Q(coa_sub_group__type='a')),status=0).order_by('coa_sub_group__name', 'name'), choices_groupby = 'coa_sub_group', empty_label="Ledger", required=True) project = forms.ModelChoiceField(queryset=Project.objects.filter(status=0), empty_label="Project", required=False) class Meta: model = LineItem fields = ['description','project', 'ledger','dr',] # This init disallows empty formsets def __init__(self, *arg, **kwarg): super(SplitPaymentLineItemForm, self).__init__(*arg, **kwarg) self.empty_permitted = False def clean_dr(self): data = self.cleaned_data['dr'] if data != None: if data < 0: raise ValidationError('Amount cannot be negative') #if data == None: <---- I do not want this validation to apply to first item in formset # raise ValidationError('Amount cannot be empty') return data Views.py @login_required def split_payments_new(request): LineItemFormSet = formset_factory(SplitPaymentLineItemForm, formset=BaseSplitPaymentLineItemFormSet, extra=0, min_num=2) if request.method == 'POST': form = SplitPaymentForm(request.POST) lineitem_formset = LineItemFormSet(form.data['amount'], request.POST) if form.is_valid() and lineitem_formset.is_valid(): q0 = JournalEntry(user=request.user, date=form.cleaned_data['date'], type="SP") q1 = LineItem(journal_entry=q0, description=form.cleaned_data['store'], ledger=form.cleaned_data['account'], cr=form.cleaned_data['amount']) q0.save() q1.save() for lineitem in lineitem_formset: … -
How do I setup my own time zone in Django?
I live in Chittagong, Bangladesh and my time zone is GMT+6. How can i change to this time zone in Django settings? -
Concerning about https in development stage using django
I'm designing a web app using django as backend. I've read a couple of books and a lot of docs about it. They always refer to http protocol, at least for the development. But in the end it is recommenden to switch to https when it comes a production environment. I was wondering whether should I concern about https already in the development stage, or if it would be easier and faster to develop in basic http and switch to https right before production deployment. This previous question Rewrite HTTP to HTTPS Django suggest me (for what I've understood) that django app should speak simple http, and it should run behind a web server (e.g. nginx) which is responsible to accept https request from users and forward them via http to django. I hope some expert could enlighten me on that point.