Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : How to migrate local saved objects to heroku server
I am trying to deploy Django webapp to heroku server. I followed steps like adding to staging, committing and pushing. This showed error Programming error relation doesn't exist. For which I ran heroku run bash ./manage.py makemigration ./manage.py migrate Now this created tables but I have 10 objects saved in say model Article which I also want in heroku served database. But it is not showing there, which is obvious as the tables are created only after my bash commands. I wanted to ask whether it is possible to get same database in heroku server as my local development server ? Otherwise I have to re-create all the articles which I have been creating locally. P.S : I forgot to tell you that I already added migrations folder in git and commit it too. Still no luck. Is it even possible ? -
How to optionally pass an parameter to django logging?
In my django logging settings under formatter - I have a var: %(new_line_number)s I have a logging function in my views that calls logger.debug at the end, and so in this case I want to pass newlinenumber. logger.debug('context for %s: %s', product, tool, extra={'newlinenumber':newlinenumber} ) I do NOT want to have to pass in extra={'newlinenumber':None} everytime I call the logger. As that looks very messy and is redundant. How can I accomplish this? Currently if I do not include extra={'newlinenumber':None} The logger errors out anytime it has been called without newlinenumber. The only time I am trying to pass in a newlinenumber is when I call it from my logging function. -
'Form' object has no attribute '__name__'
'OrderProductForm' object has no attribute 'name' I'm a little confused as to why I'm receiving this error. I've spent quite a bit of time today trying to diagnose why my code isn't working. I was trying to have the form drop down selections be queried based on a pk, but I seemed to mess everything up from doing so. I'm looking for some advice on a better way to do so, because the current method is not doing it for me. forms.py class OrderProductForm(ModelForm): def __init__(self, pk=None): room = forms.ModelChoiceField( queryset = Room.objects.filter(order_id__exact=pk) ) class Meta: model = OrderProduct exclude = ('ID',) The view using this form for reference: views.py def create_orderproduct_view(request, pk=None): order_list = [] order_number = get_object_or_404(Order, pk=pk) OrderProductFormSet = formset_factory(OrderProductForm(pk=pk)) if request.method == 'POST': ## using formsets formset = OrderProductFormSet(request.POST) for form in formset: if form.is_valid() and 'Product_ID' in form.cleaned_data: form.save() else: return HttpResponseRedirect(reverse('orderproduct', kwargs= {'pk':pk})) else: order_list = [] for x in range(50): order_list.append({'Order_ID':order_number}) formset = OrderProductFormSet(initial=order_list) return render(request, 'create_orderproduct.html', {'formset': formset}) Thank you in advance! -
Avoid duplicated logging - Django
currently, I am working a website using django and I would like to avoid double logging using the same account. My libraries are: pyasn1==0.2.3 pyasn1-modules==0.0.8 pycparser==2.17 pycups==1.9.73 pycurl==7.43.0 pygobject==3.20.0 pyparsing==2.1.10 python-apt==1.1.0b1 python-dateutil==2.6.0 python-debian==0.1.27 python-systemd==231 pytz==2016.10 pyxdg==0.25 PyYAML==3.12 reportlab==3.3.0 requests==2.9.1 rsa==3.4.2 scikit-learn==0.18.1 scipy==0.18.1 sessioninstaller==0.0.0 simplegeneric==0.8.1 six==1.10.0 SoundFile==0.9.0.post1 stevedore==1.21.0 system-service==0.3 TextGrid==1.0 ubuntu-drivers-common==0.0.0 ufw==0.35 unattended-upgrades==0.1 uritemplate==3.0.0 urllib3==1.13.1 usb-creator==0.3.0 virtualenv==15.1.0 virtualenv-clone==0.2.6 virtualenvwrapper==4.7.2 xdiagnose==3.8.4.1 xkit==0.0.0 I hope that you can help me. -
Django ListView self.kwargs
I'm using Django==1.11. As I understand from class based views, in this case ListView, you can access url params in get_queryset with self.kwargs, as answered here and here. And I have no problem when I use get_context_data and self.kwargs. But I can't get it to work in get_queryset. ¿What I'm doing wrong or missing? I've been trying so many alternatives but I can't get the right one. My code: urls urlpatterns = [ url(r'^escuelas/(?P<level>(inicial|primario|secundario))/$', SchoolListView.as_view(), name='school-by-level-index'), #... view class SchoolListView(ListView): model = School template_name = 'edu/adminlte/school_index.html' def get_queryset(self): queryset = super(SchoolListView, self).get_queryset() """ Here below self.kwargs['level'] does not return anything as I would expect """ level = self.kwargs['level'] if level is 'inicial': queryset = School.objects.filter(level='I') return queryset return queryset Thanks. -
initial = {'key': 'value'}. Handling forms with Class Based Views
I read the Class Based View page in the Django documentation site and I stumbled with this code example: from django.http import HttpResponseRedirect from django.shortcuts import render from django.views import View from .forms import MyForm class MyFormView(View): form_class = MyForm initial = {'key': 'value'} template_name = 'form_template.html' def get(self, request, *args, **kwargs): form = self.form_class(initial=self.initial) return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): # <process form cleaned data> return HttpResponseRedirect('/success/') return render(request, self.template_name, {'form': form}) My question is why I should create the initial = {'key': 'value'} dictionary. -
Logging/Printing in Django-TastyPie
I cannot get my print statements to produce any output in my console when I hit a resource. The below code runs the print statements on app load, but I cannot get anything other than the HTTP request information to populate in my console when the resource is invoked. I know it works because my database receives the record, but I need to see what's happening. class TreeResource(ModelResource): class Meta: queryset = Tree.objects.all() resource_name = 'tree' list_allowed_methods = ['post'] authorization = Authorization() filtering = { 'id': 'exact', 'user_id': 'exact', 'match_id': 'exact', 'currency': 'exact', 'when': ALL, 'amount': ALL, 'success': ALL } def dehydrate(self, bundle): print('First DEHYDRATE pass') return bundle # Make sure tree has enough tree to cover tree def dehydrate_success(self, bundle): print('Lets see if we can dehydrate') c = CheckSum() passes_check_sum = c.verify_tree(bundle.data) if passes_check_sum: return 1 -
Pulling data from Sheets API via Python and Django issue
I'm trying to run python manage.py runserver on the local host (using virtualenv) but it kept giving me the message below and I kept hearing that it might be because of the Oauth2 Error? Performing system checks... usage: manage.py [--auth_host_name AUTH_HOST_NAME] [--noauth_local_webserver] [--auth_host_port [AUTH_HOST_PORT [AUTH_HOST_PORT ...]]] [--logging_level {DEBUG,INFO,WARNING,ERROR,CRITICAL}] manage.py: error: unrecognized arguments: runserver I'm adding my the Python code that I'm using (it's some what an example code from Google Sheets API V4) from __future__ import print_function from apiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools # Setup the Sheets API SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly' store = file.Storage('credentials.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service = build('sheets', 'v4', http=creds.authorize(Http())) def get_form_data(): SPREADSHEET_ID = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms' RANGE_NAME = 'Class Data!A2:E' result = service.spreadsheets().values().get(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME).execute() values = result.get('values', []) data = [] if not values: return data else: for row in values: data.append([]) for each in row: data[len(data)-1].append(each.encode("utf-8")) return data Has anyone ever run into this problem before and solve the issue? Any help is appreciated -
Django get file basename from uploaded file
In my form there is a file upload. fileandext = forms.FileField( ..... the user will upload a file barcode.txt . I want to get the barcode without the extension or dot. It seems no matter what type of os path file function i use a get an error of the format AttributeError: 'InMemoryUploadedFile' object has no attribute 'something here' So what is an InMemoryUploadedFile and how can I manipulate the filename to extract the basename? What I've tried, separate function, using os.path.splitext(fileandext) EDIT the value of fileandtext has no path it looks like "barcode.txt" -
Django[ TypeError: __init__() got an unexpected keyword argument 'choice' ] Happening when adding a choice in my model
I have a model that is a radar, and it needs to have 4 possible modes. I followed the documentation on the django website (https://docs.djangoproject.com/en/1.11/ref/models/fields/#choices). However I am still getting an error. I will post my model file down below. If you think I might need to post any other code let me know. from django.db import models # Create your models here. class Radar(models.Model): id = models.AutoField(primary_key=True) SCAN = "SC" ON = "ON" OFF = "OF" STANDBY = "ST" MODE_CHOICES = ( (SCAN, "scan"), (ON, "on"), (OFF, "off"), (STANDBY, "standby"), ) mode_choice = models.CharField( max_length=2, choice=MODE_CHOICES, default=OFF, ) ip_address = models.CharField(max_length=200) start_azimuth_angle = models.FloatField(default=0) end_azimuth_angle = models.FloatField(default=0) azimuth_scan_speed = models.FloatField(default=0) azimuth_increment = models.FloatField(default=0) start_elevation_angle = models.FloatField(default=0) end_elevation_angle = models.FloatField(default=0) elevation_scan_speed = models.FloatField(default=0) elevation_increment = models.FloatField(default=0) def __str__(self): string = 'RadarID : %s ip: %s ' % (self.id, self.ip_address) return string -
Django - nested relation query with the ORM
Because I need to avoid a recursive import and work with a Group object as my starting point for my query (which is why I can't import Action objects directly.) The relationship is Group -> Component -> ComponentVersion -> Action For instance, Group.components.all() returns all the components in a query set. Additionally [component.versions.all() for component in Group.components.all()] returns a list of Querysets whose results are all of the versions. Subsequently, .actions.all() would return all the Queryset of actions for each ComponentVersion returned in the comprehension. What is the optimal way to do this to avoid making unnecessary calls to the DB and for readability? -
Django Rest Framework nested relationship sets field 'read_only=True'
My AirportSerializer has a field city, that is a ForeignField nested by setting depth=1. I need the serializer to return the information of the 'Airport' and the information of the related 'City', so I need to nest the objects. The problem is that the field 'city' is set read_only=True when I set the depth to 1, so post method raises a 'not null' error because the field is required. I tried by setting city = CitySerializer(), and I get the nested result that I need, but this approach implies that a post method expects data for creating a new 'Airport' and a new 'City' also. This is not what I want. I only want the field 'city' not to be set read_only=True. The documentation says that I have to create create() and/or update() methods in order to explicitly specify how the child relationships should be saved I tried this, with this serializer: class AirportSerializer(serializers.ModelSerializer): class Meta: model = models.Airport fields = ('id', 'city', 'name', 'iata') depth = 1 def create(self, validated_data): airport = models.Airport.objects.create(**validated_data) return airport But validated_data gets de 'city' field already set to null, so airport = models.Airport.objects.create(**validated_data) raises the same not null error. So, in the end, … -
Django through Docker Error: That IP address can't be assigned to.
I am working on Ubuntu 16.04 VM and trying to run my Django app through Docker container. I successfully verified that my web is working. It runs if I just command on my machine. However, when I build image with my app and run the container, it does not work. my Dockerfile has this CMD at the end. CMD ["python", "manage.py", "runserver", "myVmip:8000]" It gives me an error Performing system checks... System check identified no issues (0 silenced). June 21, 2018 - 20:50:44 Django version 1.11.13, using settings 'datahttptools.settings' Starting development server at http://myVMip:8000/ Quit the server with CONTROL-C. Error: That IP address can't be assigned to. I was trying all the possible solutions by googling but I was not able to figure it out. -
autocomplete django form jquery
I m kinda new to django, anyway I want my form to have javascript autocomplete. Example that I m trying to do is https://www.w3schools.com/howto/howto_js_autocomplete.asp. So here my question is that should i go for all HTML and Javascript and then try to pass the user input manually by declaring this in my views.py def register(request): country = request.POST['mycountry'] or is there any Django way of handle this? -
Assigning a slug in template url with taggit's built in slugify does not seem to work. Tosses a slug field error
I'm using a 3rd party app called django taggit to handle my tagging needs. I am mainly using it to display a list of all my tags and maybe in the future I will create a tag cloud. I have a tags page on my site that displays a list of all the tags. I created a detail view for my tags. If someone clicks on a tag I want it to list all the articles with that corresponding tag. Now Taggit has it's own slugify built in which I can call using tag.slug. Models: class BlogPost(models.Model): ... test_cat = TaggableManager() ... def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', args=[str(self.id)]) Urls: urlpatterns = [ ... path('blogs/tags', views.TagListView.as_view(), name='tags'), path('tags/<slug>', views.TagDetailView.as_view(), name='tagged'), ... ] Tag list template: I have specified the slug in my {% url %} <ul class="tags"> {% for tag in tags %} <li><a href="{% url 'tagged' slug=tag.slug %}">{{tag}} ({{tag.num_times}})</a> </li> {% endfor %} </ul> Views: class TagListView(generic.ListView): model = BlogPost template_name = 'blog/all_tags.html' def get_context_data(self, **kwargs): context = super(TagListView, self).get_context_data(**kwargs) tags = BlogPost.test_cat.most_common() context['tags'] = tags return context class TagDetailView(generic.DetailView): model = BlogPost template_name = "blog/tag_detail.html" ... The error code is FieldError at /blog/tags/world-news Cannot resolve keyword … -
How to make internal requests to Nginx
My architecture is: Ubuntu + postgres + django + Nginx From a python application or system service, how can I make an internal request https to Nginx. And in case it can be done, how could you create a Nginx block that distinguishes between internal and external requests (internet). -
Processing Background Tasks on a Scheduled Basis While returning HTTP Requests
Here is what I am trying to accomplish: 1) GET Request is made 2) Background task is scheduled. Response that task has been scheduled is made. 3) After ten seconds (after the response has been made), the task is processed. I want to do this asynchronously so that the computer that made the call is not waiting on the response and can perform other tasks without wasting CPU. I am able to process the background tasks if I use the command python manage.py process_tasks but I want this to occur automatically on a routine basis in my Python code. How can I do this? -
Django form with grouped checkboxes
I need to create a form in Django which contains a list of grouped checkboxes like: group_one [] option_one [] option_two group_two [] option_one [] options_three Right now I've an intermediate table where I'm storing a option_id and a group_id. I found this snippet but only works on Django 1.8, after that version some classes were removed from the core of django forms... I could find the way to update the snippet, but I wonder if maybe somebody had the same situation and found a better solution for this challenge. Thank you in advance! -
Verbosity for Django management commands
Django lets you define --verbosity parameter for management commands with different verbosity levels: 0, 1, 2, 3. For what cases would anyone need more than 2 verbosity options for management commands? Wouldn't silent and verbose mode be enough? -
Sending forms clears the Get parameters
When I click on the link <a href="?page={{request.GET.page}}&order_by=counter__service__name_service&sort={{ sort_type }}&from_date={{request.GET.from_date}}&from_date={{request.GET.to_date}}&type_water={{request.GET.type_water}}"> all the parameters are saved as both forms and the rest, but when I try to also keep the parameters in the form action method <form class="row justify-content-around" id="searchform" action="{% url 'history_application' %}?page={{request.GET.page}}&order_by={{request.GET.order_by}}&sort={{request.GET.sort}}" method="get" accept-charset="utf-8"> it removes them (URL: history/?type_water=hot&from_date=&to_date=). Why parameters do not remain in the query? -
How do I update django to 2.x on digitalocean?
I have recently started using digitalocean, and I have this problem ever since! I have created a django project on django 2.0.3, and I want to launch this. But the standard django version on digitalocean is 1.8.7. Now there are posts on the internet which have helped me to upgrade django using pip3, but that does not update the django version of the standard project digitalocean allready has created. So my question is, how can I update the version of that project? -
How to replace line number in a python logging function
I have a method that I am calling at the end of all my django views for logging. logger = logging.getLogger(__name__) def context_logger(context, request): for key, val in context.items(): if key is not 'page_form' and key is not 'failure_form': logger.debug('%s - context for %s: %s', request.get_full_path(), key, val) logger.debug(sys._getframe().f_lineno) views def index(request): products, tools = menu() job_executions = jobs_in_progress() context = {"products": products, "tools": tools, "job_executions": job_executions} context_logger(context, request) # i am able to get the line number here logger.debug(sys._getframe().f_lineno) return render(request, "app/index.html", context) The problem is when context_logger gets called it always prints the line number of the context_logger method (rather than where it is being called from) in the log. I am able to grab the line # with (sys._getframe().f_lineno) but not sure how to replace this in the log. Is there a straight forward way to do this? -
git submodule update via ssh error
I cloned the application commcare-hq after installing python and django in my cpanel. here's the link: https://github.com/dimagi/commcare-hq but whenever i enter the following command git submodule update --init --recursive i get the following error fatal: clone of 'git://github.com/dimagi/xml2json.git' into submodule path '/home/hcdcnetl/myProject/commcare-hq/submodules/xml2json' failed Failed to clone 'submodules/xml2json'. Retry scheduled Cloning into '/home/hcdcnetl/myProject/commcare- hq/corehq/apps/hqmedia/static/hqmedia/MediaUploader'... fatal: unable to connect to github.com: github.com[0: 192.30.253.113]: errno=Connection refused github.com[1: 192.30.253.112]: errno=Connection refused -
Can I build Uber app App admin panel with django.?
I want to get User Location with django.. (Lat,Lng) and also I want get all users around it within 10 km I want to do stuff that I am already doing in android with this library compile 'com.firebase:geofire-android:2.3.1' Thank you. -
django multiple filter options on queryset
We have 2 approach ideas that we are trying to consider here for the Django REST api. At the moment, we have implemented 1 filter option: class APINewsViewSet(viewsets.ModelViewSet): serializer_class = APINewsSerialiser def get_queryset(self): queryset = NewsBackup.objects.all() source = self.request.query_params.get('source', None) if source is not None: queryset = queryset.filter(news_source = source) return queryset This achieves: 127.0.0.1/news?source=xxx Something additional that we would like to do is have other filter options that the user can type in such as 127.0.0.1/news?source=xxx&sourcename=xxx which would then return them the JSON object with only data that has a source_id of xx and source_name of xx. Is this possible with the Django REST framework? We have tried to add other options within the method: query_params.get()