Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest-auth login. How to return user_permissions with the key when using token authentication
Excuse me how I can recover the permissions that a user has when making the login in the system class ObtainAuthToken(APIView): throttle_classes = () permission_classes = () parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,) renderer_classes = (renderers.JSONRenderer,) serializer_class = AuthTokenSerializer def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key, 'id': token.user_id}) obtain_auth_token = ObtainAuthToken.as_view() increase the user_id, it works, it returns the id of the user, but how can I get back other parameters of the user such as the permissions or the groups that come by default in django, I hope you help me { "token": "9e1d00cffd2860c0934724c477c7928a1559ec21", "id": 79 } path('api-token-auth/', obtain_auth_token), that is my url -
How to hide tabular inline if checkbox is selected
I want to hide the Choices form if the checkbox is not selected, I've tried solving this using jquery but I can't seem to get it working... Image of what i'm trying to hide and the checkbox asset_admin.js console.log(django.jQuery‘#id_is_multiple_choice’)) django.jQuery('#id_is_multiple_choice').change(function(){ if(django.jQuery("#id_is_multiple_choice").is(':checked')) { django.jQuery(".js-inline-admin-formset inline-group").show(); console.log('showing element'); }else { django.jQuery(".js-inline-admin-formset inline-group").hide(); console.log('hiding element'); } }); The initial console.log prints out assets_admin.js:1 Uncaught SyntaxError: Invalid or unexpected token and none of the other console.logs print, this leads me to believe the id_is_multiple_choice identifier is not working which is strange because this is the checkbox in html... <div class="checkbox-row"> <input type="checkbox" name="is_multiple_choice" id="id_is_multiple_choice" checked><label class="vCheckboxLabel" for="id_is_multiple_choice">Is the question multiple choice?</label> </div> Here is my admin.py although I doubt this has anything to do with my issue class ChoiceTabularInline(admin.TabularInline): model = Choice class Media: js = ('/staticfiles/admin/js/assets_admin.js', '//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js', ) -
Why am I getting core.Model.none?
I'm working on a django based backend. I have a Submentor model. This model is going to have a list of names associated with it. So, I made a model called List. they both have a manytoMany relationship. Now, I made another model called names. This has a ManytoMany relationship with List. The list will have many names. Each Submentor will have one List each. After coding when I try to add a value in The list from admin console I get core.Name.none instead of the name in my Submentors list. What am I doing wrong? code of models :- class Names(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,blank=True,null=True) name = models.CharField(max_length=50) def __str__(self): return self.name class SAccepted_list(models.Model): saccepted_name = models.ManyToManyField(Names,blank =True, related_name='saccepted_name') def __str__(self): return str(self.saccepted_name) class SPending_list(models.Model): spending_name = models.ManyToManyField(Names,blank =True, related_name='spending_name') def __str__(self): return str(self.spending_name) class SRejected_list(models.Model): srejected_name = models.ManyToManyField(Names,blank =True, related_name='srejected_name') def __str__(self): return str(self.srejected_name) class SubMentor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) mentee_pref_count = models.IntegerField(default=3, verbose_name='Preferred mentee count') rating = GenericRelation(Rating, related_query_name='Submentor') skills = models.ManyToManyField(Skill, blank=True, related_name='subskills') courses = models.ManyToManyField(Course, blank=True, related_name='subcourses') projects = models.ManyToManyField(Project, blank=True, related_name='subprojects') saccepted_list = models.ManyToManyField(SAccepted_list,blank=True,related_name='saccepted_list') spending_list = models.ManyToManyField(SPending_list, blank=True,related_name='spending_list') srejected_list = models.ManyToManyField(SRejected_list, blank=True,related_name='srejected_list') def __str__(self): return self.user.get_full_name() def get_mentee_count(self, *args, **kwargs): if self.trainees.exists(): return self.trainees.count() … -
How to search database when hyperlink is clicked in Django?
I am using a mySQL database with Django 1.11 and I am building an inventory management web app. I would like a page to show the projects that in the database as, in effect, buttons. When a project is clicked on, the page takes the user to another page displaying the results of a search for this project in the database (showing assets assigned to the project). I have made the graphical areas displaying these 'buttons' but I have not made them clickable as I am stuck as to how to link them to a search: {% for item in project_data %} <div class="col-lg-4" > <div class="project_button"> <span> <h3>{{ item.project_name }}</h3> </span> </div> </div> {% endfor %} e.g. Clicking on 'Project Microsoft' should return a page that searches my database for all assets that belong to 'Project Microsoft'. I have made a search in my views (that returns what I need in the terminal perfectly) but I can't work out how to link this to my buttons. My views.py: def assets_by_project(request): project_data = project.objects.all() query = request.GET.get('q') if query: results = box.objects.filter(Q(project_assigned_to__icontains=query)) else: results = "NA" return render(request, 'main_app/assets_by_project.html' , { "project_data":project_data }, {"results":results}) If anyone could help me with … -
Django : Handle nested forms or alternatives?
I'm coming here in order to find a way to use my nested forms in my Django HTML template. I will try to explain my code and what I would like to do with my forms. Environnement : Django 1.11.16 Javascript/JQuery/AJAX Context : I have a Django form which is splitted in 2 parts. THe first one lets to fill some user fields like email, firstname, lastname ... Then, user has to select one or several documents from another form which contains filters in the search process. Once fields are filled and one or several documents are checked, user has to submit this form and the Django application will send an email with informations previously given. As you can see in my picture : You have the part Your informations which is the first form with submit button named Sauvegarder at the bottom and an other form including in Search publication part with Recherche button to sumbit this one. So user has to fill YOUR INFORMATIONS part, can make a search over publications, has to check one or multiple documents and finally submit all informations. Issue : The issue is : my forms are nested and I get problems with … -
DRF - Serializer fields "source" argument unclear behaviour
So, based on the following: >>> d = {'macAddress': '00:00:00:00:00:00'} >>> s = DeviceSerializer(data=d) >>> s DeviceSerializer(data={'macAddress':'00:00:00:00:00:00'}): mac_address = CharField(max_length=20, source='macAddress') >>> s.is_valid() False >>> s.errors {'mac_address': [ErrorDetail(string='This field is required.', code='required')]} Based on the simple above example and my current understanding of the source field argument I would expect the mac_address fields to be automatically mapped to the macAddress in the input data and the serializer to be valid. Why this is not the case? Thanks to anyone willing to help out :) -
Why i get a 404 error in django running server?
I get the 404 when i open up the home page of the project. it says : No ImageAlbum matches the given query. But my ImageAlbum model exist and i done migrate operations before run the server! there is the query for it: def environment(**options): env = Environment(**options) env.install_gettext_translations(translation, newstyle=False) internal_images = get_object_or_404(ImageAlbum ,title='__internal_images', ).images return env -
fcm django, send message to single user having mutiple devices
Iam new to django. I want to know how can I send firebase cloud message to a single user having mutiple devices using fcm django -
How to access Django models of PostgreSQL with scrapy
I know this has been answered before but all answers and articles I read are of old versions on Django, scrapy and Djangoitem. I read some articles and some answers I got totally screwed up and confused about what to do, When I am running the spider it is printing the output in terminal but when I go to my admin panel or site I see no new data. Can anyone tell me the working method to connect Django with scrapy. -
Django: How to join columns without foreign key with ORM
I´m new to Django and Python and I can´t get a solution to this problem, so any help is appreciated! I´m trying to join Database columns in Django, that do have a corresponding value but that value is not a foreign key. Let´s say my models are: class Order(models.Model): order_id = models.AutoField(primary_key=True) oOrder_number = models.CharField(max_length=50) ... and class Shipment(models.Model): dShipment_id = models.AutoField(primary_key=True) dTo_order = models.CharField(max_length=10) ... What I do know is, that I can use Djangos select_related command to get the values from tables, that are connected with a foreign key. But here is my problem: I can not use a foreign key in my model here, for reasons that are rooted in a third party software that is pushing the Data over my API. That software is incapable of storing a return value from the created order and use it as an identifier for the shipment (...). So finally here is my question: Is it possible to do some join with the identical fields oOrder_number and dTo_order ? My desired result is, that I can select a certain Order and get all connected shipments from the Shipment table, that will all have the same dTo_order. I know how to … -
Django dynamic filtering by passing slug from template
So I've read this article on dynamic filtering in Django; Dynamic filtering Though I had something working I needed two similar views, one to show all different categories with their slug as parameter, and a second view to show all posts from all categories without a parameter. How can I use a single ListView and pass an empty parameter from the template to show all posts from all categories in a list? urls.py urlpatterns = [ path('', views.PostListView.as_view(), name='index'), path('<slug:slug>/', views.PostbyCategoryListView.as_view(), name="category"), ] views.py class PostListView(ListView): model = Post template_name = 'index.html' class PostbyCategoryListView(ListView): model = Post template_name = 'index.html' def get_queryset(self): self.slug = get_list_or_404(Post, category__slug=self.kwargs['slug']) return Post.objects.filter(category__slug=self.slug) index.html ... <h6>Categories</h6> {% if category_list %} <ul> <li class="category-item"> <a href="{% url 'index' %}">All categories</a> </li> {% for category in category_list %} <li class="category-item"> <a href="{% url 'category' category.slug %}">{{ category.name }}</a> </li> {% endfor %} </ul> {% else %} <p>No categories</p> {% endif %} ... -
Already Exist error in DJANGO even it's unique in HTML
I have created a model form in DJANGO but on inserting value to populate the model I am getting error Coupons with this Valid coupons already exists. in my html file. I have two models : class Coupons(models.Model): valid_coupons = models.CharField(max_length=5,unique=True) def __str__(self): return self.valid_coupons class ChapterParticipated(models.Model): code = models.ForeignKey(Coupons,unique=True,on_delete=models.PROTECT) ChapterName = models.CharField(max_length=264) TeamName = models.CharField(max_length=264) def __str__(self): return self.code And my view.py contains : from django.shortcuts import render from first_app.forms import NewUserForm # Create your views here. def index(request): form = NewUserForm() if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): form.save(commit=True) return index(request) else: print('ERROR FORM INVALID') return render(request,'firstapp/firstapp.html',{'form':form}) And my forms.py contains : from django import forms from first_app.models import Coupons class NewUserForm(forms.ModelForm): class Meta(): model = Coupons fields = '__all__' What happening is when I enter the value in input field and click on submit button it shows me Coupons with this Valid coupons already exists. And it add the input to table but it still shows that error. -
Django ProgrammingError must appear in the GROUP BY clause or be used in an aggregate function
Give it any basic model say; class Post(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(_('Title'), max_length=100) content = models.TextField(_('Content html'), max_length=65000) author = models.ForeignKey('user.User', on_delete=models.SET_NULL) A query like Post.objects.annotate(Count('id')) (or any field, any annotate()) fails with the following error: ProgrammingError: column "post.created" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT "post"."id", "post"."created", "post"."ti... Using django 1.11.16, and postgres 9.4.19. As I read here in another stackoverflow question tried different django versions and postgres versions; using django 2.0, 2.1.2, postgres 9.5.. same error! Reading around I've seen that might be a problem related to SQL, but I'm having this problem only at one server running Ubuntu 18.04 (bionic). Running the query locally at Ubuntu 16.04, with django 1.11.16, or any version above that and postgres 9.4 or above runs fine in my local system.. So the problem might actually be related with some low level libraries perhaps, I'm not running complex queries, any simple annotate() with django 1.11+ fails in ubuntu 18.04 with postgres 9.4 or 9.5 -
Is there a way to import another model field inside raw_id_field?
I am trying to use a child model field inside parent admin page, is it possible to such thing? I've already tried writing a custom widget inside admin form class. So, basically I have a Base class connected to product class through foreign key. Now, I want to have the Product child class named Course inside base class admin page. This field should function as a normal raw_id_field. Django 1.11 Thanks -
Different actions on resources of the same type in one request with Django Rest Framework
I want to design endpoint that can handle multiple action on the resources of the same type in one request. I came to this idea while reading: article The request on this endpoint would look like this: [ { "id": "ID1", "method": "DELETE" }, { "id": "ID2", "method": "PATCH", "body": {"resource's": "data"} }, { "method": "POST", "body": {"resource's": "data"} } ] Lets take my serializers class ActionResourceSerializer(serializers.Serializer): HTTP_METHODS = ('POST', 'PUT', 'PATCH', 'DELETE') pk = serializers.IntegerField(min_value=1, required=False) method = serializers.ChoiceField(choices=HTTP_METHODS, required=False) body = ResourceSerializer() def validate(self, attrs): pk = attrs.get('id') method = attrs.get('method') if method in ('PATCH', 'PUT', 'DELETE') and not pk: raise serializers.ValidationError({'id': f'This field is required for {method} method.'}) if method in ('POST', 'PUT'): raise serializers.ValidationError({'body': f'This field is required for {method} method.'}) During writing the code I encountered a few problems: 1)partial flag in django serializers. By default the ActionResourceSerializer will have partial flag False. The child ResourceSerializer of ActionResourceSerializer will also 'inherit' the flag so it during validation it will raise exceptions about required fields. There is no easy way to change this behaviour. Because of this problem it came into my mind to write a custom Manager class that will itterate over the request.data and … -
Django REST Framework with Angular - selector issue
I'm using next technologies: Django 2.1.2 Django REST Framework 3.9.0. Angular 7 This is my project structure, among the others folders which I think it's uneccesary to mention here regardles to my issue: +---company | | angular.json | | db.sqlite3 | | manage.py | | package-lock.json | | package.json | | requirements.txt | | tsconfig.json | | | +---client_app | | | browserslist | | | favicon.ico | | | index.html | | | karma.conf.js | | | main.ts | | | polyfills.ts | | | styles.css | | | test.ts | | | tsconfig.app.json | | | tsconfig.spec.json | | | tslint.json | | | | | +---app | | | | app-routing.module.ts | | | | app.component.html | | | | app.component.ts | | | | app.module.ts | | | | page-not-found.component.ts | | | | | | | +---addEmployee | | | | addEmployee.component.html | | | | addEmployee.component.ts | | | | | | | +---department | | | | department-resolver.service.ts | | | | department.component.html | | | | department.component.ts | | | | | | | +---editEmployee | | | | editor-resolver.service.ts | | | | editor.component.css | | | | editor.component.html | | … -
Passing multiple arguments from django template href link to view
I am trying to pass some arguments with a link url href in a template to a view. In my template : <a href="/print-permission-document/ studentname={{studentinfo.0}} studentsurname={{studentinfo.1}} studentclass={{studentinfo.2}} doctype=doctype-studentlatepermission">Print</a> So i am trying to pass 4 arguments to my view. My view is : def print_permission_document(request, studentname, studentsurname, studentclass, doctype): file_write(studentname.encode('utf-8')+" "+studentsurname.encode('utf-8')+" "+studentclass+" "+doctype) return response My urls.py is : url(r'^print-permission-document/.+$', print_permission_document, name='print-permission-document') But i get below error : Exception Type: TypeError Exception Value: print_permission_document() takes exactly 5 arguments (1 given) -
Adding django view result from ajax as table in template
I have a django model and I view i am aggregating few columns and filtering result and returning as below def show_grid_summery(request): id = request.GET.get('id', None) context = { "summery": [], } result = Records.objects.filter(grid_id_id = id).aggregate(Sum('house_count'), Sum('point_count')) if len(result) != 0: context["summery"].append([result['house_count__sum'], result['point_count__sum']]) return JsonResponse(context) And on the template i am getting results using ajax $.ajax({ url: 'ajax/summery/', data: { 'id': ID }, dataType: 'json', success: function (data) { alert(data); var trHTML = ''; document.getElementById('summaryLabel').innerHTML = ''; $.each(data.summery , function (item) { trHTML += '<tr><td>' + item[0] + '</td><td>' + item[1] + '</td></tr>'; }); $('#summaryLabel').append(trHTML); } Now I want to fill the results record (2 columns) as a table inside the #summaryLabel tag. (preferably with headers as well). But I am unable to sort it out after many different attempts. -
Django social auth doesn't forget the session on logout
I am creating a simple app in Django that allows a user to login using google account. I am using social-django library for this purpose. I am able to login using google but Not able to logout properly. Here is my code for user logout from django.contrib.auth import logout as auth_logout def logout(request): auth_logout(request) return render(request, 'logout.html') The problem is, if I login again after logout, I will get log-in from previous log-in google account. social-django will force me to login from previously log-in account. It didn't ask me to switch the account. Even, It wont go to google signin-page. I don't have any idea, why it is happening. Any help would be appreciated. Thanks. -
Django: Having error when add auto_now in DateTimeField
I'm trying to do django api. In models.py updated_at = models.DateTimeField(auto_now=True) I got error if I add in auto_now =True. Here is my error message. django.core.exceptions.FieldError: 'updated_at' cannot be specified for Receipt model form as it is a non-editable field What should I do to solve this error? -
Django models connect with json data and use that data to templates later
This is my all code i want to send my data to models fields but how json send this..what can i do in my views to do this task.i try through url but its not working any other way please..I see almost every example related to my problem but did not find anything helpful. if anyone provide my a little bit help its a pleasure for me.. #models class Mvouchar(models.Model): related = models.ForeignKey(Signs, on_delete=models.CASCADE, null=True, blank=True) bill_no = models.CharField(max_length=80, null=True, blank=True) bill_details = models.CharField(max_length=1000, null=True, blank=True) am = models.CharField(max_length=30, null=True, blank=True) to_pay = models.CharField(max_length=50, null=True, blank=True) #views.py @csrf_exempt def jsdata(request): url = 'http://localhost:8000/jsondata/' r = requests.get(url) titles = r.json() for title in titles['data']: Mvouchar.objects.create(bill_no=title['bill_no'], bill_details=title['bill_details'], am=title['am']) // my json data [{ "BillNo": "5443", "BillDetails": "my bill", "Amount": "6000" }, { "BillNo": "443", "BillDetails": "my bill", "Amount": "3000" }, { "BillNo": "5443", "BillDetails": "my bill", "Amount": "4000" }] // script json var i = parseInt(0); var sum = parseInt(0); $(document).ready(function() { var i = parseInt(0); $("#btnAdd").click(function() { var name1 = $("#billNo").val(); var name2 = $("#billDetails").val(); var name3 = $("#amnt").val(); sum += parseInt(name3); var markup = "<tr id='" + i + "'><td>" + name1 + "</td><td>" + name2 + "</td><td>" + name3 … -
django signals on inherited profile
I have User model and a user can be of type 1 or 2. Depending on what type of user is created, I want to associate a profile to the model. If type 1, it will be a Person, and type 2 a Company. I have tried writing the code in models.py and also following the tutorial : https://simpleisbetterthancomplex.com/tutorial/2016/07/28/how-to-create-django-signals.html This is my models.py class CompanyModel(AuditedModel): name = models.CharField(max_length=64, db_index=True, verbose_name='Name', null=True, blank=True) class PersonModel(AuditedModel): name = models.CharField(max_length=64, db_index=True, verbose_name='Name', null=True, blank=True) class Tester(PersonModel,PersistentModel): # Link with user user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, blank=True, related_name='%(class)s_user') class Company(CompanyModel,PersistentModel): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, blank=True, related_name='%(class)s_user') @receiver(post_save, sender=settings.AUTH_USER_MODEL) def user_create_profile(sender, instance, created, **kwargs): if created: if instance.user_type == 1: entities_models.Tester.objects.create(user=instance) elif instance.user_type == 2: entities_models.Company.objects.create(user=instance) else: pass Without declaring urls.py, it works. But when I do and I try to import one of this models, I get this error: RuntimeError: Conflicting 'tester' models in application 'entities': <class 'entities.models.Tester'> and <class 'tektank.apps.entities.models.Tester'>. I have the example code on github if someone wants to check it out : https://github.com/gonzaloamadio/django-signals You can clone the repo, and it is working. Just uncomment in settings which app do you want to use. -
Django "Latest" filter with multiple values
I have a table that looks like this: Date Value Oct. 23, 2018 -400 Oct. 23, 2018 -1100 Oct. 23, 2018 -200 Oct. 22, 2018 -400 Oct. 22, 2018 -1100 Oct. 21, 2018 -400 I would like to return the latest value for the date, but with multiple results. filter().latest() only returns one object. I'd need three in this case. Thanks! -
Django: How to update the modified datetime after the data was updated?
I'm trying to do django api. In models.py updated_at = models.DateTimeField() I got errors if i add auto_now =True in it. In views.py class ReceiptUpdateView(RetrieveUpdateAPIView): queryset = Receipt.objects.all() serializer_class = ReceiptUpdateSerializer lookup_field = 'name' How can I get the last modified date time after the update operation is done? -
How we can modify the datepicker in django template using jquery?
template : <button type="button" class="btn btn-vilot btn-block btn-drop"> <span class="btn-sect"> <i class="icon-calendar icon-eoicon-btn"></i> </span> <span class="btn-sect"> <span>15 Sep, Sat</span> <span>Check-in</span> </button> JQUERY: $('#checkins').datepicker({dateFormat:"dd/mm/yy", minDate: '13/09/2019', maxDate: '15/09/2019'}).datepicker("setDate", '13/09/2019'); I want to change the code to the format as in the template mentioned above. Now i tried like this ,, <input class="form-control" type="text" id="checkins" placeholder="Select Date" name="checkins"> What modifications are required in JQuery?