Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, make model that refer more than equal 2 foreign key but not be deleted CASCADE
I have django model: @python_2_unicode_compatible class TestModel(models.Model): description = models.CharField(max_length=34) def __str__(self): return "TestModel %s" % self.description @python_2_unicode_compatible class TestModelLog(models.Model): description = models.CharField(max_length=34) foreignkey = models.ForeignKey(TestModel_2, related_name='test_foreignkey_1', null=True, blank=True) foreignkey_2 = models.ForeignKey(TestModel_2, related_name='test_foreignkey_2', null=True, blank=True) def __str__(self): return "TestModelLog %s" % self.description Let say I made a model object like this: testmodel_a = TestModel.object.get_or_create(descripton=A_test) testmodel_b = TestModel.object.get_or_create(descripton=B_test) testmodel_log = TestModelLog.object.get_or_create(descripton=Log, foreignkey=testmodel_a, foreignkey=testmodel_b) Although I set null=True, blank=True to TestModelLog's foreignKey fields in models.py, not on_delete=models.CASCADE, When I try to delete just testmodel_a(or testmodel_b) in django admin, it keep saying it will delete related testmodel_log also. I thought testmodel_log will still be exist whether testmodel_a or testmodel_b is deleted or not. Question: Why this happened and How to make testmodel_log be independent from testmodel_a or testmodel_b's change? -
Ajax POST function not running successfully with Django
I am trying to run the Ajax POST function. But I am not able to see any alert message after completion of the function. function SendData() { $.ajax({ url : window.location.href,// the endpoint,commonly same url type : "POST", // http method data : { csrfmiddlewaretoken : csrftoken, lastMessage : lastMessage, NewMessage : NewMessage }, // data sent with the post request // handle a successful response success : function(json) { console.log(json); // another sanity check //On success show the data posted to server as a message alert('User : '+json['lastMessage'] +' . User : '+ json['NewMessage']); ***//Not showing this alert*** }, // handle a non-successful response error : function(xhr,errmsg,err) { console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console } }); } I am calling the SendData() function from another function KepPress() that runs when the 'enter' key is pressed. Data in 'lastMessage' and 'NewMessage' are received from input type text tag in HTML. -
Dynamically generate accompanying model in django
In my project i have many models in multiple apps, all of them inherit from one abstract model. I would like to create a model that would hold the changes to the history for every one of my models, so that every model would have its own history model. Each model would also have one-to-many relation to its history model. All history models would be the same, except for the foreign key to their respective model. My problem is that I do not want to write all the history models manually. Instead i would like to have the history model created for every model automatically, so I don't have to write all that boilerplate code. Can this be achieved? -
Django installation admin page not getting
I installed Django and created myproject & myapp by refer the tutorial https://www.tutorialspoint.com/django/django_creating_project.htm I got below output while run the command $ python manage.py runserver Performing system checks... System check identified no issues (0 silenced). January 05, 2018 - 06:32:21 Django version 1.11, using settings 'myproject.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. But while I run the URL in the browser http://127.0.0.1:8000/admin/, it shows "Unable to connect" -
Got an unexpected keyword argument 'pk1' issue
I am getting an error, that I do not know how to fix and even why I am getting that error. I am rendering a form to link a team to a project in a url where like : http://127.0.0.1:8000/website/project/20/linkteam2 where 20 is my pk1 = 20 which is the project id. I am using pk1 and pk2 because when the team is linked, the url become : http://127.0.0.1:8000/website/project/20/team_id For some reason I am getting: TypeError at /website/project/21/linkteam2/ TeamSelect() got an unexpected keyword argument 'pk1' my code is : def TeamSelect(request): import pdb; pdb.set_trace() if request.method == "POST": select_form = EditSelectTeam(request.user, request.POST) if select_form.is_valid(): data = select_form.cleaned_data['team_choice'] obj2 = Project.objects.filter(project_hr_admin=request.user) obj3 = obj2.latest('id') if obj3.team_id == None: obj3.team_id = data obj3.save() obj4 = obj3.team_id obj5 = obj4.members.all() for i in obj5: current_site = get_current_site(request) message = render_to_string('acc_join_email.html', { 'user': i.first_name, 'domain':current_site.domain, }) mail_subject = 'You have been invited to SoftScores.com please LogIn to get access to the app' to_email = i.email email = EmailMessage(mail_subject, message, to=[to_email]) email.send() messages.success(request, 'test') return HttpResponseRedirect(reverse('website:ProjectDetails', kwargs={'pk1':obj3.id, 'pk2':obj4})) else: print('this project has already a team') else: print('Non Valid form') else: import pdb; pdb.set_trace() select_form = EditSelectTeam(request.user) return render(request,'link_project.html', {'select_form':select_form }) my html: {% load static … -
How to format foreignkey conditionally in django admin
My model.py: class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='user_profile') myfield = models.ForeignKey(Mymodel, on_delete=models.CASCADE, blank=True, null=True) ... class Mymodel(models.Model): name=models.CharField(max_length=64) complete = models.BooleanField(default=False) In my admin panel when I add a Userprofile this gives a dropdown menu with all the Mymodel istances. I would like to format (colour red) the ones already taken (I have a more complex problem, based on a field of Mymodel but the concept is the same). Is it possible to do? def model_taken(self): if UserProfile.objects.filter(myfield=self.myfield).exists(): return format_html('<span style="color: red;">{}</span>') What if I would like to filter out this values instead of format them? Thank you -
I am trying to dynamicallyload mynavbar content from my django model database without affecting the display page
My template structure is base.html where i included navbar.html inside the base I have an app called tags and tags has a models.py and a views.py inside the views.py, i have a django code as this from tags.models import Tag class TagList(ListView): model = Tag def get_queryset(self): return Tags.object.all() this works, when i call {{ object_list }} inside my template for the tag_list.html. So i added the {{ object_list }} inside my template navbar.html which was included inside the base.html but it works only when am on the url that displays my tag_list.html and does not show anything when am on other urls or other templates.. How do I make it show irrespective of the template directory am inside or the url am displaying ... i want it to show I've thought of copying my views.py code into every app view and repeat the same process for every templates but i have a lot of template directories i cannnot do this for all of them -
My PostgreSQL database is empty
I'm developing a Django project and as a database I'm working with PostgreSQL 10.1, the "problem" is I can't see my Tables, it doesn't show anything but when in the command line I run "python manage.py makemigrations" it create the files and then when I run "python manage.py migrate" it actually migrate all the info to the database, but I can't see anything in pgAdmin 4. -
Django, update the object after a prefetch_related
I have the following models: class Publisher(models.Model): name = models.CharField(max_length=30) class Book(models.Model): title = models.CharField(max_length=100) publisher = models.ForeignKey(Publisher) In my views.py, When I want to show the publisher page, I also want to show their books, so I usually do something like this: publisher = Publisher.objects.prefetch_related('book_set').filter(pk=id).first() Then, after some processing I also do some work with the books for book in publisher.book_set.all(): foo() This works great, but I have one problem. If there is a book added between the query and the for loop, the publisher.book_set.all() won't have the newly added books because it was prefetched. Is there a way to update the publisher object? -
Is there anyway to filter all ORM queries in Django?
So I have a rather unorthodox idea of using a middleware to filter queries dynamically, as to keep my authentication further away from the views themselves. I've seen a few library's that could log transactions, but there's no way to alter them since it's post-transaction. Essentially any calls to a certain model would be filtered based on authentication credentials. E.g. Some field that states a user's privileges. This is probably insane and would require me hooking into the ORM itself, but I must ask out of curiosity. Maybe I'm just too lazy to change the rest of my code to reflect this. Thanks to anybody who could clarify if this is possible or impossible. Edit: As of writing this question... Wouldn't this be possible to achieve by subclassing a model manager? Am I this thick?! -
Django rest framework import data from one table to another
I am doing a django rest framework API for ios application. And currently, i am doing a function between user and family. Let me explain my logic between these two. User= current user (an account that can be use to login) Family = current user's family member eg:father mother (it is not an account, cannot be use to sign in) What i am thinking right now is that if the current user's family wanted to create an account, is it possible to import the data from family table to user table for that family member to register ? user table : userId, username, password, email, phone_number, identification_num, first_name, last_name family table :Id, userId(foreign key to user table, cannot be null) , familyId(can be null, reason is to allow user to add family member that did not register an account), phone_number, identification_num, first_name, last_name, relationship Example scenario : user sent invitation link to that family member(either by email or other social app, and it will import the data to the family member to register an account family member click on invite link redirect to register page with the detail from family table. If register success, insert the userId of that family … -
Django 2.0 Block/Force Particular Browser
In my new Django project, i am planning to use CSS Grid for template layout. To make site responsive without using bootstrap. So here i want to know how can i block those browser which doesn't support CSS grid ?? For testing purpose i tried this in settings.py but nothing works DISALLOWED_USER_AGENTS = (re.compile(r'IE\s[0-9]+', re.IGNORECASE), ) is there any better way to do this ? where i can force user to upgrade their browser -
Reactjs axios HTTP request not retrieving Django-rest-framework's API request.user
axios HTTP request to the django-rest-framework api not receiving the request.user (logged in user) data. The output (response.data) from the axios HTTP request receives json data of: request_user: " ", an empty string. I have tested the HTTP request with both when a user is logged in and not. When i test with a user logged in the django server, the django-rest-framework API shows data with the request.user's username request_user: "username", however the reactjs axios HTTP request still shows an empty string. When there is no user logged in the json data in both the API and axios HTTP request shows an empty string request_user: "" (showing that no user is logged in). So i'm guessing the problem is to do with the request in the RequestUserAPIView, both the django and reactjs development servers are separate. Reactjs class Wrapper extends Component { state = { requestUser: null } componentDidMount () { this.loadData() } loadData () { axios.get('http://127.0.0.1:8000/api/user/request/').then(response => { this.setState({ requestUser: response.data.request_user }); }) } } Django API class RequestUserAPIView(APIView): def get(self, request, format=None): data = { "request_user": request.user.username } return Response(data) -
How to filter objects in django based on json field where a key is list and based on number of list items mathched for each object?
I have a an object named canditade. class Candidate(models.Model): name = models.CharField(max_length=64) skills = models.JSONField() I have created objects like this Candidate.objects.create(name='mark',skills={'list':{'name':'python'}, {'name':'java'}, {'name':'sql'}, {'name':'django'} }) Candidate.objects.create(name='jeremy',skills={'list':{'name':'python'}, {'name':'java'}, {'name':'sql'}, {'name':'django'} }) Candidate.objects.create(name='jeremy',skills={'list':{'name':'python'}, {'name':'java'}, {'name':'sql'}, {'name':'flask'} }) I want to filter candidates where based on skills required vs skills present for alleast 75% match or 50% match. note : the percent can be dynamic. How should I query and filter the objects . if i enter skills like 'python','java','sql','docker'. and mention 75% match. I also want to know how the performance will be if i have to traverse over atleast a million records. -
how to convert UTC timezone DateTime in to local timezone using Django ORM query
class Book(models.Model): created_at=models.DateTimeField(auto_now_add=True) this datetime in utc timezone and i want to this datetime in to local timezone converted using query -
set tab-pane also to active when clicking nav-tab to active
Im trying to set a nav-tab to active and its corresponding tab-pane to active also. The problem here is whenever i click the offered_orders tab and choose for example page 2 in its pagination, it returns to allorders tabs. For it to return the correct page, it needs both the nav-tab and tab-pane set to active. However in my code below its not working. <div class="nav-tabs-custom"> <ul class="nav nav-tabs"> {% with active_tab="allorders" %} <li class="{%if active_tab == "allorders" %}active{%endif%}"><a href="#allorders" data-toggle="tab">All Orders</a></li> <li class="{%if active_tab == "offered_orders" %}active{%endif%}"><a href="#offered_orders" data-toggle="tab">Offered Orders</a></li> {%endwith%} </ul> <div class="tab-content"> <div class="tab-pane {%if active_tab == "allorders"%} active {%endif%}" id="allorders"> <div class="row"> <div class="col-md-12"> <table class="table table-bordered table-hover" border="0" style="width: 100%"> <thead> <tr> <th>Job Order No.</th> <th>Client Name</th> </tr> </thead> {%for allorders in allorders%} <tr> <td>{{allorders.oid}}</td> <td>{{allorders.client}}</td> </tr> {%endfor%} </table> {% if allorders.has_other_pages %} <ul class="pagination"> {% if allorders.has_previous %} <li><a href="?{{page_request_var}}={{ allorders.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in allorders.paginator.page_range %} {% if allorders.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?{{page_request_var}}={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if allorders.has_next %} <li><a href="?{{page_request_var}}={{ allorders.next_page_number }}">&raquo;</a></li> {% else %} … -
Django version upgrade 1.7 to 1.8 - content type issue
While upgrading django version from 1.7 to 1.8, I got a new migration called 0002_remove_content_type_name, after that I migrated that file, then I run my project, after that, it shows below error. (1054, "Unknown column 'django_content_type.name' in 'field list'") Then I checked the ContentType model in django.contrib files in packages, there I found the below code, class ContentType(models.Model): name = models.CharField(max_length=100) app_label = models.CharField(max_length=100) model = models.CharField(_('python model class name'), max_length=100) objects = ContentTypeManager() Due to the available of name field, I got the unknown column error, We should not edit the package file(like commenting the name field list in the model file), also we have to migrate the changes given when upgrading django version 1.7 to 1.8. Give me the best solution to resolve this issue. Thanks. -
Django rest framework display data from 2 other serializer in 1 view
I am currently doing an API for IOS application and i have 3 model, MyUser, Family and Schedule2. MyUser = Current user Family = Current user's family Schedule2 = A reminder (eg: birthday or an outing reminder kind) My idea is that in create schedule API, it will display: current userId, username, url(it is image url currently for testing) family id that is related to current user, relationship(the relationship between this family member and current user. eg: father, mother), url(same as above, image url) It is something like mobile app of facebook messenger where there is image showing the friends. And then the message/group chat below. Is there a way to do it ? I tried doing it but it got error and failed. What i did is insert related_name='family_mem' in Schedule2 userId, insert my_family = FamilySerializer(many=True, source='family_mem') into Schedule2Serializer and add my_family into the field. My expected output for ListCreateAPI : (this is only for when doing create function. I have a seperated API List to view schedule.) I only want to get the 3 details of current user as well as 3 details of all family member. Here is my code: models class MyUser(AbstractUser): userId = models.AutoField(primary_key=True) gender … -
Minor Issue: Where is the better place to put User.objects.create_user in DRF?
Recently, I have reviewed my previous codes in Django thoroughly line by line. And I've got a minor issue. I have a preference to put ORM method to VIEW, not serializer. For example, I would like to make User.objects.create_user into APIView class like below. class SignUp(APIView): def post(self, request): serializer = SignUpSerializer(data=request.data) if serializer.is_valid(raise_exception=True): User.objects.create_user( email=serializer.validated_data['email'], password=serializer.validated_data['password1'], first_name=serializer.validated_data['first_name'], last_name=serializer.validated_data['last_name'], ) return Response(data=serializer.data, status=status.HTTP_201_CREATED) However, I've found many people code like below overriding create method in serializer. class SignUpSerializer(serializers.ModelSerializer): password1 = serializers.CharField(write_only=True) password2 = serializers.CharField(write_only=True) class Meta: model = User fields = ('pk', 'email', 'password1', 'password2', 'first_name', 'last_name') def validate(self, data): if data['password1'] != data['password2']: raise serializers.ValidationError('password should match') return data def create(self, validated_data): return self.Meta.model.objects.create_user( email=validated_data['email'], password=validated_data['password2'], first_name=validated_data['first_name'], last_name=validated_data['last_name'] ) I personally consider that serializer is more like data convertor, not reproducer. I would appreciate that you are able to share your opinion about this minor issue :) p.s I've said it minor issue because I am aware of this can be a matter of taste. -
Are Django caches syncronized, memcached etc
I have a scenario where a function will be called from two different places at the same time. before calling the function from each place, i'm using cache system to see if it's already been called by one of them. then after calling the method, i'm caching a value indicating that it has been called. using memcached. -
Django Contact form: TypeError: "to" argument must be a list or tuple
I am trying to get my email contact form to work on my Django website. I am getting an error in my browser as follows: Exception Type: TypeError Exception Value: "to" argument must be a list or tuple Exception Location: /home/Gassymule/Skeletonv3.1/myvenv/lib/python3.6/site-packages/django/core/mail/message.py in init, line 264 It specifically highlights try: send_mail(name, company, phone, subject, message, from_email, ['kkeeper.ch@gmail.com']) from my views.py but I am not entirely sure what it needs me to fix. The Tutorial website that I took this from used this exact format. views.py from django.http import HttpResponse from django.shortcuts import render, redirect from django.views.generic import TemplateView from website.forms import ContactForm from django.core.mail import send_mail, BadHeaderError def email(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] name = form.cleaned_data['name'] company = form.cleaned_data['company'] phone = form.cleaned_data['phone'] try: send_mail(name, company, phone, subject, message, from_email, ['kkeeper.ch@gmail.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('thanks') return render(request, "email.html", {'form': form}) def thanks(request): return HttpResponse('Thank you for your message.') Here is the relevant code from my contact form template. email.html <form action="" method="post"> {% csrf_token %} <ul class="contactList"> <li id="name" class="contact">{{ form.name }}</li> <li id="company" class="contact">{{ form.company }}</li> <li id="email" class="contact">{{ … -
CORS/Django/AWS/Elastic Load Balancer
I was running a Django server on Elastic Beanstalk for a few weeks --- a problem forced me to reinstantiate the instance. For some reason now, I can't seem to get my API to work correctly -- my requests are turning into: 504 (GATEWAY_TIMEOUT) I have the correct settings in my Django app and the thing was working correctly two hours ago. I'm fairly confident this is an AWS issue but I'm not sure where to go to fix it. -
Django model field _('name')?
I'm reading the django.contrib.auth.models.py file and I see this being done all over the place: name = models.CharField(_('name'), max_length=255) I believe 'name' is the option designating the name of the database column to use for this field. But what does surrounding it with _('...') mean? And what's the advantage to doing that? -
Send Activation Code in Email After Registration
As we seen in different website, After signup it sends 6/5 character of activation code in our email.And we use that activation code to activate our account. I am trying to do the same thing but cant figured out how to do it in django-rest-framework Currently, I am using Djoser for Registration and activation. Djoser sends activation url in the email and its working fine. How can i replace activation url by activation code of 6 alphanumeric character for account activation ?? Am Using: Django-Rest-Framework, Django-Rest-Fraework-JWT, Djoser -
Django rest framework viewset and url mixup
In my project, i have 2 different viewset of the different serializer as both get query is different than each other. However, after applying the routers, when i go to check the API output, both API were using the same url instead. I did double check to make sure both serializer and views are different but i still get the same result. Moreover, there is another url which i create with 2 different view thus 2 different router yet it work as i wanted. Did i do something wrong ? Here is the screenshot of the output to get better understanding of what im talking about. Its really weird : https://imgur.com/a/PVfcu As u can see from my code below, in the url i specify 2 different viewset for different url however, only the schedule works, the user and family url however, got problem. Here is my code: serializer class FamilySerializer(serializers.ModelSerializer): class Meta: model = Family fields = ('id', 'userId', 'first_name', 'last_name', 'gender', 'nric', 'birthday', 'relationship', 'birthTime', 'bmi', 'height', 'weight', 'bloodtype', 'allergy') class Family2Serializer(serializers.ModelSerializer): class Meta: model = Family fields = ('id', 'userId', 'first_name', 'last_name', 'gender', 'nric', 'birthday', 'relationship', 'birthTime', 'bmi', 'height', 'weight', 'bloodtype', 'allergy') class Schedule2Serializer(serializers.ModelSerializer): valid_time_formats = ['%H:%M', '%I:%M%p', …