Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django | How to make a reverse Relationship with two models
i want to make a ticket system. I have the main model (TicketSystem) and a model with the messages from the users (TicketSystem_Messages). In the model "TicketSystem_Messages" is the ForeignKey to the model "TicketSystem". Here is my code: class TicketSystem(models.Model): subject = models.CharField(_('Subject'),max_length=30, blank=False, default="N/A") message = models.TextField(_('Message'), null=False, blank=False) created_date = models.DateTimeField(_('Date'), default=datetime.utcnow().replace(tzinfo=utc)) fertig_date = models.DateTimeField(_('Date'), default=datetime.utcnow().replace(tzinfo=utc)) class TicketSystem_Messages(models.Model): user_name = models.ForeignKey(User) status = models.ForeignKey(TicketSystem_Status) ticketid = models.ForeignKey(TicketSystem) message = models.TextField(_('Message'), null=False, blank=False) created_date = models.DateTimeField(_('Sent'), default=datetime.utcnow().replace(tzinfo=utc)) At the moment i get the Tickets without the Messages: sql_TicketSystem = TicketSystem.objects.filter(id=kwargs['pk']) I want to make a LEFT JOIN like this SELECT * FROM TicketSystem LEFT JOIN TicketSystem_Messages ON Ticketsystem.id = TicketSystem_Messages.ticketid I heard something about "select_related" and "prefetch_related" and tried it but it does not work. -
save search query result into a model in django
Please I have the following code in my view,all I want is to save the query result( if it's true)in to another model.so how do I achieve this please? def scan(request): print(request.session) if request.method == 'POST': srch = request.POST['srh'] if srch: match = ReportModel.objects.filter(Q(serialNumber__iexact=srch)) if match: return render(request, 'admin/scan.html', {'sr': match}) else: messages.error(request, 'No result yet for the requested device!') else: return redirect('/scan/') return render(request, 'admin/scan.html') -
How to provide values form field Calss
Hi i have a form class forms.py class HealthCheckForm(forms.Form): locality = forms.ChoiceField() How can i do something like this? HealthCheckForm({'locality':choices=SELECTED_CHOICES}) -
Django - pass URL as URL Parameter
I have the following URL pattern: path('my_path/(?P<url>\w+)/$', views.my_view) where url is a url such as https:www.google.com Howevever my function returns an error get_external_job_ad() got an unexpected keyword argument 'format' What is the right way to pass an url as url parameter? -
overwriting Django Model
i need to update the columnvalue of a particular field everytime i create a new entry to the table with some hash value. i created the model as follows: class ICOExchange(models.Model): id = models.CharField(default=create_UUID('user '), max_length=100, primary_key=True) def set_id(self): self.id = create_UUID('user ') where create_UUID(arg) is a function that generates a hash value according to some inputs and timestamp. But while adding datasets through the admin panel it doesnt refresh the id and id remains the same. -
Remove keys from array in django rest framework serializer
Consider this json response from one of my endpoint in a django rest framework web app. { "links": { "next": null, "previous": null }, "count": 2, "total_pages": 1, "results": [ { "movie": { "id": 13, "title": "Living Doll", "genres": [ { "genre": "Horror" } ], "imdbID": "tt0100038", "poster": "/8VUR5PN3yqRoK9M65BASDrZ4Imd.jpg", "language": "en", "favourite": false, "watch_later": true, "watched": false } }, { "movie": { "id": 230, "title": "Porno", "genres": [ { "genre": "Romance" }, { "genre": "Comedy" } ], "imdbID": "tt0100388", "poster": "/dNkLerizbd53flidKiippvBTns4.jpg", "language": "pl", "favourite": true, "watch_later": true, "watched": false } } ] } See the redundant movie key in each elements in the array. How do I remove them to make it like this? { "links": { "next": null, "previous": null }, "count": 2, "total_pages": 1, "results": [ { "id": 13, "title": "Living Doll", "genres": [ "Horror" ], "imdbID": "tt0100038", "poster": "/8VUR5PN3yqRoK9M65BASDrZ4Imd.jpg", "language": "en", "favourite": false, "watch_later": true, "watched": false }, { "id": 230, "title": "Porno", "genres": [ "Romance", "Comedy" ], "imdbID": "tt0100388", "poster": "/dNkLerizbd53flidKiippvBTns4.jpg", "language": "pl", "favourite": true, "watch_later": true, "watched": false } ] } Also see the genres. They need to be like the second json without the keys. The serializer for the aboove json response is given β¦ -
Row based permissions in Django
I have a simple Django model which looks roughly like this: from django.contrib.auth.models import Group from mylogapp.models import LogType class Log(models.Model): responsible_group = models.ForeignKey(Group) description = models.TextField() log_type = models.ForeignKey(LogType) There will be several million rows in the database table. Row based permission for the django admin interface should get implemented. If the current user is in the "responsible_group", then he is allowed to see and modify it. AFAIK django guardian is not well suited for this. See this related page: https://django-guardian.readthedocs.io/en/stable/userguide/performance.html Even solution "Direct foreign keys" does not match. The current model already contains everything which is needed to filter the rows. How to enable row-based-permission for django and use the Log model for permission checking? -
Django Method Not Allowed Status 405 on a Ajax call to a foreign key model
Intro: I am making a stackoverflow style Question and Answer App, where a user can ask a question and other users can answer the question. Users Also have the option to Upvote and Downvote both questions and Answers. I am using Ajax calls to asynchronously update the upvote and downvote. I was successful is asynchronously upvote and downvote Questions. but somehow the same code is giving me a Method Not Allowed Status 405 on the Answer upvote/downvote (See Images below) I believe I may me doing something wrong in the URLs or in the calling URL function in the model Models.py class Answer(models.Model): question = models.ForeignKey(Question, related_name='answers') author = models.ForeignKey(User, related_name='answers') text = models.TextField() ansup = models.ManyToManyField(User, blank=True, related_name='answer_ansup') ansdown = models.ManyToManyField(User, blank=True, related_name='answer_ansdown') def get_absolute_url(self): return reverse('questions:single', kwargs={'username': self.question.user.username, 'slug': self.question.slug}) def get_ansup_url(self): #This is the 1 of 2 place I believe I may be doing something wrong return reverse('questions:ansup', kwargs={'username': self.author.username, 'pk': self.pk}) def get_ansdown_url(self): return reverse('questions:ansdown', kwargs={'username': self.author.username, 'pk': self.pk}) Below are the views.py class AnswerAnsupToggle(LoginRequiredMixin, RedirectView): def post(self, *args, **kwargs): pk = self.kwargs.get('pk') obj = get_object_or_404(Answer, pk=pk) user = self.request.user context = {"answer": obj} if user in obj.ansup.all(): obj.ansup.remove(user) else: obj.ansup.add(user) if self.request.is_ajax(): html = render_to_string("questions/answer_upvote_section.html", β¦ -
Serializer get RelatedField
serializers.py class SliderImageSerializers(serializers.ModelSerializer): class Meta: model=SliderImage fields='url','rank' class ItemVariationsSerializer(serializers.ModelSerializer): # items = ItemsSerializer(many=True, read_only=True) class Meta: model = ItemVariation fields ='price','item_code','image' class RestaurantSerializers(serializers.ModelSerializer): items = ItemVariationsSerializer(many=True, read_only=True) sliders = SliderImageSerializers(many=True, read_only=True) class Meta: model=Restaurant fields=('__all__') models.py class ItemVariation(models.Model): restaurant=models.ForeignKey(Restaurant,on_delete=models.CASCADE) item=models.ForeignKey(Item,on_delete=models.CASCADE) price=models.IntegerField(blank=True,null=True,default=0) item_code=models.CharField(max_length=500) keyword= models.ManyToManyField(Keyword) image=models.ImageField(upload_to='dishes/', blank=True, null=True) def __str__(self): return str(self.id) response: { "id": 1, "sliders": [ { "url": "/media/restaurant/download_2.jpeg", "rank": 1 } ], "name": "Haveli", "email": "test@tet.com", "web": "wdew", "short_description": "dsfsdf", "description": "fsdfsd", "phone": 21315, "lat": 30.704649, "lng": 76.717873, "address1": "dsff", "address2": "vfdg", "city": "sdfds", "state": "fs", "postalcode": "sdfsd", "avg_rating": 1, "price": 0, "restaurant_type": 1, "keywords": [ 1, 2, 3 ] } I need to add ItemVariationsSerializer to RestaurantSerializers response i need response like { "id": 1, "sliders": [ { "url": "/media/restaurant/download_2.jpeg", "rank": 1 } ], "name": "Haveli", "email": "test@tet.com", "items":[ { "price":"213" "item_code":"testr" } ] "keywords": [ 1, 2, 3 ] } -
What is the correct way to delete a child node in django-mptt tree structure
I am using Django: >>> django.VERSION (1, 11, 15, u'final', 0) MPTT: django-mptt 0.9.1 In Models: from mptt.models import MPTTModel, TreeForeignKey class Location(MPTTModel): id = models.AutoField(primary_key=True) name = models.CharField(max_length=75,null=False) parent = TreeForeignKey('self', on_delete=models.PROTECT, null=True, blank=True) I can view and add properly as per django-mptt documentation. But I am not able to delete a child node. It messes up all the tree structure. Here is how delete is used in views: Location.objects.get(id=loc_id).delete() where loc_id is the id of the node i want to delete. I am not sure how to use Delete properly or maybe there is a bug in mptt. I looked up for any example on its official doc. It says nothing more than the following on this topic: class mptt.models.MPTTModel(*args, **kwargs) Base class for tree models. class Meta abstract = False MPTTModel.delete(*args, **kwargs) Calling delete on a node will delete it as well as its full subtree, as opposed to reattaching all the subnodes to its parent node. There are no argument specific to a MPTT model, all the arguments will be passed directly to the djangoβs Model.delete. delete will not return anything. Thanks -
How to send a graph (highcharts) via email in django using email templates?
One of my requirement is to send a weekly graph report to the team members. For that I am using highcharts.js to display graphs on the UI. I need to send the same graph in mail using django. Is it possible to include internal css and javascript/jquery in the email template? In my case internal css and js are displaying in the email. Is there a way to send graphs in email using django? -
How to Register different type user with profile in django?
I am new to django and I started a new project. shortly, I want to register different type of users (Teacher, Student, Stuff) with their profile picture. I made a one to one field from user to profile and below is my code and I get the following error. if you have any suggestion for my registration purpose, I want to register a different type of user with a profile picture. models.py from django.db import models from django.contrib.auth.models import User,AbstractUser from django.conf import settings from django.dispatch import receiver from django.db.models.signals import post_save class User(AbstractUser): USER_TYPE_CHOICES = ( (1,'Student'), (2,'Teacher'), (3,'Stuff') ) profile = models.OneToOneField(on_delete=models.CASCADE, related_name='user') user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES) class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='profile') photo = models.ImageField(upload_to='users/%Y/%m/%d/') def __str__(self): return 'Profile {}'.format(self.user.username) its the form from django import forms from django.contrib.auth.models import User from .models import Profile class UserCreationForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput, label='Password') password2 = forms.CharField(widget=forms.PasswordInput, label='Repeat Password') class Meta: model = User fields = ('username', 'first_name', 'last_name') def clean_password(self): cd = self.cleaned_data if cd['password']!=cd['password2']: raise forms.ValidationError('password no match') return cd['password2'] class ProfileCreationForm(forms.ModelForm): class Meta: model = Profile fields = ('photo',) its my view module from django.shortcuts import render from .forms import ProfileCreationForm, UserCreationForm from .models import Profile from django.http β¦ -
Error while using iPython for executing a python script
I am using iPython 5.5.0, when i run my script which takes input for input.csv I get the following error: In [1]: %run "C:\myrootFolder\pythoncode\testfile.py input.csv" ERROR:root:File `u'In [1]: %run "C:\myrootFolder\pythoncode\testfile.py input.csv.py' not found. Same way I am unable to execute.. %run "C:\Python27\Scripts\mysite\manage.py runserver" Similar error occurs, What am I doing wrong. TIA. -
Nested Serializer with 3 Foreign Key. How to implement GET and POST?
class Author(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) age = models.IntegerField() // class Editor(models.Model): first_name = models.CharField(max_length=255) date_edition = models.DateTimeField(default=datetime.now) status = models.BooleaField(default=True) // class Book_Manufacturer(models.Model): name = models.CharField(max_length=255) year_production = models.DateTimeField(default=datetime.now) // class Book(models.Model): author = models.models.ForeignKey(Author, on_delete=models.CASCADE) editor = models.models.ForeignKey(Editor, on_delete=models.CASCADE) book_manufacturer = models.models.ForeignKey(Book_Manufacturer, on_delete=models.CASCADE) title = models.CharField(max_length=255) year = models.DateTime(default=datetime.now) Can anyone help me? How I would serializer a Book with 3 foreign_key and show all details when I have a GET method? (Al details = Book details + Book_Manufacturer + Editor + Author) Also what about the POST method, how would it be implemented If I want to create a Book with all the information? PS: In the real application I have a model with 3 foreign key, just like the exemple. I used a example here with a naive approach, it's not my real model fields and class names XD, is just a example. -
Django auto logout and page redirection
I have an application whose backend is written using django and python. I want to implement auto logout feature in my applcation. For this , I used following django built-in features : SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_COOKIE_AGE = 40 SESSION_SAVE_EVERY_REQUEST = True I have also used LOGOUT_REDIRECT_URL to redirect the page after logout. But this doesn't help. After 40 seconds, logout happens but it is not visible in frontend, login page comes only if the user refreshes the tab or makes any request in the tab. If I close the browser and open it again , the home page appears with no data as the data are user specific . and if refresh is done of tab is done , the tab is redirected to login page. I want to achieve 2 scenarios: If the auto log happens the user should be automatically redirected to login page. If the user closes the browser window and opens it again then user should be displayed the login page of the application. Any suggestions on how to achieve these scenarios ? Any help would be appreciated. Thank you. -
How to revoke has_delete_permission for certain users in Django?
In the Django templates there are conditions like "can_delete_related"... It is set somewhere else: can_delete_related=related_modeladmin.has_delete_permission(request)... How is it possible to define has_delete_permission for certain users? -
Django slots + foreign key save silently fails
I have found that when Django2.0 model has ForeignKey and mixin with slots it's .save() method doesn't work. While it's quite specific case, it is still kinda surprising, because there is no any Exception, data is just not saved. Here is an example: from django.db import models class FooSlots: __slots__ = ["bar", "value"] class Bar(models.Model): pass class FooSloted(models.Model, FooSlots): value = models.FloatField(default=0.42) bar = models.ForeignKey(Bar, on_delete=models.CASCADE, related_name="foo_sloted" ) def check_sanity(source, bar, value=0.5): instance = source.objects.create(bar=bar) instance.value = value instance.save() instance = source.objects.get(pk=instance.pk) assert instance.value == value # Must be true! So check_sanity(FooSloted, Bar.objects.first()) will raise assertion error, because data won't be saved, but there is no exceptions from Django itself. Even more confusing that in case bar is not a ForeignKey, but e.g. a CharField, everything is ok. Also when slots are not specified, there is no such problem too. Is there any explanation for such behavior? PS. To make this example less fictional: I have several "Foo"-like models with keys to different "Bar" which are populated in similar way elsewhere. FooSlots is used to enforce same interface and to treat given data for different Foo in a same way. -
django search by one field and update or create on another field(s)
For example: test_table Field, Type, Null, Key, Default, Extra 'username', 'varchar(64)', 'NO', 'PRI', NULL, '' 'status', 'tinyint(1)', 'NO', '', NULL, '' I want to search by username='john', if it's exist, then update status to 1; Django has update_or_create function but it works when both username and status exist; e.g. data already in table: username:john status:0 I want to change status to 1 If I use update_or_create(), since there is no row like "username:john, status:1", so it will "create", not "update" status to 1 Of course you can always : search first, then "if...create; else...update". But I wonder if there is some django functions I can use or something I didn't notice when using update_or_create(). Thanks! -
How to add a `or` condition filter in this prefetch_related query filter?
I have a qs filter code like bellow: qs2 = qs1.filter(ipv4s__ip=ip).prefetch_related( Prefetch('ipv4s', queryset=IPv4Manage.objects.filter(ip=ip))) now I want to add a OR logic filter in this filter. how to add a or condition filter in this query filter? I mean I want to add a or condition filter like this: it will meet this filter(ipv4s__ip=ip).prefetch_related( Prefetch('ipv4s', queryset=IPv4Manage.objects.filter(ip=ip))) condition or it will meet ip='1.1.1.1'. How to make this come true? -
How to get app config data from a file in s3 bucket before user logged in to the app for a multi-tenant application?
I am using s3-bucket to store app config data for multi tenant application. I need tenant info saved in public file(.json) in s3-bucket before client is logged in to the application. For example, app config data might be client logo and some custom title/sub-title for each tenant and etc. I am trying to fetch file content based on sub-domain. So, I need to fetch the client data, while rendering the login component itself. I am using aws-sdk tool in client side, but am facing 'missing credentials` error. I am not getting, How to achieve this?? thanks and regards SHASHIDHAR N K -
Django CK-Editor Custom Plugin with Dialog
I work with a website in Django, Django CkEditor 5.2.2 I would like to create a custom plugin to insert a little html. I need a dialog in my plugin to select the logo I want in my html, the title and content. I followed rigourously the widget tutorial on the CK Editor website, but the line: editor.widgets.add( 'simplebox', { button: 'Create a simple box' } ); doesn't work. So I tried to insert a button with: editor.ui.addButton( 'simplebox', { label: 'Ajouter un encadrΓ©', command: 'insertTextBox', toolbar: 'yourcustomtools', }); This works, I have a button in my toolbar that inserts html. But I Cannot manage to link it to any dialog... currently my code is in my simplebox/plugin.js CKEDITOR.plugins.add('simplebox', { requires: 'widget', icons: 'simplebox', init: function (editor) { CKEDITOR.dialog.add('addSimpleBox', this.path + 'dialogs/simplebox.js' ); editor.ui.addButton( 'simplebox', { label: 'Ajouter un encadrΓ©', command: 'insertTextBox', toolbar: 'yourcustomtools', }); editor.addCommand( 'insertTextBox', { exec: function( editor ) { editor.insertHtml( '' + '<div class="text-box">' + '<div class="logo">Logo</div>' + '<div class="content">' + '<div class="content--title">Le titre</div>' + '<div class="content--content">Le contenu</div>' + '</div>' + '</div>' ); } }); } }); And in my dialogs/simplebox.js, that's a mix of the tutorial and what I tried... CKEDITOR.dialog.add( 'simplebox', function( editor ) β¦ -
Extand CreatesUserForm and keep l10n / i18n built-in feature
I am discovering Django (v2.1.1) and want to set up a signin page in which I have 2 emails fields, if the 2 fields are identical, I call form.is_valid(). The project tree : βββ manage.py βββ requirements.txt βββ project β βββ __init__.py β βββ settings.py β βββ urls.py β βββ views.py β βββ wsgi.py β βββ templates β βββ base.html β βββ project β β βββ home.html β βββ registration β βββ logged_out.html β βββ login.html β βββ signin.html βββ app βββ __init__.py βββ admin.py βββ apps.py βββ models.py βββ urls.py βββ views.py βββ migrations βββ templates βββ app βββ home.html Internationalization config in project/settings.py : # (β¦) # Internationalization LANGUAGE_CODE = 'fr-fr' USE_I18N = True USE_L10N = True # (β¦) With a basic django signin view it works well: project/views.py : from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm def index(request): return render(request, 'project/home.html', {'context':'project index'}) def signin(request): # (β¦) form = UserCreationForm() return render(request, 'registration/signin.html', {'form': form}) I have a nice French translated HTML form (except for the submit button) : Let's add an email field in the form, email is a built-in user fields (as first_name & last_name) so I just β¦ -
How to parse JSON Array of objects in python and load it to template?
How can we parse json array of objects in python. I have the ff code below in getting the data. How to parse it where in we can load the p_id and item_name on the tempalte select option value ? products = requests.get('http://123.89.166.42:803/api/1.0/data', headers=headers).json() context['products'] = products template : <select> {% for product in products.result %} <option value="{{ product.p_id }}">{{ product.item_name }}</option> {% endfor %} </select> Data : http://dpaste.com/0BHS9TP -
Django - POST method not working for those forms created within a FOR loop in template
I'm using a for loop in a template to create multiple forms with method="post" that work with Ajax. But only the form for the first element of items_list works fine, the rest do not work at all showing error 405 0 Method Not Allowed. I think they all should work the same way. And just wondering if this issue was caused by a for loop or something else. cart_items.html: <script> $(document).ready(function () { $("#remove").click(function (event) { event.preventDefault(); $.ajax({ url: '{% url "cart:remove_from_cart" %}', type: "POST", dataType: 'json', data: {bookID: $('#idInput').val()}, success: function (response_data) { alert('works fine') }, error: function (response_data) { console.log('error occurred'); } }); }); }); </script> {% for book in items_list %} <div class="items"> <p id="title"> {{ book.book.title }}, quantity: {{ book.quantity }} </p> <form method="post"> {% csrf_token %} <input id="idInput" value="{{ book.book.id }}" > <button id="remove" type="submit"> Remove</button> </form> </div> {% endfor %} The code in the function body below is just for testing. Once the first form works, I guess the problem was not caused by the function view. cart/views.py: @csrf_exempt def remove_books(request): cart = Cart.objects.get(user=request.user) if request.method == 'POST': passed_id = request.POST['bookID'] secured_id = int(passed_id) response_data = { 'quantity': secured_id } return JsonResponse(response_data) -
Django, how to include pre-existing data in update form view
I am unable to see pre-existing form data when updating. The forms work fine, after submitting the database is updated, but in order to submit the user must enter all form data (including data that will not be updated). While reentering, the previous data is not visible. Is there a way to display the current data of the model instance being updated in the form fields? Forms: UpdateSomethingForm(forms.ModelForm): class Meta: model = Something fields = ['field1', 'field2', 'field3'] Views: def update_something(request, object_pk): form = UpdateSomethingForm() context_dict = {} try: instance = Something.objects.get(pk=object_pk) context_dict['instance'] = instance except Something.DoesNotExist: context_dict['instance'] = None if request.method == 'POST': form = UpdateSomethingForm(request.POST, instance=instance) if form.is_valid(): form.save(commit=True) return HttpResponseRedirect('/home') else: print(form.errors) context_dict['form'] = form return render(request, 'form.html', context=context_dict) Html: <form role="form" method="post"> {% csrf_token %} {{ form|bootstrap }} <div class="form-group"> <button type="submit" class="btn btn-primary">Submit</button> </div> </form>