Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Is there a way to get the top most Transaction object during a nested atomic transaction in Django
I have a scenario where I want to perform some action on Transaction commit, but to user the tranasction.on_commit by django I need the transaction object. While the transaction get created a level above where I need it, is there a way I can get the transaction object inside the flow without explicitly passing it. -
Hepl with Django model
Could you help me? I'm writing the next code from django.db import models from warehouses.models import Warehouse, Location from products.models import Product from customers.models import Customer class Storage(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE, verbose_name="Cliente") warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE, verbose_name="Almacén") location = models.ForeignKey(Location, on_delete=models.CASCADE, verbose_name="Ubicación") product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name="Producto") quantity = models.IntegerField(verbose_name='Cantidad') class Meta: verbose_name = "almacenamiento" verbose_name_plural = 'almacenamientos' ordering = ['product'] ## Ordenado por ... unique_together = (('customer', 'warehouse', 'location', 'product'),) def __str__(self): return self.product I know this is easy for a more experimented Django programmer. This is what i need: in Admin, for product, i need to choose products of the customer previously choosen, not all products; in that way, i need the same for location. i need to be able to choose only between de locations of de warehouse previously choosen. How could i do this? Thanks for your help... Gabriel -
Overriding __init__ method of Django Forms - when passing request.POST form has no data
I need to generate a random quiz from a database of Questions (entity in DB). I have overrided init method of the Form import django.forms as forms import random from .models import Question class ExaminationForm(forms.Form): # matricola = forms.CharField() def __init__(self, *args, **kwargs): super(ExaminationForm, self).__init__(*args, **kwargs) if not self.is_bound: questions = list(Question.objects.all()) random_questions = random.sample(questions, k=3) for i in range(len(random_questions)): field_name = random_questions[i].question_id answers = [(random_questions[i].answer_A,random_questions[i].answer_A), (random_questions[i].answer_B,random_questions[i].answer_B), (random_questions[i].answer_C,random_questions[i].answer_C), (random_questions[i].answer_D, random_questions[i].answer_D)] random.shuffle(answers) self.fields[field_name] = forms.ChoiceField(label=random_questions[i].title, choices=answers, widget=forms.RadioSelect) else: print('Forms should have data') The above code works and I can generate a Form with random questions but when i send the POST request to the server, the form is always without data This is the code in my view: if request.method == 'GET': form = ExaminationForm() context = { "has_done":False, "form":form } return render(request, 'examination.html', context) elif request.method == 'POST': form = ExaminationForm(request.POST) ### HERE THE FORM IS BLANK AND WITHOUT DATA if form.is_valid(): print('Form is valid') print(form.fields.values()) for field in list(form.cleaned_data): print(field) return HttpResponseRedirect('/') else: print('An error occurred') print(form.errors) return HttpResponseRedirect('/') -
Django token authentication test
I'm working on very simple API for creation and authentication user with a token. If I run a server and user is created manually then I can get a token, so it probably works as expected. But my unittest for creating token for user actually do not pass. My question is - why it actually do not pass? Probably I have missed something what is done by django underhood. Appreciate any feedback. Below you can see my serializer, view, model and a failing test. models class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """Creates and saves a new user.""" if not email: raise ValueError('User must an email address') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None): """Creates and saves a new superuser.""" user = self.create_user(email, password) user.is_admin = True user.is_superuser = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): """Custom user model with email instead of username.""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' @property def is_staff(self): """Is the user a member staff?""" return self.is_admin serializer class AuthTokenSerializer(serializers.Serializer): """Serializer for the user authentication object""" email = serializers.CharField() password = serializers.CharField( style={'input_type': 'password'}, trim_whitespace=False ) def validate(self, … -
How to pass parameters from the form input box with action="get"?
I am trying to implement a form that sends a GET request but I want to pass arguments obtained by extracting data from the textfield. Here is an example: urls.py: urlpatterns = [ path('my-awesome-url/<str:foo>', MyAwesomeView.as_view(), name='my_awesome_url'), ] views.py: class ContactTracingView(View): def get(self, request, *args, **kwargs): foo = kwargs['foo'] context = {} # do some logic here return render(request, 'my_awesome_template.html', context) my_awesome_template.html: {% extends 'base.html' %} {% block content %} <form method="get" action="{% url 'my_awesome_url' foo %}"> <input type="text" name="foo"> <button type="submit" value="Submit">Submit</button> </form> {% endblock %} However, this code is not doing the job. I am receiving this error: NoReverseMatch Reverse for 'my_awesome_url' with no arguments not found. 1 pattern(s) tried: ['my\-awesome\-url\/(?P[^/]+)$'] I don't want to use POST, because I want the user to be able to bookmark the page. Also, when I tried to hardcode the url without writing parameters, csrf token was passed into the url, too. I want the url to be: my-awesome-website.tld/my-awesome-url/foo -
SyntaxError: Unexpected token < in JSON at position 0 while getting object
I am writing a SPA using DRF and Vue. I can get the list view class ArticleViewSet(viewsets.ModelViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer lookup_field = "slug" def perform_create(self, serializer): serializer.save(user=self.request.user) and my script export default { name: "Home", data() { return { articles:[] } }, methods: { getArticles() { let endpoint = 'api/articles/'; apiService(endpoint) .then(data=>{ this.articles.push(...data.results) }); } }, created() { this.getArticles(); console.log(this.articles) } }; when I try to route-link my articles : <router-link :to="{ name: 'article', params: { slug: article.slug }}" >{{article.content}} </router-link> I get error although I can see the object in the console. SyntaxError: Unexpected token < in JSON at position 0 vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in render: "TypeError: Cannot read property 'content' of undefined" this is my article.vue <template> <div class="single-question mt-2"> <div class="container"> {{article.content}} </div> </div> </template> <script> import { apiService } from "../common/api.service.js"; export default { name: "Article", props: { slug: { type:String, required: true } }, data(){ return { article: {} } }, methods: { getArticleData() { let endpoint = `api/articles/${this.slug}/`; apiService(endpoint) .then(data=> { this.article = data; }) } }, created() { this.getArticleData(); } }; </script> Can you help me to fix the error. Thanks -
Filter Django model on reverse relationship list
I have two Django models as follows: class Event(models.Model): name = models.CharField() class EventPerson(models.Model): event = models.ForeignKey('Event',on_delete='CASCADE',related_name='event_persons') person_name = models.CharField() If an Event exists in the database, it will have exactly two EventPerson objects that are related to it. What I want to do is to determine if there exists an Event with a given name AND that have a given set of two people (EventPersons) in that event. Is this possible to do in a single Django query? I know I could write python code like this to check, but I'm hoping for something more efficient: def event_exists(eventname,person1name,person2name): foundit=False for evt in Event.objects.filter(name=eventname): evtperson_names = [obj.person_name in evt.event_persons.all()] if len(evtperson_names) == 2 and person1name in evtperson_names and person2name in evtperson_names: foundit=True break return foundit Or would it be better to refactor the models so that Event has person1name and person2name as its own fields like this: class Event(models.Model): name = models.CharField() person1name = models.CharField() person2name = models.CharField() The problem with this is that there is no natural ordering for person1 and person2, ie if the persons are "Bob" and "Sally" then we could have person1name="Bob" and person2name="Sally" or we could have person1name="Sally" and person2name="Bob". Suggestions? -
Problems with session set_expiry method
I created a session for a view that some action, but i want to reset this session every week, i found set_expiry for that and tried to add that, but after working it reset all sessions in the website and i am doing logout. How to do that only for my action and not to touch all sessions in the website views.py def auth_join(request, room, uuid): room = get_object_or_404(Room, invite_url=uuid) join_key = f"joined_{room.invite_url}" if request.session.get(join_key, False): join_room(request,uuid) return HttpResponseRedirect(Room.get_absolute_url(room)) else: try: room_type = getattr(Room.objects.get(invite_url=uuid), 'room_type') except ValueError: raise Http404 if room_type == 'private': if request.method == 'POST': user = request.user.username form_auth = AuthRoomForm(request.POST) if form_auth.is_valid(): try: room_pass = getattr(Room.objects.get(invite_url=uuid), 'room_pass') except ValueError: raise Http404 password2 = form_auth.cleaned_data.get('password2') if room_pass != password2: messages.error(request, 'Doesn\'t match') return HttpResponseRedirect(request.get_full_path()) else: user = CustomUser.objects.get(username=user) try: room = get_object_or_404(Room, invite_url=uuid) except ValueError: raise Http404 assign_perm('pass_perm',user, room) if user.has_perm('pass_perm', room): request.session[join_key] = True request.session.set_expiry(10000) join_room(request,uuid) return HttpResponseRedirect(Room.get_absolute_url(room)) else: return HttpResponse('Problem issues') else: form_auth = AuthRoomForm() return render(request,'rooms/auth_join.html', {'form_auth':form_auth}) else: try: room = get_object_or_404(Room, invite_url=uuid) except ValueError: raise Http404 join_room(request,uuid) return HttpResponseRedirect(Room.get_absolute_url(room))