Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Setting depth on model serializer forces relational fields to be read_only?
I was looking for a clean way to GET nested model instances, and thought I had found it with the depth attribute. But then I found evidence that this sets all fk, m2m, and probably other relational fields to read_only, which causes problems when POSTing new model instances. The evidence I found was 1) The fields disappeared from the POST form in the browsable api, 2) when I try to create a new model instance from my frontend UI, I get errors about not providing ids for the relational fields (which are non-NULL fields), and most damning 3) the OPTIONS http method returned read_only: true for those fields. So I'm wondering what the most preferred method for patching this up so that I can save new model instances from my frontend UI. Solutions I am considering include: 1) leaving the depth attribute how it is (depth=2) and writing a custom serializer that saves the relational fields correctly (in that case would I need to explicitly set the fields to read_only=False on the model?), 2) removing the depth attribute and instead write logic in the view that returns nested objects using maybe select_related instead, or 3) use 2 serializers, one with … -
Query in Django table intermediate
I am developing my app in Django 1.10 in which I have the following models: class House(models.Model): code = models.IntegerField() ...... class Appliance(models.Model): code = models.IntegerField() ........ class House_appliance(models.Model): house = models.Foreignkey(House) appliance = models.Foreignkey(Appliance) I want to make a query, where I can know all the homes that have a device in common. It may be simple but I could not do the query. I appreciate your help -
Publishing a stock Django apolicaiton to Azure - Internal Server Error
I have created a Django project in Visual Studio 2017 and I am attempting to publish the project to Azure. I have read multiple tutorials and watched some videos from Microsoft but every time I try to publish the project I get The page cannot be displayed because an internal server error has occurred. I am deleting the old files on each publish and restarting the application after as well. I am trying to publish a fresh Django project without changing anything. Could that be my problem? -
django cbv JsonResponse pagination
I have some troubles with pagination. Need paginations url like /api/cards?from=10&to=50 I try with django paginator, but it didn't work. views.py from django.views.generic import View from django.http import JsonResponse from cards.models import Card class Api(View): def get(self, request): paginate_by = 10 cards = Card.objects.all() response_cards = [] for card in cards: card_dict = {'url': card.url, 'image': card.image.path, 'type': card.type, 'preview': card.preview, 'category': card.category.title, 'title': card.title, 'has_button': card.has_button, 'button_text': card.button_text, 'button_url': card.button_url} response_cards.append(card_dict) return JsonResponse(response_cards, safe=False) urls.py from django.conf.urls import url from python_ru.views import Api from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api', Api.as_view()), ] -
Django Class Based Views Login
I am trying to convert my function based view into a class based view in Django. The functionality of the view is to display a homepage as well as a login/logout form/button. Basically, if the user is logged in, the logout button will be displayed underneath Account and if the user is already logged out, a login form will be displayed instead. So it works for my function based view: views.py def _get_login_form(request): form = UserLoginForm(request.POST or None) if request.POST and form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user: login(request, user) return form @csrf_protect def index(request): if request.user.is_authenticated(): form = forms.Form(request.POST or None) if 'logout-button' in request.POST and form.is_valid(): logout(request) form = _get_login_form(request) else: form = _get_login_form(request) info = { 'company_name' : 'Purpose VC', 'form': form, 'lorem': '''Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est … -
django.db.utils.ProgrammingError: cannot cast type jsonb[] to jsonb
I have a schema that goes like the following class Order(models.Model): order_id = models.AutoField(max_length=120,primary_key=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) delivery_address = models.CharField(max_length=200, blank=True) order_Desc= ArrayField(JSONField(),default=list, null=True); order_by = models.ForeignKey(User,null=True, blank=True,on_delete=models.CASCADE); I was initially trying to set a list of JSON objects into the order description columns but was constantly facing an issue column "order_Desc" is of type jsonb[] but expression is of type text[] while model object create. So I tried to convert order_Desc= ArrayField(JSONField(),default=list, null=True); to order_Desc= JSONField(blank =True,null=True) but I get the following error while migrating django.db.utils.ProgrammingError: cannot cast type jsonb[] to jsonb LINE 1: ...TER COLUMN "order_Desc" TYPE jsonb USING "order_Desc"::jsonb I am not sure what to do. I tried reverting back to the old state but somehow I still get the same issue which was weird. I also tried adding a new column to the model of type JSONField keeping the old state as it was but this error never seem to go. Thank for your help in advance. -
Use newsletter application on user side in Django
I am beginner to Djnago, I have installed newsletter application in my Django project but that application is use at admin side so how can I use that to user side ? I have used http://django-newsletter.readthedocs.io/en/latest/usage.html this link for installing newsletter application. -
Understanding Django internals working - Where to start?
I have dabbled with Django and Created one project successfully. What I don't understand is how exactly the whole Django Framework Works e.g. internal structure, which line of code gets executed first and why, what would be workflow between a request and response cycle, etc. ? I maybe asking the wrong questions. What would be the best way to understand the Django framework? Regards. -
Cannot have POST Data sent with python module Requests
I have 2 django server. I want to send some POST data from the server A to server B. I use this code on server A to send data (I simply follow the tutorial ) : payload = {"contenu" : Contenu, "ID" : hashage} payload_json = json.dumps(payload, separators=(',', ': ')) with open('backend/config.json') as json_data: facto = json.load(json_data) json_data.close hostnamefacto = facto["Factory"]["IP"] portFacto = facto["Factory"]["port"] reponse = requests.post('http://'+hostnamefacto+':'+portFacto+'/outil/test/', data = payload_json) On server B, I use this code to get data : try: contenu = request.POST['contenu'] except KeyError: contenu = None try: ID = request.POST['ID'] except KeyError: ID = None But ID and contenu are equal None. Does someone have an idea of how to do it ? Thanks a lot. -
Filter queryset in inline model admin based on parent attribute
Orders are created in django admin with ticket inlines. I want to filter ticket zones by event that is selected in order. class Order(models.Model): event = models.ForeignKey(Event, null=True) ... class Ticket(models.Model): zone = models.ForeignKey(Zone, null=True) order = models.ForeignKey(Order, null=True) ... class Zone(models.Model): event = models.ForeignKey('Event', null=True) ... screenshot of order creation Was used to add event in ticket inline. How can I solve this problem to get rid of event in ticket inline? Basically I need to filter queryset of inline model based on selected field of parent model. -
Testing extra actions with overridden view attributes
I have a ModelViewSet with an extra action that needs to behave differently than the rest of the viewset with respect to authentication and authorization. E.g. class MyModelViewSet(viewsets.ModelViewSet): authentication_classes = [SomeClass] permission_classes = [AnotherClass] queryset = Model.objects.some_important_ones() serializer_class = MyModelSerializer @list_route(methods=['post', 'options'], authentication_classes=[]) def action(self, request, *args, **kwargs): response_data = so_something_specific(request) return Response(response_data, status=status.HTTP_201_CREATED) The testing set up is @pytest.fixture def request(): return APIRequestFactory() def test_the_data_was_created(request): req = request.post('/api/my-model/action/', payload={}, format='json') view = MyModelViewSet.as_view({'post': 'action'}) res = view(req) assert res.status_code == 201 So the issue is that the response always complains about authentication not being provided but the action doesn't actually need it! The repr looks like this: <Response status_code=401, "text/html; charset=utf-8"> Content '{"detail":"Authentication credentials were not provided."}' Question is, how might I go about getting the callable to operate as it should? -
django prefetch_related for reverse fk's reverse fk
I have 2 simple questions about reverse foreign key in django orm class User(AbstractBaseUser): pass class Follow(models.Model): user = models.ForeignKey(User, related_name="following") following = models.ForeignKey(User, related_name="followers") class Post(models.Model): user = models.ForeignKey(User) pass above is part of my models I'm trying to find ways to get query set of User instances that will give me User instances in user.followers or user.following If this is not doable, it is fine since I found workaround. I'm just looking for best way to get this. But secondly, one of the API that I need to build retrieves Post instances which includes user with it, as well as if request.user is following the owner of the post so I added ".prefetch_related('user__followers')" to achieve query optimization so that it prevents retrieving all user.followers objects again. is this gonna do what I am trying to achieve? -
How is REQUEST object for a user in Django Views diffrentiated from one to another?
I'm not sure if what I'm doing is right or wrong. But this functionality brought me across a very esoteric event happening inside Django Views. So the code: from django.contrib.messages import get_messages from django.contrib import messages #Other required modules. @require_GET def get_form(request): #code to get a form. storage = get_messages(request) for message in storage: message = message if message: context['message'] = message html = render(request , 'some_html.html' , context) return HttpResponse(html) @require_POST def submit_form(request): #Initialize a bounded form. if form.is_valid(): form.save() messages.add_message(request, messages.INFO, success_message) else: messages.add_message(request, messages.INFO, error_message) # ABOVE LINE IS WHERE THE ISSUE OCCURS return redirect('reverse_url_mapping_to_get_form') # Above line is redirecting to "get_form" function(The function preceding this one). ISSUE : Now the strange thing I encountered occurred when I made a typo in return redirect('reverse_url_mapping_to_get_form')(The last line of the code mentioned.). Obviously I encountered Django's error page, saying that there is "NoReverseMatch". But when I reloaded the form(normal refreshing through the browser, on the "url" mapping to get_form(request)), I found that the error message which I added in the line messages.add_message(request, messages.INFO, error_message) was being brought to the html(some_html.html). Even thought the error occurred and I never redirected to the url successfully. Now I understand that messages.add_message() somewhat … -
no module named 'kronos' in ubuntu
I'm using AWS (ubuntu instance) and django. In ubuntu, I did sudo pip install django-kronos. But, When sudo python3 manage.py runserr --settings=health.settings Import Error: No module named 'kronos' happens. Kronos works well in locals. Why I get the error in ubuntu?? -
Hide certain rows with Django Tables2
I'm trying to make a table using djangotables2, and the model I have has a Boolean field called status. I want the table to hide the instance if the status equals false, but I'm not sure how to do this. Thanks. models.py class Course(models.Model): category = models.ForeignKey(Category) title = models.CharField(max_length=128) url = models.URLField() summary = models.CharField(max_length=256, blank=True) hascertification = models.BooleanField(default=False) status = models.BooleanField(default=True) views = models.IntegerField(default=0) def __str__(self): return self.title tables.py class CourseTable(tables.Table): name = tables.TemplateColumn('''<a href="{{ record.url }}">{{ record.title }}</a>''', verbose_name=u'Name') manage = tables.TemplateColumn('''Update / Delete''', verbose_name=u'Manage') class Meta: model = Course fields = ('name', 'category', 'manage',) attrs = {'class': 'table table-striped', 'id': 'course'} views.py def list_all_courses(request): context_dict = {} course_list = Course.objects.all() context_dict['courses'] = course_list table = CourseTable(course_list) context_dict['table'] = table return render(request, "courses/list_all_courses.html", context_dict) list_all_courses.html {% block main_content %} <div id="schedule_list_table"> {% if table %} {% render_table table %} {% else %} <strong>There are no courses currently.</strong> {% endif %} </div> {% endblock %} -
Value of object = calculation in models.py
I need to use objects data to create the value of another value. See the code. The last object is the one I need to change depending of the other objects. user_current_conversion_rate = models.IntegerField(default=0) user_optimal_conversion_rate = models.IntegerField(default=0) user_monthly_visitors = models.IntegerField(default=0) user_average_order_value = models.IntegerField(default=0) user_increase_conversion_rate = int(user_monthly_visitors* (user_optimal_conversion_rate/100)* user_average_order_value)- (user_monthly_visitors* (user_current_conversion_rate/100)* user_average_order_value)) -
Subprocess call error in django application
I am trying to convert topojson file in django application using subprocess.call() function. My Application running on UWSGI & NGINX My Code: geojsonfile_path="/home/testuser/jsonfile/geojson.json" topojsonfile_path="/home/testuser/jsonfile/topojson.json" command = ["topojson","-o",""+topojsonfile_path+"","--bbox","levels="+geojsonfile_path+""] subprocess.call(command) Getting Error: internal/process/stdio.js:166 throw new Error('Implement me. Unknown stream file type!'); ^ Error: Implement me. Unknown stream file type! at createWritableStdioStream (internal/process/stdio.js:166:13) at process.getStdout [as stdout] (internal/process/stdio.js:10:14) at console.js:100:37 at NativeModule.compile (bootstrap_node.js:493:7) at Function.NativeModule.require (bootstrap_node.js:434:18) at get (bootstrap_node.js:255:34) at Object.module.exports [as topology] (/usr/lib/node_modules/topojson/lib/topojson/topology.js:72:5) at output (/usr/lib/node_modules/topojson/bin/topojson:284:25) at notify (/usr/lib/node_modules/topojson/node_modules/queue-async/queue.js:47:18) at Object.await (/usr/lib/node_modules/topojson/node_modules/queue-async/queue.js:62:25) I am running command line or separate python file it's working. But i am running inside Django application this conversion is not working. Please help me. -
How to solve encoding problems when sending email via Python 2.7?
I have the following code in my Python 2.7, as the backend of my Contact form in my website: import sys import smtplib from django.http import HttpResponse form = request.POST from_addr = form['name']+' <'+form['email']+'>' to_addrs = ['myemail@address'] msg = ("From: %s\r\nTo: %s\r\nSubject: Email sent from my website form\r\n\r\n" % (from_addr, ", ".join(to_addrs))) msg = msg + form['message'] try: s = smtplib.SMTP('smtp.address') s.starttls() s.login('myemail@address', 'mypassword') s.sendmail(from_addr, to_addrs, msg.encode('utf-8')) s.quit() except smtplib.SMTPException: return HttpResponse(status=404) return HttpResponse(status=200) This code works, BUT... if I send a message like "¿En qué año estamos?" it arrives to my inbox as "En qu ao estamos?" (it deletes some characters). How can I solve this? -
Django : save the user that has created the object instance
I have a model Package with a field owner that should contain the user ID that has created the object instance. I thought about overriding the save() method but I didn't figure out how to get the logged in user. I have proceeded this way class Package(models.Model): source = models.CharField(max_length=20) destination = models.CharField(max_length=20) date_estimation = models.DateTimeField() owner = models.ForeignKey('auth.User', related_name='packages', on_delete=models.CASCADE) def save(self, *args, **kwargs): #WAHT TO DO HERE ? super(Package, self).save(*args, **kwargs) How can I save the current logged in user ? Thank you -
Django forms ChoiceField not selecting the wanted value
I created a django form (IssueForm) which is meant to be used to register an object which is instance of one of my models (Issue). Following are the model: model.py class Issue(models.Model): TYPE_FIELDS = [ ("Math", "Math"), ("Physics", "Physics"), ("Programming", "Programming"), ("Arts", "Arts") ] issue_text = models.TextField(default="Please insert text") issue_description = models.TextField(default="Newly created") issue_deadline = models.DateField() issue_field = models.CharField(max_length=30, choices=TYPE_FIELDS) published_by = models.ForeignKey(User, on_delete=models.CASCADE, default=None) def __str__(self): return self.issue_description the form used: forms.py class IssueForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): self.user = user super(IssueForm, self).__init__(*args, **kwargs) TYPE_FIELDS = [ ("Math", "Math"), ("Physics", "Physics"), ("Programming", "Programming"), ("Arts", "Arts") ] issue_text = forms.CharField(widget=forms.Textarea, required=True) issue_description = forms.CharField(widget=forms.Textarea, required=True) issue_deadline = forms.DateField(required=True) issue_fields = forms.ChoiceField(choices=TYPE_FIELDS, required=True) class Meta: model = Issue fields = [ 'issue_text', 'issue_description', 'issue_deadline', 'issue_fields' ] def save(self, commit=True): issue = super(IssueForm, self).save(commit=False) issue.issue_text = self.cleaned_data['issue_text'] issue.issue_description = self.cleaned_data['issue_description'] issue.issue_deadline = self.cleaned_data['issue_deadline'] issue.issue_fields = self.cleaned_data['issue_fields'] if commit: issue.published_by = self.user issue.save() return issue and the related view: views.py def create_issue(request): if ExtendedUser.objects.filter(user=request.user).exists(): if request.method == 'POST': form = IssueForm(request.user, request.POST) if form.is_valid(): form.save() return redirect("/issues") else: form = IssueForm(request.user) args = {'form': form} return render(request, "issues/create_issue.html", args) else: raise Http404("You are not allowed to perform this action") The forms works … -
Bulk creation of objects that contains multiple foreign keys in Django
I have the following models in my DJango app: class Ratings(models.Model): field1 = models.ForeignKey(Table1) field2 = models.ForeignKey(Table2) field3 = models.ForeignKey(Table3) field4 = models.ForeignKey(Table4) field5 = models.ForeignKey(Table5) class Values(models.Model): grade = models.ForeignKey(Grade) rating = models.ForeignKey(Ratings, related_name='ratings') value = models.TextField(blank=True, null=True) I am using the following code to create instances of the Rating table: rating_obj = Ratings( field1_id=id1, field2_id=id2, field3_id=id3, field4_id=id4, field5_id=id5 ) rating_obj.save() The above method works but it is way too slow. I have to create around 30 instances of this model. I cant use bulk_create as i need the reference of the rating_obj for creating Values objects. I have already tried using raw_sql for insertion but to no avail. Can someone suggest a better way for achieving the same.? P.S. Table1,Table2..etc already have db_index=True in their primary keys. -
django ListView - custom queryset by joinining with another model
I have the following two models. class Product(models.Model): product_group=models.ForeignKey('productgroup.ProductGroup', null=False,blank=False) manufacturer=models.ForeignKey(Manufacturer, null=False,blank=False) product_type=models.CharField(max_length=2, choices=PRODUCT_TYPE, null=False,blank=False) wheel_position=models.CharField(max_length=1, choices=FRONT_BACK, null=False,blank=False) opening_stock=models.PositiveIntegerField(default=0) class Meta: ordering=['product_group','manufacturer'] unique_together = ('product_group', 'manufacturer','product_type','wheel_position') def get_total_stock_in(self): sum=Stock.objects.filter(product=self.id, ttype='I').aggregate(Sum('quantity')) if sum['quantity__sum'] is not None: return sum['quantity__sum'] else: return 0 def get_total_stock_out(self): sum=Stock.objects.filter(product=self.id, ttype='O').aggregate(Sum('quantity')) if sum['quantity__sum'] is not None: return sum['quantity__sum'] else: return 0 def get_balance_stock(self): return (self.opening_stock+self.get_total_stock_in() - self.get_total_stock_out()) and class Stock(models.Model): product=models.ForeignKey('product.Product', blank=False,null=False) date=models.DateField(blank=False, null=False,) quantity=models.PositiveIntegerField(blank=False, null=False) ttype=models.CharField(max_length=1,verbose_name="Transaction type",choices=TRANSACTION_TYPE, blank=False) added_date=models.DateTimeField(blank=False, auto_now=True) I have a ListView subclass to list all products. class ProductList(ListView): model=Product paginate_by = 20 def get_queryset(self): queryset = super(ProductList, self).get_queryset() queryset = queryset.prefetch_related('product_group','product_group__category','manufacturer') return queryset.order_by('product_group__category','product_group') I need to display the total stock in, total stock out and available balance along with each product in the list-view. Right now, I'm calling the functions get_total_stock_in(), get_total_stock_out() and get_balance_stock() defined in the Product model . But this creates a lot of repeated queries on the database. How do I add these data into the queryset of ListView? (I hope I can do it with by combining Count() and filter(), but I'm clueless on how to proceed.) Thanks for any help. -
How to set initial value of Django-Select2 widget in Django
I am using the django-select2 plugin for a field that lets the user select an institution from a list in the database( driven by AJAX), and it works fine. Here is the field in forms.py institution = forms.CharField( widget = ModelSelect2Widget( queryset=Institution.objects.all(), attrs={'class': 'form-control'}, model=Institution, search_fields=['name__icontains'], max_results=500, ), Using the same form, the user can edit/change the previous selected Institute. For this, however, I would like to set the initial selected value of the field as the previously selected Institution. This is has caused me a lot of trouble as I am unable to set an initial value for the plugin despite trying many things. Ideally I am looking to set the initial value of the plugin without using any Javascript(using only Django form options) , something like : current_instutition = Institution.objects.get(user=page_user) form.fields['institution'].initial = current_institution (the above doesn't work) I've tried using the Select2 placeholder option to set this manually during page load using the following Javascript code: $("#id_institution").djangoSelect2({ placeholder: { id: '123', text: 'My Institution' } }); This doesn't seem to do anything at all.(The plugin still loads, with an empty(or no) placeholder) .I'm not sure if django-select2 overrides the manual Select2 options. Any help is appreciated. Thanks! -
create form for a intermediate table in a many to many relationship
I have a model called Semester: class Semester(models.Model): sem_year = models.IntegerField(default=datetime.date.today().year, verbose_name='Semester Year') questions = models.ManyToManyField(Question, through='QuestionSemester') A couple tables that are categories and Questions: class QuestionCategory(models.Model): cat_title = models.CharField(max_length=200,verbose_name='Category title',unique=True) cat_create_date = models.DateField(default=timezone.now) class Question(models.Model): category = models.ForeignKey(QuestionCategory, related_name='question_category') question_title = models.CharField(max_length=200) And also an intermediate table that is the relationship between the above mentioned tables: class QuestionSemester(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) semester = models.ForeignKey(Semester, on_delete=models.CASCADE) question_deadline = models.DateTimeField() question_visibility = models.BooleanField() I want to create a form that shows All the questions from Question table and their categories from category table with a checkbox beside them plus a select field for the semester so that the user can select the year for the semester and also select the questions and then press submit to submit the form in the QuestionSemester table (intermediate table). I have been digging for several hours and still haven't got a clue on how to approach this. Even some ideas are very much appreciated. -
How to set python functions based on input from the web interface?
I was wondering if there's any way I could dynamically generate a def function based on input from a Django website? For example, def constraints1(x) return x[1] - x[2] def constraints2(x) return x[2] - x[3] Since I don't know the size of x, I can't really pre-set all the constraints. I was thinking if I could use a loop to automatically generate all these constraint functions? Thanks!