Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
It is in the djangogirls tutorial in creating a blog
i am having problems with -r requirements in the creation of my first project which is creating a blog. " Could not find a version that satisfies the requirement Django~=2.0.6 (from -r requirements.txt (line 1)) (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.8.19, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3, 1.10.4, 1.10.5, 1.10.6, 1.10.7, 1.10.8, 1.11a1, 1.11b1, 1.11rc1, 1.11, 1.11.1, 1.11.2, 1.11.3, 1.11.4, 1.11.5, 1.11.6, 1.11.7, 1.11.8, 1.11.9, 1.11.10, 1.11.11, 1.11.12, 1.11.13, 1.11.14, 1.11.15, 1.11.16, 1.11.17, 1.11.18, 1.11.20) (line 1)) " No matching distribution found for … -
Problem adding a queryset to a field on a FilterSet
I have some filtersSets working fine, but now I tried to add a queryset to a field on the FilterSet and it fails when I load the page. I'm using Django 2.1.1 with Python 3.6 and Django-filter 2.0.0. view def search_jobs(request): job_list = Job.objects.filter(project__status="P", is_deleted="False") job_filter = JobsListFilter(request.GET, queryset=job_list) return render(request, 'webplatform/jobs_list_filter.html', {'filter': job_filter}) filter class JobsListFilter(django_filters.FilterSet): # LINE ADDED - the following line is the added queryset projects = Project.objects.filter(status="P", is_deleted="False") skills = WorkerSkills.objects.filter( id__in=Job.objects.values_list('required_skills__id', flat=True).distinct()) worker_job = django_filters.CharFilter(method='my_filter') required_skills = django_filters.ModelMultipleChoiceFilter(queryset=skills, widget=forms.SelectMultiple) # LINE ADDED - The following line is the one that adds the queryset inside the field I want to filter. project = django_filters.ChoiceFilter(queryset=projects) compensation_type = django_filters.ChoiceFilter(choices=Job.COMPENSATION_TYPE, widget=forms.RadioSelect) class Meta: model = Job fields = ['worker_job', 'required_skills', 'project', 'compensation_type'] def my_filter(self, queryset, worker_job, value): return queryset.filter( worker_job__icontains=value ) | queryset.filter( work_description__icontains=value ) The code is working without the added lines LINE ADDED on the FilterSet. But the thing is that on the field project it just let me select between all the projects created, and I want to have only the ones that are really necessary (applying the queriset on the code). But adding those lines in the code, when I use debug mode I can … -
Migrating from django 1.x to 2.x with django-modeltranslation
I'm currently upgrading my application to move from django 1.x to version 2.x Unfortunately it looks django-modeltranslation isn't compatible with version 2.x, and not even in development anymore. As all my translation rely on this module, I have to find an other solution. My questions are : Which equivalent solution could I use to translate the content from my Database? How should I proceed to migrate from django-modeltranslation to this module without having the manually doing it. Thank you for your help. -
How to speed up copy_expert in postgresql?
The following function imports around 60k records in 111 seconds. I've heard others say that copy_from and copy_expert are doing 1 million records in less than a minute. Is there something about using copy_expert that is slowing down process vs using copy_from? Anything I can do to optimize this? cursor = connection.cursor() cursor.copy_expert(''' COPY employee_employee (name, slug, title, base, overtime, other, gross, benefits, ual, total, year, status, jurisdiction_id, notes) FROM STDIN WITH (FORMAT csv, HEADER true, FORCE_NOT_NULL (status)); ''', open(csv_fname), ) As for relevant variables the database connection is from Django (from django.db import connection). The database is on my local Macbook Pro and is Postgresql 10. -
AttributeError - Oauth2 Application Creating - Django
I am tryig to create Oauth2 Application from function. AbstractApplication is a model for soting client_id client secret Here is ref - https://django-oauth-toolkit.readthedocs.io/en/latest/models.html#oauth2_provider.models.AbstractApplication. But it is giving me error - if value is not None and not isinstance(value, self.field.remote_field.model._meta.concrete_model): AttributeError: 'str' object has no attribute '_meta' from django.shortcuts import render from oauth2_provider.models import AbstractApplication from django.shortcuts import render, redirect import pdb def CreateApplicationIdSecret(request): # pdb.set_trace() # company_name = request.user.userprofile.user_company.company_name obj = AbstractApplication( user = request.user, client_type = 'public', authorization_grant_type = 'client-credentials', name = 'Added BY Func', ) obj.save() return redirect('dashboard') -
Django - Dev Server security?
Was starting to develop a django app and ran these commands (using windows and django version 2.1.7): >>django-admin startproject testing >>cd testing >>python manage.py startapp core >>python manage.py runserver Got the message: Django version 2.1.7, using settings 'testing.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. But when I access the root URL (127.0.0.1:8000) it gives: Method Not Allowed The method is not allowed for the requested URL. And when I try to access the admin (127.0.0.1:8000/admin/) page it shows: Not Found The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. No other changes were made to the base app code. What is happening? Recent django versions have some kind of security update? -
Using getattrs() to access Foregin Key values
I am using a basic form in Django to collect a users choices which will be used to create a filter of objects and then output to csv. I would like to use the values from the form to access data in the different models. My form looks like this.. class CustomReportForm(forms.Form): CHOICES=[('Asset Labels','Asset Labels'), ('Asset List','Asset List')] REPORT_FIELDS = [('id','ID'), ('name','Name'), ('location','Location'), ('status','Status'), ] type = forms.ChoiceField(choices=CHOICES) col_choices = forms.MultipleChoiceField(choices=REPORT_FIELDS, widget=forms.CheckboxSelectMultiple) location = forms.ModelChoiceField(AssetLocation.objects.all(), required=False) status = forms.ModelChoiceField(AssetStatus.objects.all(), required=False) I have 2 models included in the form 'AssetLocation' and 'AssetStatus'. class AssetLocation(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) company = models.ForeignKey(Company, on_delete=models.CASCADE) location = models.CharField(max_length=20) location_code = models.CharField(max_length=10, blank=True) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return str(self.company) + " - " + self.location class AssetStatus(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) company = models.ForeignKey(Company, on_delete=models.CASCADE) status = models.CharField(max_length=20) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return str(self.company) + " - " + self.status I also have an Asset model class Asset(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) company = models.ForeignKey(Company, on_delete=models.CASCADE) location = models.ForeignKey(AssetLocation, on_delete=models.CASCADE) status = models.ForeignKey(AssetStatus, on_delete=models.CASCADE) name = models.CharField(max_length=40) def __str__(self): return str(self.company) + " - " + self.name And I have a view which accesses … -
I can't get the user-id/pk working in my APIView
folks :-) I need to filter my data by the user. I have a foreignKey in my model. But I can't get the id/pk from the user sadly... If I enter a pk manually like author=1, It works pretty well. I just can't get the pk automatically. I would appreciate your help :-) class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): user = get_object_or_404(User, pk=self.kwargs.get('pk')) kosmisch = Char.objects.filter(gebiet='Kosmisch', author=user)[:5].aggregate(Sum('stärke'))['stärke__sum'] geschick = Char.objects.filter(typ='Geschick', author=user)[:5].aggregate(Sum('stärke'))['stärke__sum'] stadt = Char.objects.filter(gebiet='Stadt', author=user)[:5].aggregate(Sum('stärke'))['stärke__sum'] labels = ['Kosmisch', 'Geschick', 'Stadt'] default_items = [kosmisch, geschick, stadt] data = { "labels": labels, "default": default_items, } return Response(data) from django.urls import path from .views import ( ChartsViews, ChartData, ) from . import views urlpatterns = [ path('charts/<int:pk>', ChartsViews.as_view(), name='chart-view'), path('api/charts/data/', ChartData.as_view(), name='chart-data'), ] class Char(models.Model): name = models.CharField(max_length=100) gebiet = models.CharField(max_length=100) typ = models.CharField(max_length=100) stärke = models.IntegerField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.FileField(max_length=1000, blank=True, null=True, default="default.jpg") def __str__(self): return self.name -
The form editing the existing form does not save and redirects to wrong. Django
I'm trying to add an edit form to an existing model, but it does not save every time and redirects me to the home page instead of the 'account' page. What am I doing wrong? why changes in the existing model are not visible? any help will be appreciated. views.py def account(request, time_id=1): #my form time = get_object_or_404(Time, pk=52) # how to replace it correctly in the query set collections, what can I use? like this Time.objects.all()[:12] if request.method == "POST": form = TimeEditForm(request.POST, instance=time) if form.is_valid(): time = form.save(commit=False) time.save() return redirect('account') else: form = TimeEditForm(instance=time) forms.py class TimeEditForm(forms.ModelForm): class Meta: model = Time fields = ('compartment',) labels ={ 'free_or_no': 'field name in my language?' } models.py class Time(models.Model): day_time = models.ForeignKey(DayTime, on_delete=models.CASCADE) compartment = models.CharField(max_length=11) free_or_no = models.BooleanField(default=True) time_equivalent = models.IntegerField() urls.py urlpatterns = [ url(r'^$', views.masseur_detail, name='masseur_detail'), url(r'^account$', views.account, name='account') ] -
How to fix Django : didn't return an HttpResponse object. It returned None instead?
I have used python3.7 and django 2.1 and for django app models and views diretory have separated folder and files. Project Name : fusion App Name : admin_lte Getting bellow error ValueError at /csv/ The view django_adminlte.views.file_csv_view.file_csv_show.file_csv_show didn't return an HttpResponse object. It returned None instead. Traceback : Traceback (most recent call last): File "C:\Users\parth\Desktop\admin_lte\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\parth\Desktop\admin_lte\lib\site-packages\django\core\handlers\base.py", line 137, in _get_response "returned None instead." % (callback.__module__, view_name) ValueError: The view django_adminlte.views.file_csv_view.file_csv_show.file_csv_show didn't return an HttpResponse object. It returned None instead. [15/Feb/2019 17:23:57] "POST /csv/ HTTP/1.1" 500 67126 I already make all init.py file for separated folder. View file : file_csv_show.py from django.shortcuts import render,redirect from django_adminlte.forms import File_csvForm from django_adminlte.models import file_csv def file_csv_show(request): if request.method == 'POST': form = File_csvForm(request.POST,request.FILES) #request.POST = geting title/auth request.FILES = for book upload if form.is_valid(): try: form.save() return redirect("file_csv_show") except: pass else: form = File_csvForm() return render(request,'adminlte/file_csv_index.html',{'form' : form}) models file : file_csv.py from django.db import models # Create your models here. class File_csv(models.Model): title = models.CharField(max_length=50) csv_files = models.FileField(upload_to='files/csv') class Meta: db_table = "csv" def __str__(self): return self.title html file {% extends 'adminlte/base.html' %} {% load crispy_forms_tags %} {% block content %} {% if user.is_authenticated … -
MultiValueDictKeyError at /connect/
I'm trying to have all location functionality on one page: get users location, post it to the database, then filter results based on a user-inputted kilometre radius value. I am getting MultiValueDictKeyError at /connect/ 'latitude' because the POST request is going to location = Location(latitude=request.POST['latitude'], longitude=request.POST['longitude'], user = request.user) when it should be going to if request.POST['radius']: radius_km = request.POST.get('radius', 0) I researched how to stop this happening and saw I could do if request.POST['radius']: to direct the post request to the right function. This hasn't helped with the error unfortunately. Am I missing something? views.py class ConnectView(View): template_name = 'connect/home.html' def get(self, request, *args, **kwargs): f = ProfileFilter(request.GET, queryset=Profile.objects.exclude(user=request.user)) context = { 'users': User.objects.exclude(username=request.user), 'friends': Friend.objects.filter(current_user=request.user), 'filter': f, } return render(request, self.template_name, context) def post(self, request, *args, **kwargs): location = Location(latitude=request.POST['latitude'], longitude=request.POST['longitude'], user = request.user) location.save() if request.POST['radius']: radius_km = request.POST.get('radius', 0) queryset = User.objects.annotate( radius_sqr=pow(models.F('loc__latitude') - request.user.loc.latitude, 2) + pow(models.F('loc__longitude') - request.user.loc.longitude, 2) ).filter( radius_sqr__lte=pow(int(radius_km) / 9, 2) ).exclude(username=request.user) context = {'users': queryset} return JsonResponse({'message': 'success'}) home.html <script> var pos; var $demo; function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { $demo.text("Geolocation is not supported by this browser."); } } function showPosition(position) { pos = position; var … -
How do I get a city name that belongs only to a certain country in Django?
As I do 'cities = Post.objects.all().values('city')' I get list of all the cities. But I don't know how to sort them out by country in order to show them on the template. When I print {{ city }} city names of other countries also come out. I tried on my template {{ country.city }} but everything disappears. my models.py from PIL import Image from django.db import models from django.urls import reverse from django.utils import timezone from django.db.models.signals import post_save from django.contrib.auth.models import AbstractUser class User(AbstractUser): first_name = models.CharField(verbose_name="First name", max_length=255) last_name = models.CharField(verbose_name="First name", max_length=255) country = models.CharField(verbose_name="Country name", max_length=255) city = models.CharField(verbose_name="City name", max_length=255) email = models.EmailField(verbose_name="Email", max_length=255) def __str__(self): return self.username class Post(models.Model): title = models.CharField(max_length=255) country = models.CharField(max_length=255) city = models.CharField(max_length=255) address = models.CharField(max_length=255) email = models.EmailField(max_length=255) phone = models.CharField(max_length=255) website = models.URLField(max_length=255) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('users:blog') class City(models.Model): model = Post def __str__(self): return self.city class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def create_profile(sender, **kwargs): if kwargs['created']: user_profile = Profile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) my views.py def blog(request): context = { 'posts': Post.objects.filter(author=request.user) } return render(request, 'users/post_list.html', context) def … -
How do I reduce duplicate sql queries in django admin
I have a model which is a ForeginKey for a number of other models. I've defined these as TabularInlines within my ModelAdmin. It looks like this: class HouseAdmin(admin.ModelAdmin): list_display = ['owner', 'get_house','number','street','city'] list_filter = ['completed'] readonly_fields = ['slug'] inlines = [HouseWorkInline, HouseDocumentInline, HouseBudgetInline, HouseSelectionInline, \ HouseSpecificationInline] actions = [send_schedule_emails] fieldsets = ( (None, {'fields' : ('owner', 'number','street', 'city', 'start_date','completed')}), ) search_fields = ['street','number','owner__username','city'] It is making 764 queries including 757 similar and 468 duplicates. I'm trying to understand how to reduce this using select_related but nothing I do seems to make any difference. Can anyone give me some guidance please. Thank you -
Deploying a chatbot with Django: WebSockets vs HTTP
I currently have a chatbot app in my django project that I would like to deploy. I am confused as to whether I should use WebSockets or normal HTTP calls (AJAX) for it's implementation. This is what I have understood about the pros/cons of each(in the context of my use-case) till now after some internet research. Reasons for using WebSockets over HTTP: WebSockets are recommended for chat applications because of low overhead per user message once the connection has been established. HTTP will have the overhead of establishing a connection each time a message is sent (Also the header will be bigger in size, which will be sent with each request/user message) WebSockets allow for real-time communication without workarounds like polling in case of HTTP which can lead to many unnecessary requests from the client. Reasons for using HTTP over WebSockets: HTTP just might be okay for a chatbot(not human to human chat) because the response of the chatbot is only triggered when the user messages something i.e. The Bot isn't expected to message the user all of a sudden at random intervals which would require real-time communication. The Bot only sends replies to user messages. Will have to use … -
Edition of many objects in one model table in one form. Django
I have a very simple form to edit one field in the table, it looks like this. class TimeEditForm(forms.ModelForm): class Meta: model = Time fields = ('free_or_no',) Now I would like to create a view in which I have many objects from one table and all of my query set can be edited in one place. How can I transfer many objects to the unit edition? I was looking for answers on the forum but they mainly refer to the editing of many models by one form and not many objects in one table. Any help will be appreciated. My models.py class Time(models.Model): day_time = models.ForeignKey(DayTime, on_delete=models.CASCADE) compartment = models.CharField(max_length=11) free_or_no = models.BooleanField(default=True) views.py def time_edit(request): time = get_object_or_404(Time, pk=pk) # how to replace it correctly in the query set collections, what can I use? like this Time.objects.all()[:12] if request.method == "POST": form = TimeEditForm(request.POST, instance=time) if form.is_valid(): time = form.save(commit=False) time.save() return redirect('account') else: form = TimeEditForm(instance=time) return render(request, 'time_edit.html', {'form': form}) -
How to point FilePond to django media files
I am using FilePond.js to allow users to drag and drop images on a website. I am trying to setup FilePond to retrieve user photo inputs. Apparently I am meant to put in the media link of where I want the photo to be uploaded to. Like so: <script> FilePond.registerPlugin(FilePondPluginImagePreview); const inputElement = document.querySelector('input[type="file"]'); const pond = FilePond.create(inputElement); FilePond.setOptions({ server: "api/" *** MEDIA LINK GOES HERE*** }); </script> But I can't seem to get FilePond to upload the images to the Django media url. My question is how do I point FilePond to upload to the url where my photo is meant to be stored? The only way I know how to collect images from user inputs is with a get request. Also can I just use a get request to just retrieve the users submitted FilePond images and upload them to the database that way? P.S I am trying to point FilePond to upload it to the media url on my development server. Which is http://www.example.local:8000/media -
How to write attachment data?
I'm getting attachment data from Gmail, while I'm writing data it is throwing an error UnicodeDecodeError 'utf-8' codec can't decode byte 0xf0 in position 14: invalid continuation byte service = build('gmail', 'v1', credentials=creds) results = service.users().messages().list(userId='me',labelIds = ['INBOX'],maxResults=10).execute() messages = results.get('messages', []) if not messages: print("No messages found.") else: print("Message snippets:") count = 0 if os.path.exists('token.pickle'): for message in messages: msg_dict = {} msgbody_dict = {} msg = service.users().messages().get(userId='me', id=message['id']).execute() ID=message['id'] payld = msg['payload'] headr = payld['headers'] payload_data = payld['body'] #print('type========================',payld) if 'parts' in payld.keys(): payload_parts = msg['payload']['parts'] for i in payload_parts: payload_headers = i['headers'] for NAME in payload_headers: if NAME['name'] == 'Content-Type': content_type = NAME['value'] if 'text/html' in content_type or 'text/plain' in content_type: partstype_dat = i['body']['data'] partstype_dat=partstype_dat.replace('-', '+') partstype_dat=partstype_dat.replace('_', '/') payldp=base64.urlsafe_b64decode(partstype_dat) payldp = str(payldp , 'utf-8') msgbody_dict['data'] = payldp payload_pldata.append(msgbody_dict) elif i['filename']: attach_parts = i['body'] att_id = attach_parts['attachmentId'] att_data = service.users().messages().attachments().get(userId='me', messageId=ID, id=att_id).execute() encydoc_data = att_data['data'] doc_data = base64.urlsafe_b64decode(encydoc_data.encode('UTF-8')) dcdata = doc_data.decode('ASCII') final_docdata = str(doc_data , 'UTF-8') with open(i['filename'],"w") as f: f.write(final_docdata) -
how to show an image in the django templates dynamically?
I want to show the uploaded image in the django templates,but it was not showing any image,i have successfully uploaded and saved it,how can i fix this problem,could anyone please explain or a sample demo on how we have to configure our settings.py to display the image in templates? my settings.py: LOGIN_URL='/login' STATIC_URL = '/static/' LOGIN_REDIRECT_URL = '/home' LOGOUT_REDIRECT_URL='/accounts' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' my models.py: class Images(models.Model): user_id=models.ForeignKey(User,on_delete=models.CASCADE,null=True) image=models.FileField(upload_to='home') And the Image tag i was using to display it is <img src="{{ obj.image.url }}" class="img-circle" height="65" width="65" alt="Avatar"> -
ValueError - How to Extend OAuth2 Application Model - Django
I want extend Application model of django oauth toolkit. They have given intsructions here https://django-oauth-toolkit.readthedocs.io/en/latest/advanced_topics.html#extending-the-application-model But i am not getting how to do it. I have created one app inside apps folder and inside models i have added the following code. from django.db import models from oauth2_provider.models import AbstractApplication class MyApplication(AbstractApplication): logo = models.ImageField() agree = models.BooleanField() Resgitered the app inside installed_apps as 'apps.oauth2', and added the following line: OAUTH2_PROVIDER_APPLICATION_MODEL='apps.OAuth2' But it giving me error LookupError: No installed app with label 'apps'. -
django rest auth with Google: How to pass key correctly when I send request as a authenticated user?
I'm trying to access API as authenticated user from my mobile app but never successful. I was successful logging in via Google and register with the website from my mobile app but I don't know how to use key which I get when I pass access_token to the login endpoint. I tried to add key to header like Authorization: Token <key> , Authorization: Bearer <key> but both ways didn't work. API returns 403. Anyone knows how to pass key correctly? -
How to get flat value out of a djano-dict?
I need to get the flat value of a Sum out of a query/dict to use it in Chart.js. I am able to get the flat value out of a single item in a query with .values[0]['field']. But if I sum two or 5 (I need the 5 highest values) up, I can't get a flat value back. It's also not possible to add something to () in values (takes no arguments) I appreciate your answers :-) >>> Char.objects.filter(gebiet='Kosmisch')[:5].values().aggregate(Sum('stärke')) {'stärke__sum': 135000} >>> Char.objects.filter(gebiet='Kosmisch')[:5].aggregate(Sum('stärke')).values() dict_values([135000]) As you see my results above, I need the flat 135000. -
Hide a field form in django forms
I am trying to hide the 'password' field in my edit profile form. Even though I have excluded the field it still appears, here is my forms.py file: class EditProfileForm(UserChangeForm): class Meta: model = User fields = ( 'email', 'first_name', 'last_name' ) exclude = ( 'password', ) Here is my html: {% block body %} <div class="container"> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> </div> {% endblock %} A screenshot of what is currently being produced To clarify, I am trying to completely hide the password field -
Writing JSON to file causing Unicode Error on Ubuntu Server 16.04LTS
I am sure that the problem I am experiencing isn't directly related to the OS or version, but instead to some kind of setup. In a python django app I am writing JSON to a file which can contain characters from other languages like 我, ל, and は. At no point in time in the flow of data am I changing the encoding as far as I am aware. During local development, this was not a problem. with open(self._json_path, 'w') as f: json.dump(test_dict, f, indent=2, ensure_ascii=False) answer, wordid, question = self._unpack_dict(test_dict) Once I deployed to the live web server, I began getting: 'ascii' codec can't encode character '\u90fd' in position 1: ordinal not in range(128) I know for a fact that the data in test_dict is encoded properly. As soon as the json.dump occurs, it errors. If I open the file that was created, it fails at the very first non-latin character I put into it. I've been through this post, but couldn't sort out the problem. Adding , encoding='utf-8' causes the output of the above code to create a file but put nothing in it. Again, I know for a fact that test_dict has data as the data is … -
How to make an apk for a django website or is there any way to convert django website to apk?
I have made a website in Django and want to make an android app for the same. Is there any way to convert the website to an apk or we have to code it again from the scratch? -
Specify API View methods in urls
So, I have a view that inherits from APIView, I've defined get, post and delete methods. My urls.py: path('projects/', projects.ProjectView.as_view()), path('projects/create/', projects.ProjectsView.as_view() But right now I can make a request with any method accessing these API's. For example, I can create a project going to 'projects/' and I can delete a project going to 'projects/create/'. Is there a way to specify what methods I wanna use for a specific url? When a user goes to 'projects/' I want only the 'get' method to be allowed for this url.