Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModelChoiceField Concatenate two fields in one field - Django
Hi i dont know the way to transform two fields model into one 'custom' to propose a unique field (pass ('fieldA','fieldB') to ('fieldA fieldB'). I am trying to build an inner model function but without excepted result... models.py class Referencebank(models.Model): idtable1 = models.AutoField(db_column='idtable1', primary_key=True) genus = models.CharField(max_length=45, blank=True, null=True) species = models.CharField(max_length=45, blank=True, null=True) subspecies = models.CharField(max_length=45, blank=True, null=True) def getScientifName(self): return str(self.genus) + " " + str(self.species); class Meta: managed = False db_table = 'table1' forms.py class ScientifNameForm(forms.Form): for ref in Referencebank.objects.all(): queryset = ref.getScientifName(); print("\n queryset") scientifName = forms.ModelChoiceField(queryset=Referencebank.objects.values_list('genus','species').order_by('genus').distinct(), empty_label="(Nothing)", required=False, help_text="Select the bacteria",label='Scientific Name') In forms.py, the for loop execute correctly the result that i want display in modelchoicefield I want something like that scientifName = forms.ModelChoiceField(queryset=Referencebank.objects.values_list('scientificName').order_by('scientificN').distinct(), empty_label="(Nothing)", required=False, help_text="Select the bacteria",label='Scientific Name') -
In Django. How to sort using field length
How to sort using field length results like this: Model.objects.all().order_by(len("field")) sql: select * from table order by len(field) -
How can I style django.contrib.auth.views.login? Django
I use login form, django provides. I want to give a placeholder to each forms. (username, password) What should I do for style this login form? urls.py : from django.contrib.auth.views import login, logout urlpatterns = [ url(r'^$', IndexView.as_view(), name='index'), url(r'^accounts/login/$', login, name='login'), ] registration/login.html : <form method="post" action=""> {% csrf_token %} <div> {{ form.username }} </div> <div> {{ form.password }} </div> <button class="btn btn-default" type="submit" value="Log in">Login</button> <button class="btn btn-default"> <a href="{% url 'signup' %}"><span>Sign Up</span></a> </button> </form> -
How to read a large .XLS file in chunks without loading it into RAM at once
I try to parse different kinds of very large Excel Files (.csv, .xlsx, .xls) Working (.csv/.xlsx) flows .csv is chunkable by using pandas.read_csv(file, chunksize=chunksize) .xlsx is chunkable by unzipping it and parsing inner .xml files using lxml.etree.iterparse(zip_file.open('xl/worksheets/sheet1.xml')) and lxml.etree.iterparse(zip_file.open('xl/sharedStrings.xml')), performing additional operations afterwards. Not working (.xls) flow .xls I can't find any info on how to split this file in chunks! Details: My file has a type of Django's TemporaryUploadedFile. I get it from request.data['file'] on PUT request. I get a path of the file like request.data['file'].temporary_file_path(). This is '/tmp/tmpu73gux4m.upload'. (I'm not sure what the *****.upload file is. I guess it's some kind of HTTP file encoding) When I try to read it: file.open() content = file.read() the content looks like bytes string b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1\x00\x00\x00\x00\x00\x00\x00\x00...etc. Question Are there any means of encoding and parsing this bytes string? Ideally, I would want to read .xls row by row without loading the whole file into RAM at once. Are there any means of doing it? -
Trying to access database from my local server
I want to access a database from Zoho Creator using their REST API (https://www.zoho.com/creator/help/api/rest-api/rest-api-add-records.html) I read that I cannot do that from the client side (because CORS isnt implemented or something along those lines) and that I would have to do it from a server. So I setup a local server using django and I ran a script from the terminal that should add a record to my zoho database, but it doesnt work... I'm not sure if the script is wrong or if the way I use the server is wrong. The server is ran by django, I made a simple server with the command "django-admin startproject mysite" and ran the server with "python manage.py runserver". The name of the app is "synonyms-database", the form is "Main_Form" and the only field there is is called "name". So with that info I followed the API instructions and this is my script: import requests payload = {'authtoken': myAPIToken, 'scope': 'creatorapi', 'name': 'test'} response = requests.request('POST', 'https://creator.zoho.com/api/erik341/json/synonyms- database/form/Main_Form/record/add/', json=payload) print(response.headers) print(response.text) print(response.url) And I get this response: <body> <div> An error has occurred. It has been reported to Zoho Creator support. We will look into this issue .<br> Sorry for the inconvenience … -
Downloading simple text file in Django
I'm trying to serve a simple text file with Django without success so far. I think that my Django code is OK: def status(request): # Get data from database parameters = get_parameters_from_database() if request.method == "GET": // Stuff here to render the view for a GET request return render_to_response('myapp/status.html', {'page_name': 'status', 'parameters' : parameters}) elif request.method == "POST": if request.POST['request_name'] == 'download_txt': file_path = parameters['file_path'] with open(file_path, 'rb') as fsock: response = HttpResponse() response['content_type'] = 'text/plain' response['Content-Disposition'] = 'attachment; filename=current.txt' response.write(fsock.read()) print(response) return response When the POST request is received, it get the following printed in webserver console, so I think it's ok: <HttpResponse status_code=200, "text/html; charset=utf-8"> So I think the problema is that I am not handling the success event in Jquery's Ajax method: $('#downloadButton').click(function(){ $.ajax({ url: '', method: 'POST', data: { request_name: 'download_txt' }, success: function (data) { //TODO }, error: function (err) { console.log('Error downloading file'); } }); }); The problem is that I have no idea of how I should handle the success event: I thought that the browser would automatically download the file once the server answered with that content_type Any help? -
The DECIMAL type field fetch data become string
In my table: my discount Type is DECIMAL: my data in table: but why when I fetch data in API, there gets string? I use Django/Django-Rest-Framework as the backend. -
Best way to limit access model to owner or superuser
I need to limit access to model object only to user created it or superuser. For example: post = get_object_or_404(Post, slug=kwargs['slug']) if post.created_by == request.user or request.user.is_superuser: return render(request, "post.html", {"post": post}) Is there better practice\shortcut for this ? Thank you -
Get field value from Django self.parent_model in a Stacked Inline
I have a Model admin with a field gallery to be chosen from dropdown. I need the selected value of gallery in my Stacked inline to get other fields in the Inline Model. I can access the parent model using self.parent_model but when I do self.parent_model.gallery I get . I want the exact chosen value. -
preparing a large file for downloading in Django
I use Django Rest Framework to serialize the data from my database, convert it to json and let user download it as a text file. The problem is that it takes quite a bit of time for preparing the file, so the server timeout sometimes happens. I switched to Django Channels in order to avoid the timeout, but now I do it in a rather ugly way: I send a signal to Channels, the serializer prepares the data, dumps it to a directory, and then sends back an url to download this temporary file. Everything works, but I have a bunch of temporary files, which I now need to clean regularly (with a cronjob). Is there more 'right' way of preparing large file in background and pass it to a view for downloading without necessary storing it on disk? -
django many-to-many unique set
With a many to many relationship in django, how can I add some constraint such that one side of the many to many must be a unique set? For example, with models like the following: class Topping(models.Model): # ... class Pizza(models.Model): # ... toppings = models.ManyToManyField(Topping) I want to make sure that a pizza has a unique set of toppings. The constraint will not apply the other way around. For example -- I could have olives on pizza1 pizza2 pizza3, and garlic on pizza1 pizza2 and pizza3. However, pizza1 pizza2 and pizza3 should not be the exact same pizzas. -
Limit the foreign key options in Django Admin select, having multiple Model related objects
I have the models: class A(MetaData): type = models.SmallIntegerField(choices=TYPE_CHOICES, default=0) class B(models.Model): # foreign key a = models.OneToOneField(A, related_name='b', on_delete=models.CASCADE) class C(models.Model): # foreign key a = models.OneToOneField(A, related_name='c', on_delete=models.CASCADE) TYPE_CHOICES 0 -> b 1 -> c In Django Admin, when I create C or B, for FK to A I have a select box; I want to limit the FK to A in the select box. for B creation, show only FKs where A type attribute is 0, and is not associated with any other B instance for C creation, show only FKs where A type attribute is 1, and is not associated with any other C instance. I have found that using def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "a": kwargs["queryset"] = B.objects.filter... return super().formfield_for_foreignkey(db_field, request, **kwargs) should help me, but I' m trying to get the optimal queryset for FK. Is not necessary to use the above method, if you have a better solution. -
Django settings.py error in adding a database
I am trying to add a database on "https://17x.xxx.xxx.xxx/phpmyadmin/" as my database for my django project. I have given correct database name, username and password. But I get this error. My configuration in the setting.py is DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'database_1', 'HOST': '17x.xxx.xxx.xxx', 'USER': 'xxxxx', 'PASSWORD': 'xxxxxx', } } The error that I get is, django.db.utils.OperationalError: (1130, "Host '1xx.xxx.xxx.xxx' is not allowed to connect to this MariaDB server") I haven't done this before. The database server is not mine. Is there something wrong in the way I've proceeded? -
Accessing registered Django MIDDLEWARE object
I have defined a middleware class XYZMiddleware and have registered it in settings.MIDDLEWARE. XYZMiddleware objects have relevant state, so in my integration test I need to access the XYZMiddleware object that Django (as of 1.11) has created. How do I retrieve it? (The docs do not appear to talk about it, neither topic docs nor ref docs.) -
Git- reference broken error
while i was deploying my django site on heroku.com it was perfectly going fine but when i type git push heroku master I get a error which looks like : error: update_ref failed for ref 'refs/remotes/heroku/master': cannot lock ref ' refs/remotes/heroku/master':unable to resolve reference 'refs/remotes/heroku/master':reference broken I also googled this error and i also put the code: $ git gc --prune=now $ git remote prune origin But still same error and yes i had put the project folder to sync through google drive and it creates .temp.folder or something and i also stoped syncing the folder but still i get the same error! please help me troubleshoot this! Thanks, -
Class & View for displaying Max & Avg values for each day in Django
I am extremely new to python (and django) and I've searched but honestly I'm not sure if I'm searching for the right stuff so decided to ask for some help. Here is my class. I have a script setup to enter and save these values every 5 minutes into the db. class Entry(models.Model): class Meta: ordering = ['time'] time = models.DateTimeField(default=timezone.now) inside = models.FloatField() outside = models.FloatField() gavg = models.IntegerField() ghigh = models.IntegerField() I am wanting to setup a class/view to display the date obviously, the average(and high) for 'inside' & 'outside' for that day. The average of gavg for that day. The high for 'ghigh' that day. And this would need to be done for every single day from the Entry class. I've tried to understand what I need to do in ORM but had issues with timezone aware datetime. I'm guessing I need another class, and I've seen some functions out there that might do what I need but I am having a difficulty time visualizing how the class should be defined and how/where the average/high functions should go. Or would this be better suited as an SQL query? -
Django - DeepCopy reference of parent class while copying child class
I have two classes namely:- class Person(models.Model): ... class Customer(Person): ... I have one more class Transaction which has a reference of Person class as class Transaction(models.Model): object = models.ForeignKey( Person, related_name='transactions', on_delete=models.DO_NOTHING, ) Now, I want to copy the instance of person and at the same time want to copy its reverse relationship in Transaction. I have tried deepcopy but no success as Customer model and Transaction Model are not directly related... -
Sync MySQL table with different table name
I have two Django application on 2 servers. (application "A" & application "B") I want to synchronize one table(table's name is "member") from A to B. Since I'm using Django and the actual table name is "a_member" and "b_member", I cannot use MySQL replication or pt-table-sync. (caused by different table name) What is the best way to synchronize(one-way) these two tables? using python script, django, mysql or other tools? Thanks! -
Printing static array result in webpage using django
I'm newbie to django.I want to print static array output in django web page.But when I'm executing the code It shows blank in my web page. So, help me to print my view.py results in web page This my views.py from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse("<h>Welcome</h>") def Compare(request): x=[98,8998,9,67,23] y=[67,37,9,330,123,67,56,123] x1=[2103,23,203,12,23,12] y1=[213,23,23,12,22,12,21,21] for i in x: if i in y: c=[ii for ii,val in enumerate(y) if val==i] #print c occurance1 = i,"Occur(s)",len(c),"times" #Total number of matches for j in c: if x1[j]==y1[j]: match2=i,"Secondary level match" else: match1= i,"Primary level match" #return match1 else: unoccured= i,"not in list" ##No matches #return unoccured return render(request,'web/base.html') This my html {% load staticfiles %} My site {% block content %} {% for occurance in occurance1 %} {{ occurance }} {% endfor %} {% for a in unaccured %} {{a}} {% endfor %} {% endblock %} -
Django Formsets rendering fields manually
I am trying to render fields manually in django formset. <select class="form-control" id="{{ line_form.label.id_for_label }}" name="{{ line_form.label.name }}"> {% if form.label.value %} <option value="{{ form.label.value }}">{{ form.label.value }}</option> {% else %} <option value="" selected>-</option> {% endif %} {% for item in view.items %} <option value="{{item.id}}">{{item.name}}</option> {% endfor %} </select> The name of the above field is label but i want it to lines-0-label. When i add a new form in the formset the above field has the same name it should be lines-1-label, and should increase so on. i.e., lines-2-label, lines-3-label, lines-4-label, ...., lines-101-label -
django.db.utils.OperationalError: no such column: polls_bands.id
I have run makemigrations and migrate so I'm not sure what the issue is if anyone could help me that would be a massive Here is the error. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Ethan\Envs\OnNote\mysite\polls\views.py", line 117, in bandlist return render(request, 'bandlist.html', {"bands": query}) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\shortcuts.py", line 30, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\template\loader.py", line 68, in render_to_string return template.render(context, request) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\template\backends\django.py", line 66, in render return self.template.render(context) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\template\base.py", line 207, in render return self._render(context) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\template\base.py", line 199, in _render return self.nodelist.render(context) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\template\base.py", line 990, in render bit = node.render_annotated(context) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\template\base.py", line 957, in render_annotated return self.render(context) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\template\loader_tags.py", line 177, in render return compiled_parent._render(context) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\template\base.py", line 199, in _render return self.nodelist.render(context) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\template\base.py", line 990, in render bit = node.render_annotated(context) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\template\base.py", line 957, in render_annotated return self.render(context) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\template\loader_tags.py", line 72, in render result = block.nodelist.render(context) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\template\base.py", line 990, in render bit = node.render_annotated(context) File "C:\Users\Ethan\Envs\OnNote\lib\site-packages\django\template\base.py", … -
HTTP 400 message bad request on POST - views and serializers code not designed correctly
I keep getting the following error: POST http://127.0.0.1:8000/api/creator_signup/ 400 (Bad Request) Whenever I attempt to POST data from my AngularJS application to my Django backend. On the client side, I have: function registerCreator(creatorData) { var url = envService.read('apiUrl') + "/creator_signup/"; var dataJSON = { first_name: creatorData.firstName, last_name: creatorData.lastName, email: creatorData.email, youtube_channel_username: creatorData.username, youtube_channel_url: creatorData.url, youtube_channel_title: creatorData.title, youtube_channel_description: creatorData.description, photo: creatorData.photo, youtube_channel_start_date: creatorData.startDate, keywords: creatorData.keywords, no_of_subscribers: creatorData.noOfSubscribers, no_of_videos: creatorData.noOfVideos, no_of_views: creatorData.noOfViews, no_of_likes: creatorData.noOfLikes, no_of_dislikes: creatorData.noOfDislikes, location: creatorData.location, avg_views: creatorData.avgViews, gender: 0, password: creatorData.password }; var req = { method: 'POST', url: url, headers: { 'content-type': 'application/x-www-form-urlencoded', }, data: dataJSON }; $log.info(req); return ($http(req).then(handleSuccess, handleError)); } function handleSuccess(response) { return response.data; } function handleError(response) { if (!angular.isObject(response.data) || !response.data.message) { return($q.reject('An unknown error occurred.')); } return($q.reject(response.data.message)); } On the server side, I have: urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^creator/$', views.CreatorList.as_view(), name="creator_list"), url(r'^creator/(?P<pk>[^/]+)/', views.CreatorDetail.as_view(), name="creator_detail"), url(r'^creator_signup/$', views.CreatorSignup.as_view(), name="creator_signup"), ] urlpatterns = format_suffix_patterns(urlpatterns) models.py class Creator(models.Model): """ Creator model """ id = models.UUIDField(primary_key=True, default=uuid4, editable=False) first_name = models.CharField(max_length=255, null=True, default=None) last_name = models.CharField(max_length=255, null=True, default=None) email = models.CharField(max_length=255, null=True, default=None) youtube_channel_username = models.CharField(max_length=255, null=True, default=None) youtube_channel_url = models.CharField(max_length=255, null=True, default=None) youtube_channel_title = models.CharField(max_length=255, null=True, default=None) youtube_channel_description = models.CharField(max_length=255, null=True, default=None) photo = models.CharField(max_length=255, … -
Django User Permissions
I have a django app in which only superuser or staff members can create an object. Here's how I did it, model, class Data(models.Model): content = models.TextField() view, def data_create(request): if not request.user.is_staff or not request.user.is_superuser: raise Http404 else: # Create the Data object . . . After doing so I created 2 users, first one is superuser (admin) & second one is a normal user (test). After that, I logged in as superuser (admin) into django admin panel & changed second user's (test) permission to staff & also gave him permission to create the data object. But Problem is that it's still returning Http404 error whenever I try to create data object as (test) second user. Why is it happening? Also: When I changed second user's (test) permission to superuser instead of staff, everything worked fine it was able to create data object (no longer 404 error). But I wants to keep it staff & be able to create the data. -
Recaptcha doesn't show up in django-crispy-forms form
I am trying to implement recaptcha in my django-crispy-forms form using this repo, however whenever I put it in my forms layout it doesn't show. Is there something I'm missing? class ServerBumpFormView(LoginRequiredMixin, UpdateView): model = Server template_name = "servers/server_bump_form.html" success_url = reverse_lazy("servers:manage") fields = () def get_queryset(self): if not self.request.user.is_superuser: return self.model.objects.filter(owner=self.request.user) return self.model.objects.all() def get_form(self, form_class=None): form = super().get_form(form_class) form.helper = FormHelper() captcha = ReCaptchaField(widget=ReCaptchaWidget()) form.helper.layout = Layout( 'captcha', ) form.helper.add_input(Submit('submit', 'Bump', css_class='btn-blurple')) if form.is_valid(): obj = form.save(commit=False) obj.bumpPoints = obj.bumpPoints + 1 obj.last_bumped_at = datetime.datetime.now().replace(microsecond=0, tzinfo=pytz.UTC) obj.save() return form It also produces a KeyError KeyError: "Key 'captcha' not found in 'ServerForm'. Choices are: ." -
call method in python file from angularjs, going through parameter specific data
regards I have a project of angularjs + Django, and I have a method in a python file since I need some methods that use the linux console, but some values are passed to it by parameters. That method is called from angularjs, as I can with angualrjs call that method, passing a specific datum that I want. Thank you