Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to force reload only some sources in Chrome
I’m developing a web application written in Django, I’m running the server in my machine and use Chrome/Firefox to view and test the website. I want to be able to work on it while I’m on a plane/tube and I don’t have internet. Now, the HTML loads some resources from the local server but some others from external CDNs. I want to work on some js and css files that are hosted on my machine and view the changes in the browser, so I have to force reload the website since chrome by default just shows the cached versions of these, but if I force reload, then ALL sources are reloaded and the CDN sources obviously fail to be fetched (and my site looks horrible). So I want to know how I can reload (in Chrome or Firefox) only some of the sources of my site and still used the cached versions of the CDN ones (assume these are cached because I load them before going into the plane). Any help or advise on how other people would solve this would be much appreciated. -
Slider button in django to toggle a boolean
I was able to add a slider button to my view, and it toggles the way I like, but unfortunately I am not experienced enough to make it do anything! Can someone point me in the right direction here, any help is appreciated. I want this toggle to "look" to see the status of this objects "isDefault" value, then change the toggle appropriately. Then when user presses it, it will toggle the value of "isDefault". defaults/models.py from django.db import models from django.urls import reverse class DefaultDMLSProcessParams(models.Model): customerTag = models.CharField(max_length=50,) defaultParamDescrip = models.CharField(max_length=50,blank=True,default="Default Parameters",) processType = models.CharField(max_length=50,blank=True,default="",) processNotes = models.TextField(max_length=300,blank=True,default = "") processDescrip = models.CharField(max_length=100,blank=True,default="",) tempHighThres = models.CharField(max_length=10,blank=True,default="30") tempLowThres = models.CharField(max_length=10,blank=True,default="15") humidHighThres = models.CharField(max_length=10,blank=True,default="75") humidLowThres = models.CharField(max_length=10,blank=True,default="30") hardRecoatThres = models.CharField(max_length=10,blank=True,default="800") processMaterial = models.CharField(max_length=50,blank=True,default = "") processLayerHeight = models.CharField(max_length=10,blank=True,default = "") isDefault = models.BooleanField(default = False) def __str__(self): return str(self.defaultParamDescrip) def get_absolute_url(self): return reverse('Default_Listview',) defaults/Views.py (other views removed to shorten post) from django.shortcuts import render from defaults.forms import processParams from django.views.generic import TemplateView from django.shortcuts import render, redirect, HttpResponse from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy from django.views import generic from django.views.generic import ListView, DetailView from django.views.generic.edit import UpdateView, DeleteView, CreateView from . import models from django.contrib.auth.mixins import LoginRequiredMixin class DefaultsListView(LoginRequiredMixin,ListView): … -
python3 django cant load imgur images to html <img src...> if havent been open already manually
I am working on a project i python3 django, it will test your knowledge from roadsigns in slovakia. A problem occured when i stored all 300 signs images on imgur. If i open firstly just image with a sign and than image inside of my html page everything works just fine, but i need to generate random images so i dont know which one will be next one. Console in google chrome gives me 403 error code 'forbidden' also i can see in network tab of developer tools that it loads the image as txt/plai, which seems suspicious to me. can you help me somehow please? -
How can I define variable in django template engine
How can I define variable in django template engine and change it while iteration? I want to create panel for posts management that I get from database and display them in table. then I want to set counter for table and for each post that I get from db increase it by one But I don't know how to define and set variable in template engine. -
(React Native) android emulator is not showing more than 6 images.
My back-end is fine. I tried many ways to fix this problem, but it still shows the same result. Approach added android:largeHeap="true" to the AndroidMnifest.xml cropped the image ..? -
AJAX form validation in Django Template
I am practicing AJAX in django template project, i have a signup form where i have 4 fields to submit,i'm using signup button feature to implement ajax function,its working fine, but problem is when i am keeping form empty and hitting the button its also submitting, so how can i validate fields that when there would be no values given it would show error msg to fill up all fields? Thnaks in advance. <script> $(document).ready(function(){ $('#signup-btn').click(function(event){ console.log('hi-signup') $.ajax({ method: "POST", url: '/register', data: { name :$('#id_fullname').val(), email : $('#id_email').val(), country : $('#id_country').val(), password : $('#id_password').val(), csrfmiddlewaretoken:'{{ csrf_token }}', }, success: function(res) { var response = $.parseJSON(res) $('.signup-data').html(response.msg) if (response.code == 200) { $('.signup-data').html(response.msg); window.location = "http://localhost:8000"; } }, }) }) }) </script> html <form class="my-signup-form" action="/register" method="post"> {% csrf_token %} <div class="signup-data"></div> <div class="top-row"> <div class="field-wrap"> <input name="signup-fullname" id="id_fullname" type="text" required autocomplete="off" placeholder="Full Name"/> </div> <div class="field-wrap"> <input name="signup-email" id="id_email" type="text"required autocomplete="off" placeholder="Email ID"/> </div> </div> <div class="field-wrap select2"> <span class="select-arrow"></span> <select name="signup-country" id="id_country" class="selextbox"> <option value="" selected disabled>Select your country</option> <option value="United States">United States</option> <option value="United Kingdom">United Kingdom</option> <option value="Afghanistan">Afghanistan</option> </select> </div> <div class="field-wrap"> <input name="signup-password" id="id_password" type="password"required autocomplete="off" placeholder="Password"/> </div> <p class="charcters">Minimum 8 Charcters</p> <button id="signup-btn" type="button" class="button … -
How to correctly create a response for the selected values for Ext.data.TreeStore on django
I have several objects in the database that I want to display in Ext.tree.Panel - [{'id': '1', 'name': 'title1', 'id_parent': ''}, {'id': '2', 'name': 'title2', 'id_parent': ''}, {'id': '3', 'name': 'title3', 'id_parent': ''}, {'id': '4', 'name': 'subtitle1', 'id_parent': '1'}, ..... The model itself looks like this: class Storage(models.Model): name = models.CharField(max_length = 255, null=True) id_parent = models.CharField(max_length = 255, null=True) How to correctly create an array of data for an answer in Ext.data.TreeStore? if model == 'Storage': if method == 'Read': try: # Read the data storage = Storage.objects.all() # Form a list for the answer list_sr = [] for item_sr in storage: dict_sr = {} dict_sr['id'] = str(item_sr.id) dict_sr['name'] = item_sr.name dict_sr['id_parent'] = item_sr.id_parent list_sr.append(dict_sr) # Form the answer dict_tr = {"data": list_sr, "meta": {"success": "true", "msg": ""}} #How to correctly create an array of data for an answer in Ext.data.TreeStore? # Let's translate it into Json format jsonFormat = json.dumps(dict_tr) read_out = '(' + jsonFormat + ')' return HttpResponse(read_out) -
Django + Vue. Can't connect params
So, the problem is that i can't connect Django REST with Vue. When I'm calling API from Client it says: Not Found: /api/private/ [16/Sep/2018 13:18:59] "GET /api/private/?city=London HTTP/1.1" 404 2129 This is my code: Vue function callWeather () { const url = `${API_URL}/api/private/` return axios.get(url, { headers: { Authorization: `Bearer ${AuthService.getAuthToken()}` }, params: { 'city': 'London' } }).then((response) => { console.log(response.data) this.message = response.data || '' }) } Django api url: urlpatterns = [ url(r'^api/public/', views.public), url(r'^api/private/(?P<city>\w+)/$', views.private) ] Django private func: @api_view(['GET']) def private(request, city): return HttpResponse("City is: {}.".format(city)) -
Attempting Join and getting Invalid field name(s) given in select_related: 'audio_links'. Choices are: (none)
I'm trying to do a Join on two tables - would like to return all data from both ReleasesAll and AudioLinks. Error FieldError at /api/release/0 Invalid field name(s) given in select_related: 'audio_links'. Choices are: (none) models.py class ReleasesAll(models.Model): id = models.IntegerField(primary_key=True) artist = models.CharField(max_length=255) all_artists = models.CharField(max_length=200) remixers = models.TextField(blank=True, null=True) format = models.CharField(max_length=80) title = models.CharField(max_length=255) label = models.CharField(max_length=255) label_no_country = models.CharField(max_length=255) class Meta: managed = False db_table = 'releases_all' class AudioLinks(models.Model): release = models.ForeignKey('ReleasesAll', models.DO_NOTHING, db_column='release_id') track_number = models.IntegerField() track_name = models.CharField(max_length=500) url = models.CharField(max_length=500) m3u_link = models.TextField() type = models.CharField(max_length=50, blank=True, null=True) class Meta: managed = False db_table = 'audio_links' views.py class ListReleaseDetailView(generics.RetrieveUpdateDestroyAPIView): queryset = ReleasesAll.objects.all() serializer_class = ReleasesSerializer def get(self, request, *args, **kwargs): try: a_release = self.queryset.select_related('audio_links__release_id').get(pk=kwargs['release_id']) return Response(ReleasesSerializer(a_release).data) except ReleasesAll.DoesNotExist: return Response( data = { "message": "{} does not exist".format(kwargs["release_id"]) }, status=status.HTTP_404_NOT_FOUND If I remove the select_related then the query works -
Catch specific errors in python
I was trying to catch a specific exception: username = 'myuser' try: user = User.objects.get(username=username) print(user) except Exception as e: if type(e)=='django.contrib.auth.models.User.DoesNotExist': print('No such user') print (type(e)) But instead of going into the if loop, I am getting: <class 'django.contrib.auth.models.User.DoesNotExist'> Why is this happening? How can I catch a specific exception? -
How to access a table record by id of another table in many to many relationship in django?
Here is my model : class Movie(models.Model): genre = models.ManyToManyField(Genre) class Genre(models.Model): genre_eng = models.CharField(max_length=200) def __str__(self): return "{}".format(self.genre_eng) and here is my view method : def info(request, id): movie_info = Movie.objects.get(id=id) return render(request,'info.html', {'movie_info': movie_info}) I can already print the name of the movie like this in info.html file: genre : {{movie_info.title}} How Can I access the genre_eng in the info.html file? each movie may have multiple genres. -
Django: Display user's previous choices for a ModelForm in the template
I am trying to create a user profile page where users can see and update their preferences for certain things, like whether they are vegetarian, or have a particular allergy, etc. I want the data to be displayed as a form, with their current preferences already populating the form fields. So I've created the following Model: class FoodPreferences(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # One user has one set of food prefs vegetarian = models.BooleanField() vegan = models.BooleanField() ... that's referenced in my forms.py: class FoodPreferencesForm(forms.ModelForm): class Meta: model = FoodPreferences exclude = ('user', ) I've tried creating a view that inherits FormView and then referencing the form, like this: class UserProfileView(generic.FormView): template_name = "registration/profile.html" form_class = FoodPreferencesForm success_url = reverse_lazy('user_profile') This saves the form to a instance of the model correctly, but obviously it just displays the blank form again, after updating, so the user has no idea what their current preferences are. To implement this I thought I might need to override get() and post() to get the instance of FoodPreferences for the user, and then pass those values into the form like you would a request.POST object. However, firstly, I don't know how to do that, and secondly … -
Handling django rest framework + vue SPA auth
How could I get the same functionality as django provides for authenticated user (an user global object to retrieve data for user profile etc.) into vue, for a single page application (using Vue Router, of course). My point is that I do not know how could I create a middleware for vue equivalently to django middleware for keeping an user logged in once he provided username and password. I know that I can use django rest framework jwt to implement an endpoint /api-token-auth/ to get the token needed (storing it into localStorge, so I could get it into axios headers) to be able to retrieve information from the api, but I don't have any user session besides the token, I don't have any information about the user passed to templates, of course. How could I pass an user global object to every template? Is there an easy way to do that? Thanks in advance. -
Django Query set for counting records each month
class Orders(models.Model): orderid = models.IntegerField(db_column='orderID', primary_key=True) pickupdate = models.DateField(db_column='pickupDate', blank=True, null=True) I want to display total records in the Model for each month. The solution that I have found require me to enter year Orders.objects.filter(pickupdate__year = '2006').values_list('pickupdate__month').annotate(total = Count('orderid') The results are like this : <QuerySet [(1, 31), (2, 27), (3, 31), (4, 30), (5, 31), (6, 29), (7, 30), (8, 31), (9, 30), (10, 31), (11, 30), (12, 31)]> I want that the queryset able to get the monthly range automatically from the database. The data that I want to display is like this : Month | Total January 2007 | 1 February 2007| 2 etc enter code here -
Django initialize data test for all test classes
I need to add test to my django project, I need to create data test before execute tests. I read about setUp test data in this question. I can create data in setUpClass for all test in a class. Creating my complete data test is time consuming approach so I want to run it once for all of test classes, is any approach to set up data for all test classes once? -
Django; Is it okay to change SECRET_KEY on my own?
I'm trying to deploy my app. So I'm thinking of changing SECRET_KEY that attached originally. Is it okay? Also when I try to set the key environment variable, a part of the key like !5 cannot be set on WSL. How can I fix this? -
Django Rest Framework angularjs session auth user
I keep getting this error when accessing request.user from my viewSet class. TypeError: int() argument must be a string, a bytes-like object or a number, not 'AnonymousUser' Viewset class FriendRequestViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ def list(self, request): queryset = FriendshipRequest.objects.filter(to_user=request.user) print(queryset) serializer = FriendRequestSerializer(queryset, many=True) return Response(serializer.data) queryset = FriendshipRequest.objects.all() serializer_class = FriendRequestSerializer it works fine with postman I get authenticated user. but with my angularJs Application I get Internal error. This is the service: this.getFriendRequests = function () { var token = $window.sessionStorage.getItem('token'); console.log('TOKEN IS => ' + token); console.log('cookie is : ' + getCookie('csrftoken')); $http.defaults.headers.post['X-CSRFTOKEN'] = getCookie('csrftoken'); return $http.get('http://127.0.0.1:8000/friendsrq/', { headers: { 'Authorization': 'token: ' + token } }); }; I use Token authentification -
account/list_of_post_by_subactegory.html TemplateDoesNotExist
I can't solve this problem. When you try to load the page, list_of_post_by_subcategory.html throws TemplatesDoesNotExist. Please help. models.py class Category(models.Model): category = models.CharField(max_length=250) slug = models.SlugField() def __str__(self): return self.category def get_absolute_url(self): return reverse('list_of_post_by_category', args=[self.slug]) class SubCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True, related_name="subcategories") subcategory = models.CharField(max_length=250) slug = models.SlugField() def __str__(self): return self.subcategory def get_absolute_url(self): return reverse('list_of_post_by_subcategory', args=[self.slug]) urls.py url(r'^category/(?P<slug>[-\w]+)/$', views.list_of_post_by_category, name= 'list_of_post_by_category'), url(r'^subcategory/(?P<slug>[-\w]+)/$', views.list_of_post_by_subcategory, name= 'list_of_post_by_subcategory'), views.py def list_of_post_by_category(request, slug): categories = Category.objects.all() category=get_object_or_404(Category, slug = slug) subcategories = SubCategory.objects.filter(category=category) posts = Post.objects.filter(category=category) return render(request, "account/list_of_post_by_category.html", {'categories': categories, 'posts': posts, 'category': category, 'subcategories': subcategories}) def list_of_post_by_subcategory(request, slug): subcategory=get_object_or_404(SubCategory, slug=slug) posts = Post.objects.filter(subcategory=subcategory) return render(request, "account/list_of_post_by_subcategory.html", {'posts': posts, 'subcategory': subcategory}) list_of_post_by_subcategory.html {% extends "base.html" %} {% block title %}{{ subcategory.subcategory }}{% endblock %} {% block content %} <h1>{{ subcategory.subcategory }}</h1> {% for post in posts %} <div class="single_post"> <a href="{{ post.get_absolute_url }}">{{ post.title }}</a> <br/> <br/> <div> {{ post.publish }} {{ post.subcategory }} </div> </div> {% endfor %} <br/> {% endblock %} Similar template list_of_post_by_category.html loads correctly. But list_of_post_by_subcategory.html throws TemplateDoesNotExist. -
Template filters do not work inside include
I am trying to use the build in template tag filter default_if_none. However it appears not to work when I include it in an {% include %} tag, e.g. {% include 'foobar.html' with myfield=myfield %} where foobar.html is {{ myfield|default_if_none:'' }} When I place the html inside the parent document it works as expected. Does this have something to do with the include tag? How can I fix this? -
Superuser creation skipped due to not running TTY Django. Babun Shell
So I have been trying to create a superuser for a application in Django on Babun Shell. I am getting the following error time and time again: 'Superuser creation skipped due to not running in a TTY. You can run manage.py createsuperuser in your project to create one manually.' I have tired : 'winpty python manage.py creatsuperuser' this gave me the following result: 'stdin is not a tty' Could someone explain to me where I am going wrong and what am I missing? -
When I typed 'python manage.py shell' , I am getting this stuff.Please explain what is this?
E:\myenv\mydjango1\mysite>python manage.py shell Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] Type 'copyright', 'credits' or 'license' for more information IPython 6.5.0 -- An enhanced Interactive Python. Type '?' for help. In [2]: In [4]: -
flask or django for image processing?
I am a master student and I am working on master project . it's about image processing on the web to recognize facial features mathematically and exaggerate some features . Should I start with Django or flask framework??? thank you -
Django Rest Framework - return different serializer in same viewset
I have two models: where class Hunter(Model): name = CharField() searches for class Target(Model): name = CharField() user = ForeignKey(User) approved_hunters = ManyToManyField(Hunter) my serializers are class AnonymousTargetSerializer(ModelSerializer): class Meta: name = 'target' model = Target fields = ['id',] and also class TargetSerializer(ModelSerializer): class Meta: name = 'target' model = Target fields = ['id',] Im my viewsets I would like to: hunter = Hunter.objects.get(user=self.request.user) if hunter in Target.approved_hunters.all() return TagetSerializer else: return AnonymousTargetSerializer However I only seem to get this done for the viewset, but cannot filter on an individual object level. -
Avoid duplicates using django ModelForm
I have the following Model, ModelForm and View: class Clinic(models.Model): clinicid = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=60) label = models.SlugField(max_length=25) # logo = email = models.EmailField(max_length=50, default='') mobile = models.CharField(max_length=15, default='') alternate = models.CharField(max_length=15, default='', blank=True) about = models.CharField(max_length=250, blank=True) state = models.CharField(max_length=25) city = models.CharField(max_length=35) locality = models.CharField(max_length=35) pincode = models.IntegerField(default=0) address = models.TextField(max_length=80, default='', blank=True) website = models.URLField(blank=True) class ClinicMetaForm(ModelForm): class Meta: model = Clinic fields = [ 'name', 'label', 'email', 'mobile', 'alternate', 'about', 'state', 'city', 'locality', 'pincode', 'address', 'website' ] unique_together = ["name", "mobile", "email"] def newclinic(request): if request.method == 'POST': print('New clinic setup') form = ClinicMetaForm(request.POST) form.save() msg = "Successfully saved new clinic" print(msg) else: form = ClinicMetaForm() msg='' return render(request, 'clinic/newclinic.html', {'form': form, 'msg': msg}) The problem is that when the same data is submitted, I get duplicate entries being saved, even though I am using unique_together. Why is this happening? How can I avoid it? -
Use HyperlinkedModelSerializer in ManyToMany field in Django
Scenario In a project, I have following code. models.py class Section(models.Model): name = models.CharField(_('Section'), max_length=254, unique=True) desc = models.TextField(_('Description'), null=True, blank=True) class Item(CreateUpdateModel): name = models.CharField(_('Name'), max_length=254, unique=True) price = models.DecimalField(_('Item Price'), max_digits=10, decimal_places=3) sections = models.ManyToManyField(Section) desc = models.TextField(_('Description'), null=True, blank=True) serializers.py class ShowSectionSerializer(serializers.HyperlinkedModelSerializer): item_set = serializers.HyperlinkedIdentityField(view_name='Show Section Items', lookup_url_kwarg='sections',lookup_field='id') class Meta: from .models import Section model = Section fields = ('name', 'id', 'desc', 'item_set') class ShowItemSerializer(serializers.ModelSerializer): sections = ShowSectionSerializer(many=True) class Meta: from .models import Item model = Item fields = ('id', 'name', 'sections', 'desc') urls.py path('show/item/section/<int:sections>', views.ShowSectionItemView.as_view(), name='Show Section Items'), path('show/section/', views.ShowSectionView.as_view(), name='Show Sections'), path('show/item/', views.ShowItemView.as_view(), name='Show-Item'), views.py class ShowItemView(ListAPIView): from .models import Item from .serializers import ShowItemSerializer from django_filters.rest_framework import DjangoFilterBackend from rest_framework.filters import SearchFilter from .filters import MenuFiltering from .paginations import CustomPageSizePagination permission_classes = (AllowAny, ) queryset = Item.objects.all().order_by('id') serializer_class = ShowItemSerializer filter_backends = (DjangoFilterBackend, SearchFilter) pagination_class = CustomPageSizePagination filter_class = MenuFiltering search_fields = ('^name', '^sections__name') class ShowSectionItemView(ShowItemView): lookup_field = 'sections__id' lookup_url_kwarg = 'sections' search_fields = ('^name',) def get_queryset(self): return self.queryset.filter(sections__id=self.kwargs.get('sections')) class ShowSectionView(ListAPIView): from .models import Section from .serializers import ShowSectionSerializer from django_filters.rest_framework import DjangoFilterBackend from .paginations import CustomPageSizePagination from .filters import SectionFiltering from rest_framework.filters import SearchFilter filter_class = SectionFiltering pagination_class = CustomPageSizePagination permission_classes = (AllowAny, …