Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to GET data into views.py then POST to database
I am newbie on python and Django, just learn and follow online tutorial. But now iam facing a issues that i cannot find or i dont know what keyword should i put on the search to find the solution. i have this on my views.py salary = 212 class EmployeeCreateView(CreateView): fields = ('id','name', 'salary') model = models.Employee def form_valid(self, form): self.object = form.save(commit=False) self.object.name = salary self.object.save() return super(ModelFormMixin, self).form_valid(form) my question is, how make 'salary' reference to database?... example I have atendance table : id | employe_id | working_days | -------------------------------- 1 | 123 | 21 | i want 'salary' reference to atendance table, so i can make salary = working_days * 50 thank you for helping newbie. -
Django Generic Views disabling fields
One Modelform consist two field which is not inserting from front end, but the data is setting in coding level. One is Case No filed and the value updating from sequence and second is a forign key field mapped to user for log purposes. self.fields['last_modifieduser'].queryset = Profile.objects.filter(user=profile.user,widget=forms.HiddenInput()) I made the two fields read only and disabled respectively. Whenever doing form validation there two fields getting error. -
Displaying a ChartJS chart in Django
I am currently trying to implement a graph into my django application. I have created a HTML page to display hard-coded details from my views.py class. When I load the webpage however I can't see the chart at all. Below is how i tried to implement the graph: Views In this class I am creating the views that will display on the graph. I have hard coded in some data for the time being just to get the graph up and running. User = get_user_model() #where i am viewing the chart, calling the html page. class ChartView(View): def get(self, request, *args, **kwargs): return render(request, 'nutrition/chart.html', {"users": 10}) class ChartData(APIView): authentication_classes = [] permission_classes = [] #hard-coded data that i am trying to display on the chart def get(self, request, format=None): qs_count = User.objects.all().count() labels = ["Users", "Blue", "Yellow", "Green", "Purple", "Orange"] default_items = [qs_count, 12, 22, 13, 11, 15] data = { "labels": labels, "default": default_items, } return Response(data) urls The urls are i am using to display the pages are an extension onto nutrition/, urls. urlpatterns = [ #url for the webpage to display the chart url('^chart/$', ChartView.as_view(), name='chart'), #url to show the data using the django rest_framework url('^api/chart/data/$', … -
Form and mptt mix in a singlepage application with django
I am developing a web application which looks like desktop application. When application starts certain elements are visible by default. Among which, on the right handside I have a menu showing a directory structure in the form of a tree. For this I am using django-mptt and jquery.fancytree. I also have a navigation pulldown menu with few pages of a form. This form originally is hidden by css. When user clicks on the pulldown, this paginated form displays(only one page is shown for the clarity of the program). When user saves (post) the form I want it to post to the single view that created the singlepage. I have two problems: 1) On form post, this error shows up (source of error line 192): VariableDoesNotExist at / Failed lookup for key [drive_nodes] in "[{'True': True, 'False': False, 'None': None}, {}, {}]" ... 191 <ul id="drive-tree-data"> 192 {% recursetree drive_nodes %} 193 <li class="context-menu-one"> ... 2) On form cancel, the single page is reloaded!! I think my url is not correct in both problems and that is why the drive_nodes variable is not defined anymore and page is reloaded! Although, I know, the post goes back to the same single entry, … -
Django 2.0 CSS missing for chrome browser
I'm learning Django2.0 these days and tried the tutorial here. However, when it comes to the admin page part, the css style seems missing in Chrome browser: However, when I visited 127.0.0.1:8000/admin in IE, Firefox or even Safari, everything went fine: I'm using the latest version of Chrome. Why? What can I do to fix this? -
django.db.utils.ProgrammingError: data type character varying has no default operator class for access method "gin"
I am working on a django project,where i want to create gin indexing on my model's attribute. I want to create gin indexing on SchoolName = models.CharField(max_length=200, blank=False, null=False) but i am getting this error django.db.utils.ProgrammingError: data type character varying has no default operator class for access method "gin" help me to figure out this error -
Django: Generate PDFs
I am currently building a ticketing page using Django. I now have to find the 'best way' to generate a PDF ticket, which ticket buyers can download from our Server. I looked into different ways and apps including ReportLab in the official documentation. The ticket will include personal information and I am also planning to include a Bar/QR code on the ticket. The question I am struggling with, is which of the available apps is for my purpose the best option. From my first understanding, ReportLab might not be the best solution and I might better generate the ticket from a HTML page. Before I now dig deeper in documentations I wanted to ask you guys if you have some experience with my objective and can give me some recommendations? -
Send file to Django througth Ajax - CSRF missing
I was working with data just POSTing or GETting through AJAX until a file wanted to cause some problems :P AJAX dosnt work if I have processData and contentType set to true. But if I set processData and contentType set to false, I got an CSRF TOKEN MISSING error. How can I send the code with 'csrfmiddlewaretoken' and be able to manage the file too. this is my jQuery code: . . . more code . . . var factura = $('.inputFacturaPedido').prop('files')[0]; // Crea un objeto datos datos = { 'codigo': codigo, 'usuario': usuario, 'estado': estado, 'factura': factura, 'anulado': anulado, } // Envia los datos e los inputs al servidor $.ajax({ type: 'POST', url: url, data: {'datos': datos, 'csrfmiddlewaretoken': '{{ csrf_token }}'}, processData: false, contentType: false, success: function(contenido){ //things done if success } }); . . . more code . . . in my views.py I'm trying to receive my data in this way: if req.POST: normal_data = req.POST.get('datos[key]', '') file_data = req.FILES.get('datos[factura]', '') The code is not complete. Because everything Works without the "tweaks" for the file. I mean csrf problema mentioned before -
python spyne how to get request and path parameter in service method
I have implemented a sypne soap service with wrapping of application in DjangoApplication. In the service method, I want to get the request path or the named path parameters to view. It is not clear from the documentation or example, how can I do it. Here is my service and urls: class Inquiry(DjangoService): @rpc(Integer, _returns=Integer) def inqMulti(ctx, inqMultiRequest, *args, **kwargs): return 3 app = Application( [Inquiry], 'some-urn', name='SoapInquiry', in_protocol=Soap11(validator='lxml', polymorphic=True), out_protocol=Soap11(polymorphic=True), ) urlpatterns = [ url(r'^(?P<cliendId>\d+)/(?P<vendorId>\d+)/Inquire', DjangoView.as_view( services=[TSYSXMLMessagingInquiry], tns='urn://tsys.com/xmlmessaging/CC', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11(), cache_wsdl=False) ), url(r'^api/', DjangoView.as_view(application=app)), ] So essentially I want that clientId and vendorId to be available in the inqMulti method. -
simple example about django CRUD
I'm working on a Django REST API project for a restaurant. I have to get client requests and for some requests send model objects and for the update or delete requests send a feedback to the client. Suppose that my models.py is like: # models.py --------------------------------------------------------------------------- class Table(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30, null=False, blank=False) is_free = models.BooleanField(default=True) def __str__(self): return '%s %s %s' % (self.id, self.name, self.is_free) class Order(models.Model): order_id = models.AutoField(primary_key=True) table_id = models.ForeignKey(Table, on_delete=models.CASCADE) total_price = models.IntegerField() def __str__(self): return '%s %s' % (self.order_id, self.total_price) I want to send a list of all orders for client GET request, send feedback for the update and delete requests, and send True or False whether if a specific table with an id that sent from the client is free or not. unfortunately, I'm confused after reading so many documents. Would you please give a simple example to achieve these purposes? After that can you give me an example of how to serialize a none model object for clients uses? Thanks in advance. -
Django-Angular apache deployment
After deploying django and angular index.html, it returns blank white page and in console error is as follows: Loading failed for the <script> with source “http:localhost/inline.xxxxxxxxxxxx.bundle.js”. How to make it works? -
Facebook image link now going to default image
I was using the link structure https://graph.facebook.com/{id}/picture?type=normal in order to get the profile images of the users who sign up to my application. Till a few days ago it worked fine and I was able to get current profile image of the user but now the same link is returning the default profile image that Facebook uses. I am uncertain if I am not supposed to save this link or some change on Facebook end in causing this issue for me. Any help will be greatly appreciated. -
Issues with django cms Apphook in front end admin log in
Issues with django cms Apphook in front end admin log in so unable to link my application in my project and database is created properly please help how to create custom dashboard for django cms -
html to pdf convertion css not working
I try to convert the following page to pdf link using xhtml2pdf library for python. But the problem is the css styles are not working properly. How can i solve the problem ? -
Django save session in unittest
I am trying to get some data from session and to test it. I've gone through the docs but I keep getting None. So this is my view I want to test: class EmailLogin(LoadCartMixin, APIView): def post(self, request, format=None): session_cart = self.request.session.get('cart') And this is my test method: def test_void(self): cart = { u'meals': {self.meal.id: [{u'options': [self.meal_option.id], u'submeals': {}, u'quantity': 1}]} } session = self.client.session session['cart'] = cart session.save() response = self.client.post( reverse('accounts:email-login-url'), data={'email': self.restaurant_admin_email, 'password': self.restaurant_admin_password} ) As I say using self.request.session.get('cart') returns None although I am able to grab data correctly when running server and testing "by hand". I'm using Django 1.9, django rest framework in version 3.7.3 and Python 2.7. -
Django 2 login with email address, phone number or username
What is the best way to implement django 2 login and registration like instagram.com. user can register with username and email or phone and password. after register user can login with email address, phone number or username. Thanks -
Use value of related field when saving/POST django-rest-framework
Im trying to find a method for posting a string value and saving it to a foreign key field instead of using the pk. My models: class CustomUser(models.Model): username = models.CharField(max_length=500, unique=True) def __str__(self): return self.username class Order(models.Model): ordernumber = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False) user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, blank=True) amount = models.FloatField(null=True, blank=True) def __str__(self): return "{0}".format(self.ordernumber) And my serializer: class OrderSerializer(serializers.ModelSerializer): username = serializers.CharField(source='user.username') class Meta: model = Order fields = ('id','username', 'ordernumber', 'amount') read_only_fields = ('id') When using GET, everything works perfectly, but I can't seem to fix the POST method. I tried to override the create method like this: def create(self, validated_data): username = validated_data.pop('username') order = Order.objects.create(**validated_data) order.user = CustomUser.objects.get(username=username) order.save() return order But I get a KeyError on the username = validated_data.pop('username') line: Exception Value:'username' -
what is regular files in linux, how to select all regular file excluding the binary files in python
I would like to select all regular file and dictionaries excluding the symbolic links (on Unix) and special devices that are not regular files using python django. I tried with the python os.walk('/path'), but which will select all directories and files The code I used to fetch is for root, directories, filenames in os.walk(root_context): for directory in directories: if not directory.startswith('.'): parent_obj, flag = FileTree.objects.get_or_create(parent=parent_object, name=directory, node_root=os.path.join(root, directory)) # print('xxxxxxxxxx', os.path.join(root, directory)) for filename in filenames: if not filename.startswith('.'): file_object = RepositoryFiles.objects.create(parent=parent_object, name=filename) file = File(open(os.path.join(root, filename), 'rb')) file_object.file.save(filename, file, save=True) -
GraphQL queries in Django returning None
Hi guys, so i'm trying to use graphQL queries in django. Basically i have two apps, my 'api' app which contains everything i need to make the queries and another one called 'frontend' from which i call the api to use these queries. I can use the GraphQL view to type queries in it and it works perfectly, but whenever i try to make the query, i get this : "OrderedDict([('users', None)])" Result of my query in the GraphQl view And for the code : In 'api' my schema.py : import graphene import graphql_jwt from graphene import relay, ObjectType, AbstractType, List, String, Field,InputObjectType from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from datetime import date, datetime from django.contrib.auth.models import User from django.contrib.auth import get_user_model .... class Query(graphene.ObjectType): me = graphene.Field(UserType) users = graphene.List(UserType) profile = relay.Node.Field(ProfileNode) all_profiles = DjangoFilterConnectionField(ProfileNode) def resolve_users(self, info): ### Returns all users ### user = info.context.user if user.is_anonymous: raise Exception('Not logged!') if not user.is_superuser: raise Exception('premission denied') return User.objects.all() def resolve_me(self, info): ### Returns logged user ### user = info.context.user if user.is_anonymous: raise Exception('Not logged!') return user def resolve_all_profiles(self, info, **kwargs): ### Returns all profiles ### return Profile.objects.all() ..... def execute(my_query): schema = graphene.Schema(query=Query) return schema.execute(my_query) … -
Django: Confused about backwards relations in views
I have object CarMaker: class CarMaker(models.Model): name = models.CharField(max_length=100) And object CarModel stored in variable car_inst: class CarModel(models.Model): maker = models.ForeignKey(CarMaker, on_delete=models.CASCADE) name = models.CharField(max_length=50, null=False, blank=False) serial_number = models.CharField(max_length=50) car_inst = CarModel.objects.get(id=foo) I need to get the CarMaker that "owns" it. I tried with: maker = CarMaker.objects.get(id__in=car_inst.id) This doesn't work. I've seen examples online of using backwards relations along the lines of: maker = carmaker.carmodel_set.all() But that didn't work either. What am I doing wrong here? -
Subdirectory or Subdomain for Django apps within same project?
Yes, it does depends on use cases. My use case is, I have a generic project of which there are 6 apps, all apps share same google auth session. These apps will be scaling up in few months. I went through many posts to understand which one is preferred and how Django deals with it. Django provides Django Subdomain which requires configuring sites framework. Also there are posts suggesting same for subdirectories. I am running Django > Gunicorn + Supervisor > Nginx. Few posts I followed which directed everything through Nginx. Two of these posts are: one and two. There is so much disorientation in understanding what suits best for scaling of use case and which configuration needs to be followed ? Should we follow subdomains or subdirectory ? Where to set configuration in urls.py , settings.py or NGINX for all the routing and static files ? I understand that this is a big concept and won't fit in single answer. It would be helpful if there's any resource link I can go through. Thank you for your efforts. -
how to store commaseperated values in one column ,if user selected morethan one choice from form
I have "user" Model username email phonenumber I want to access all "user" model emails in other model "B" and make user to select more than one email and store it has commaseperatedvalues "B" colums are organization Designation share_knowledge_with (here all emails which user selected to be stored with commaseperated) I tried like this but not working: MODEL class B(models.Model): organization=models.CharField(max_length=200,blank=False,null=True) emails_for_help = models.TextField(null=True,help_text="select with whom you want to share knowledge") form class Bform(ModelForm): emails_for_help=forms.ModelMultipleChoiceField(queryset=User.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model=B fields=["organization","emails_for_help"] I tried like this but it is taking null value in "emails_for_help" -
Web based application and Office-Integration
I developed a simple issue tracking tool with web based application with django. Users can upload files to a ticket. Editing office files (MS-Word, MS-Excel) has this workflow: User A uploads foo.xlsx User B downloads foo.xlsx User B edits foo.xlsx User B uploads foo.xlsx again. The download/edit/upload workflow is too time consuming. It would be nice if this could be improved. Server: Linux, Clients: MS-Windows. -
How to render various filefield data in html?
I have a django model that looks like the following: class BlogFiles(models.Model): post = models.ForeignKey('Post') file = models.FileField(upload_to = 'blog_files',null=True,blank=True) This file can be a text file or image file or a video file. But how do i know which type it is without actually looking at each of their extensions? Because they are so many. Suppose if i have an image in the file attribute, then i can show it in the html like < img > tag. But if that file is a video.It won't work. How to solve this? -
Update Django Object
I've an object:- a = Model.objects.get(id=1) and a dictionary of data attributes of object a. update_data = { colA: 1, colB: 2, colC: 3, } Now, I want to update object a. How can I do it? Note:- .update() works on queryset, not on the object. Also, I cannot do a.colA=1 because in that case, I've use setattr on each key. Is there any way that I can update the object directly?