Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django forms: Foreign Key field with 500 options
I have a Django model with Foriegn Key in it. There are almost 500 objects in the ForeignKey model. When i Use ModelForm. it creates a Select element showing 500 objects. I hope this is not a good way to do. Also if I use multi forms this becomes more heavy to load. I am also open for using javascript if necessary -
Creating a "Yelp" like app as Python programmer
I am a hobby data scientist that has mostly been working in Python; scraping data, managing a Postgresql database and writing Jupiter notebook and python data cleaning and machine learning models. I now want to host my own web page where I can offer my data and created insights in a visual way. First objective is to have one page with an interactive map, and then markers that indicate POIs with additional data being offered to user through clicking on a point (through a pop-up bubble but also an area to the side of the map being dynamically updated to show details about selected marker). Basically a Yelp app, with their map feature. What is the best framework or language to do something like this? In my research I have seen django, plotly dash, bookeh, leaflet, react JavaScript etc. What I'm worried about it to pick something to start learning and then 3 months later I realize I don't have flexibility to add a functionality or visualization. I'm in it here to learn, so happy to learn a new language/framework as long as it will help me also down the road to build in more functionality into my website. -
Pinax app.css not found
I am using pinax template for the time.I am following the documentation.I started the project.Did everything mentioned here. The problem is the page is displayed but the css and javascript files are not loaded.The browser console gives error saying Failed to load resource: the server responded with a status of 404 (Not Found) app.css Failed to load resource: the server responded with a status of 404 (Not Found) site.js Am i missing something here? Is there anything else to do which is not there in documentation? -
django shell-plus: how to veiw a model definition from command line
I was using Django Rest Framework and I came across repr() function When I do in the Django shell >> from articles.api.serializers import PostSerializer print(repr(PostSerializer())) PostSerializer(): id = IntegerField(label='ID', read_only=True) publish_date = DateTimeField(format='%Y-%m-%d %H:%M UTC') is_deleted = BooleanField(required=False) title = CharField(max_length=256) intro_image = ImageField(allow_null=True, max_length=100, required=False) slug = SlugField(max_length=50) task_id = CharField(read_only=True) qa_bool = BooleanField(label='Allow Q&A', required=False) Assume i have model Article. I have tried: >> print(repr(Article)) <class 'articles.models.Article'> I want to see all the fields with their properties from shell. Is it possible -
In need of suggestions regarding creating a authorization structure
In my Django project, depending on the groups my users are in and other factors, I need my users to only be able to access some things or the information they get from the database to be limited depending on their access level. there is also a hierarchy on some of the access levels. Now this affects my model managers, views and my templates. Therefore, if I don't define a proper structure, it will be very troublesome in the future. I was wondering if there is a suitable pattern and how I would be able to create a decent Django project for this ( access levels are object level). I would be grateful if somebody could help me. -
Django REST framework add non-model file upload field in model Serializer
I have following model to add video tutorials. class Tutorial(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid4) url=models.CharField(max_length=500) source=models.CharField(max_length=500,choices=SOURCE_TYPE_CHOICES) title=models.CharField(max_length=100) description=models.TextField() thumbnail=models.ImageField() The problem is that the url field may contain a youtube, or vimeo video link or local file link. By default url field is a CHarField but I want to use it as file field in case of local video field. -
GET request with request parameter in Django Resr
I am trying to do GET with a request parameter in Django Rest. views.py :- class ItemView(generics.ListCreateAPIView): queryset = itemlist.objects.all() serializer_class = ItemListSerializer def perform_create(self, serializer): serializer.save() def get_queryset(self): queryset = itemlist.objects.all() get_param = self.request.GET.get('get_param') if get_param: queryset = queryset.filter(item_name=get_param) return queryset urls.py :- urlpatterns = { url(r'^itemlists/$', ItemView.as_view(), name="itemlist") } itemlists/ returns the list of all items. But, I want to return for a particular item, where let's say, item_name = "abcd" URL will look like, itemlists/abcd/ I tried with, urlpatterns = { url(r'^itemlists/(?P<pk>\d+)$', ItemView.as_view(), name="itemlist") } -
how to use manage.py inexplicitely
so when I'm im in my root directory (where manage.py lives), if I do manage.py runserver it says command not found. I have to do ~/<project_name>/manage.py runserver for it to work. Why is this? -
Forbidden from accessing Django server
What I have done so far: Acquired a Django stack from Bitnami via AWS, it is up and running. I developed a very simple Django app called frontPage on my local Windows machine, its views.py is shown below from django.http import HttpResponse def index(request): return HttpResponse("Hey.") its urls.py file is shown below from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index) ] in mysite container folder, its urls.py file is shown below: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^frontPage/', include('frontPage.urls')), url(r'^admin/', admin.site.urls), ] in mysite container folder, I added app frontPage to its settings.py file as shown below: INSTALLED_APPS = [ 'frontPage', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] the overall structure of my own Django project is: When I executed py manage.py runserver on my local Windows machine, I could access localhost:8000/frontPage with a browser and it showed "Hey". I connected to this Bitnami Django stack via WinSCP and copied my entire "mysite" folder over to under /opt/bitnami/apps/django/django_projects/. From /opt/bitnami/apps/django/django_projects/mysite, I executed python3 manage.py runserver 0.0.0.0:8000, the server is up and running But when I tried to access bitnamiIP:8000/frontPage from my Windows machine, I got a timeout message. What … -
Struggling with a unit-test
ERROR: test_dont_remember_cc (p38.tests.test_stripepayment.StripePaymentTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/infinity/.virtualenvs/p38-1/src/p38/p38/tests/test_stripepayment.py", line 70, in test_dont_remember_cc self.pay(mock_cc(brand='Visa', extra={'amount': '1.00', 'cc_hash': 'new', 'remember_cc': False})) File "/home/infinity/.virtualenvs/p38-1/src/p38/p38/tests/test_stripepayment.py", line 47, in pay self.client.post(reverse('zoneclient-payment'), cc, follow=follow) File "/home/infinity/.virtualenvs/p38-1/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 551, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "/home/infinity/.virtualenvs/p38-1/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 468, in _reverse_with_prefix (lookup_view_s, args, kwargs, len(patterns), patterns)) NoReverseMatch: Reverse for 'zoneclient-payment' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['(?P<clientcode>[0-9]{9})/payment/$'] Here is the unit test def test_dont_remember_cc(self): self.signin() self.pay(mock_cc(brand='Visa', extra={'amount': '1.00', 'cc_hash': 'new', 'remember_cc': False})) rs = self.client.post( reverse('zoneclient-payment', kwargs={'clientcode': 000111222}), {'amount': '1.00', 'quickform': True} ) m = re.search('(var cards =.*)(card_\w+)"(.*)(Visa|Mastercard)', rs.content) self.assertEqual(m, None) self.assertEqual(200, rs.status_code) and in the urls.py file is I have the following # Online payment url(r'^(?P<clientcode>[0-9]{9})/payment/$', csrf_exempt(login_required(OnlinePaymentView.as_view())), name='zoneclient-payment'), It is unclear how to fix that test. Any help? IMPORTANT Be aware I modify that project inside .virtualenv/p38-1/src/p38. I can't apply migrations directly inside p38, because is an app, not a django project. In clear, p38 is a lib inside a virtual environment. I am working on a real django project which use that. ┌─╼ [~/.virtualenvs/p38-1/src/p38/p38] └╼ ls admin.py api context_processors.py crypto.py decorators.py fixtures __init__.py middleware.py payment.py signals.pyc tests urls.pyc webservice admin.pyc apps.py context_processors.pyc crypto.pyc decorators.pyc formats … -
How to override RetrieveAPIView of django
I wrote a API that gets some of logged-in User or request.user by overriding APIView. But I want to reduce the number of lines of code by using generics.RetrieveAPIView somehow. The thing is that RetrieveAPI originally work with pk or id of an object whereas I want using request.user.id instead of pk. So Can I do that with RetrieveAPIView and how can i do that. Any help is appreciated ^^ -
python, django form duplicates label text
As time allows, I am messing around with Django. I have been paying attention to some tutorials and was following this one today on using django-widget-tweaks to add Bootstrap to forms. It "works" but I just noticed something odd. I am creating a required "profile" form on User-X's first login. That model&form have two "address" fields. The model names them "Address1" & "Address2". However, when the form is rendered the label text for Address2 is "Address1". The lavel is correct for the Address1 field. The psrt of the form involved: ... {% for field in profileForm.visible_fields %} <div class="form-group"> {{ field.label_tag }} {% if profileForm.is_bound %} {% if field.errors %} {% render_field field class="form-control is-invalid" %} {% for error in field.errors %} <div class="invalid-feedback"> {{ error }} </div> {% endfor %} {% else %} {% render_field field class="form-control is-valid" %} {% endif %} {% else %} {% render_field field class="form-control" %} {% endif %} {% if field.help_text %} <small class="form-text text-muted">{{ field.help_text }}</small> {% endif %} </div> {% endfor %} <button type="submit">Submit</button> </form> ... From views.py: ... def create_profile(request): if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): pass # does nothing, just trigger the validation else: form = ProfileForm() … -
Django Rest Framework serializer `source` giving weird required error
I have an API that sends me fields with field names that don't match the ones in my model (and that I have no control over) and am trying to map them in the serializer, but for some reason I'm getting the following error: { "phone": [ "This field is required." ], "first_name": [ "This field is required." ], "last_name": [ "This field is required." ], "messenger_id": [ "This field is required." ], "email": [ "This field is required." ], "address": [ "This field is required." ] } when I actually implement this: class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField(source='customer_email') first_name = serializers.CharField(source='first name') last_name = serializers.CharField(source='last name') address = serializers.CharField(source='customer_address') phone = serializers.CharField(source='customer_phone') messenger_id = serializers.IntegerField(source='messenger user id') class Meta: model = User fields = ('id', 'url', 'email', 'first_name', 'last_name', 'address', 'phone', 'messenger_id',) However, among those fields, the only one that's actually required in my model is the email field. I used the source= parameter according to the top rated answer here, but am not sure what's causing the issue here. Thanks! -
Django admin for categories and objects
I have objects and catetories in Django and object has ForeignKey to Category. In Admin user must first create categories and then create objects choosing category from list. What I want to have is file manager metaphore: User opens list of categories, clicks "create object here" and creates one like we do it with folders and files. I wonder if Django has some application for it. Does it? -
Fix a unittest in Django
ERROR: test_dont_remember_cc (p38.tests.test_stripepayment.StripePaymentTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/infinity/.virtualenvs/p38-1/src/p38/p38/tests/test_stripepayment.py", line 70, in test_dont_remember_cc self.pay(mock_cc(brand='Visa', extra={'amount': '1.00', 'cc_hash': 'new', 'remember_cc': False})) File "/home/infinity/.virtualenvs/p38-1/src/p38/p38/tests/test_stripepayment.py", line 47, in pay self.client.post(reverse('zoneclient-payment'), cc, follow=follow) File "/home/infinity/.virtualenvs/p38-1/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 551, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "/home/infinity/.virtualenvs/p38-1/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 468, in _reverse_with_prefix (lookup_view_s, args, kwargs, len(patterns), patterns)) NoReverseMatch: Reverse for 'zoneclient-payment' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['(?P<clientcode>[0-9]{9})/payment/$'] Here is the unit test def test_dont_remember_cc(self): self.signin() self.pay(mock_cc(brand='Visa', extra={'amount': '1.00', 'cc_hash': 'new', 'remember_cc': False})) rs = self.client.post(reverse('zoneclient-payment'), {'amount': '1.00', 'quickform': True}) m = re.search('(var cards =.*)(card_\w+)"(.*)(Visa|Mastercard)', rs.content) self.assertEqual(m, None) self.assertEqual(200, rs.status_code) and the url is # Online payment url(r'^(?P<clientcode>[0-9]{9})/payment/$', csrf_exempt(login_required(OnlinePaymentView.as_view())), name='zoneclient-payment'), It is unclear how to fix that test. Any help? -
how to use objects in django template
I have such object: data[ 'aaa' ] = ['1', 'something1'] data[ 'bbb' ] = ['2', 'something2'] And want to display it (using loop ) in template : {% for row in data %} <span>{{ row }}</span>> {% for d in data.row %} {{ d.0 }} || {{ d.1 }} {% endfor %} {% endfor %} But i see only values within the span tag ( even though array is not empty ) Can you tell me what I am doing wrong ? Thanks in advance, -
Is it possible to make a django_filters.AllValuesFilter with choices subject to a given queryset
I have a model like this one: class Worker(models.Model): city = models.CharField(max_length=50) And the following filter: class CityFilter(django_filters.AllValuesFilter): @property def field(self): f = super(WorkerFilter, self).field f.choices = [('', '--------')] + [(a.pk, a.city) for a in Worker.objects.all()] return f class WorkerFilter(django_filters.FilterSet): city = ActuallyAllValuesFilter() class Meta: model = Worker fields = ['city'] I want to create an AllValuesFilter but whit choices subject to a given queryset instead of all possible values. I mean, I am looking for something like that: class CityFilter(django_filters.AllValuesFilter): @property def field(self, qs): f = super(WorkerFilter, self).field f.choices = [('', '--------')] + [(a.pk, a.city) for a in qs] return f Is there some way to do this? -
Django Image model with dynamic upload_to function using generic relation
I am creating an Image model which will be used by other models via generic relation. For example, Newsposts and events will have images. Below is the sample Image model class Image(models.Model): description = models.CharField(max_length=500, null=True, blank=True) image = models.ImageField(upload_to=get_storage_path) content_type=models.ForeignKey(ContentType,on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() This will store the image in only one directory. However the problem is I cannot figure out how can I write a dynamic upload_to function that will store the images in the corresponding directories, e.g images/news/ and images/events. -
Django - loaddata from JSON dump gives 'no such table' error
I am trying to load a JSON dump of my Django Sqlite db into a fresh db, using manage.py loaddata. I am encountering the following django.db.utils.OperationalError, however: Could not load foo.Bar(pk=1): no such table: foo_bar The table is definitely present in the database, and all my migrations are applied, checked using showmigrations. So I am stumped as to what's going on. I would not be surprised if it's something simple, however. Would appreciate any suggestions. N.B: The db I'm trying to load the data into is just an empty file. Might that be the issue? Do I need to create the relevant tables in that fresh db before loading into it from the fixture? -
Django project with PostgreSQL database in Docker container - directory /var/lib/postgresql/data exists but is not empty
I try to run Django project in Docker container. Until now, everything was working fine. I didn't change anything but I get error shown at the bottom. Any ideas what is wrong? My PostgreSQL settings look in this way: DATABASES = { "default": { 'ENGINE': 'django.db.backends.postgresql', "NAME": 'myproject', "HOST": "db", "PORT": "5432", } } DATABASES = {'default': dj_database_url.config(default='postgres://addw...@ec2-31-11-107-127.compute-1.amazonaws.com:5432/qdsfks')} docker-compose.yml: version: '3' services: db: image: postgres environment: POSTGRES_USER: myproject POSTGRES_PASSWORD: somepass volumes: - "./local_pgdata:/var/lib/postgresql/data/pgdata" django: build: . command: python3 manage.py runserver 0.0.0.0:8001 volumes: - .:/code ports: - "8001:8001" depends_on: - db Logs: db_1 | The files belonging to this database system will be owned by user "postgres". db_1 | This user must also own the server process. db_1 | db_1 | The database cluster will be initialized with locale "en_US.utf8". db_1 | The default database encoding has accordingly been set to "UTF8". db_1 | The default text search configuration will be set to "english". db_1 | db_1 | Data page checksums are disabled. db_1 | db_1 | initdb: directory "/var/lib/postgresql/data" exists but is not empty db_1 | If you want to create a new database system, either remove or empty db_1 | the directory "/var/lib/postgresql/data" or run initdb db_1 | with … -
DELETE method in Django Rest
I am trying to DELETE record in Django Rest. views.py :- class ItemDeleteView(generics.RetrieveUpdateDestroyAPIView): queryset = itemlist.objects.all() serializer_class = ItemlistSerializer def destroy(self, request, *args, **kwargs): obj = self.get_object() if obj.survey: return Response(data={'message': "Too late to delete"}, status=status.HTTP_400_BAD_REQUEST) self.perform_destroy(obj) return Response(status=status.HTTP_204_NO_CONTENT) urls.py :- urlpatterns = { url(r'^itemlists/$', ItemView.as_view(), name="create"), url(r'^itemlists/(?P<pk>\d+)/$', ItemPartialUpdateView.as_view(), name="update"), url(r'^itemlists/(?P<pk>\d+)/$', ItemDeleteView.as_view(), name="delete"), } Now, when I am sending DELETE request to itemlists/1/ , it is not deleting the record with id = 1 Error is showing Method DELETE not allowed (CREATE, READ, UPDATE are working except DELETE, so I don't think it's cors related issue). -
Pickling error when trying to run python class static method
I am trying to run a static method on one of my classes in my Django application. I am using the multiprocessing model to make this task a little faster since the method will be iterating over a large amount of objects in my database. It works fine when I run it locally, but when I run it in production I get this pickling error... Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/socialauto/social-auto-web/vehicle/models.py", line 193, in image_existence_check p.map(Vehicle.check_image, enumerate(vehicles)) File "/usr/lib/python3.4/multiprocessing/pool.py", line 260, in map return self._map_async(func, iterable, mapstar, chunksize).get() File "/usr/lib/python3.4/multiprocessing/pool.py", line 599, in get raise self._value File "/usr/lib/python3.4/multiprocessing/pool.py", line 383, in _handle_tasks put(task) File "/usr/lib/python3.4/multiprocessing/connection.py", line 206, in send self._send_bytes(ForkingPickler.dumps(obj)) File "/usr/lib/python3.4/multiprocessing/reduction.py", line 50, in dumps cls(buf, protocol).dump(obj) _pickle.PicklingError: Can't pickle <function Vehicle.check_image at 0x7f49974d5268>: attribute lookup check_image on vehicle.models failed Por Que Model method: @staticmethod def check_image(veh): index = veh[0] print(index) veh = veh[1] try: images = veh.images.all() if images.count() == 1: image = images[0] response = requests.get(image.image_url) if response.status_code == 200: veh.has_image = True else: veh.has_image = False elif images.count() > 1: has_image = True for img in images: response = requests.get(img.image_url) if response != 200: has_image = False veh.has_image = … -
Inserting images in django blogpost
Please help me out to define a proper architecture for a Django blog project. The thing which is not clear to me is how to handle an undefined number of images in my blog model. The ImageField is not helpful for this as it would only work with a fixed number and It won't allow me to be flexible. Should I upload them somewhere and insert the URLs to my TexfField? That doesn't look like an elegant way to handle images... -
Multiple images in Django model
I am currently trying to create a Django model for a product on an e-commerce website that would hold several images (from 1 to 9 ) and by now I found out that the right way to do this is creating a model for a Product and a separate model for just images (with a ForeignKey). What troubles me is the way of showing those images to the users in a ProductDetailView. I could create the models and I coould make it work from the admin to add and remove the images, although I don't know how to display them in the product detail view. New to Django, so appreciate every answer. Have a great day. -
Filter exact ID when comparing relationships
I'm trying to filter an ID when comparing two relationships, this is the code I have: Models: ModelA class ModelA(models.Model): name = models.CharField(max_length=20) def __str__(self): return '%s' %(self.id) ModelB class ModelB(models.Model): relationship = models.OneToOneField(ModelA) def __str__(self): return '%s' %(self.relationship) ModelC class ModelC(models.Model): relationship_A = models.ForeignKey('ModelA', null=True, blank=True) relationship_B = models.ForeignKey('ModelB', null=True, blank=True) def __str__(self): return '%s' %(self.id) Views: View of the ModelA def RegModelA(request): form = "" if request.method == "POST": form = ModelAForm(request.POST) if form.is_valid(): save = form.save() create_modelc = ModelC.objects.create(relationship_A=save, relationship_B=None) return redirect('/') else: form = ModelAForm() return render(request, "template.html", {"form":form}) The result so far is the following: Click to see result View of the ModelB def RegModelB(request): form = "" if request.method == "POST": form = ModelBForm(request.POST) if form.is_valid(): save = form.save() update_modelc = ModelC.objects.filter().update(relationship_B=save) return redirect('/') else: form = ModelBForm() return render(request, "template.html", {"form":form}) I want to get the exact ID of the ModelC when relationship_A == save_relationship so that it is updated relationship_B. How should I use the filter to get that id in the ModelB view? Using: Python 3.5 & Django 1.11