Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django website in production points to localhost:8000
I'm testing my website built in Django on Apache and I'm facing this problem. Front page is loaded on 'locahost' but when I try to browse other pages I get 404. When I hover over the link and look at what link it points to it says localhost:8000/xxx which is obviously wrong. When I take off the port part of the address the page loads. Why Django behaves like that ? -
Django error when migrations or migrate
When execute python manage.py makemigrations or python manage.py migrate I see the error message: Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line File "/home/ubuntu/mywasi-root/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 13, in <module> from django.core.management.base import ( File "/home/ubuntu/mywasi-root/venv/lib/python3.5/site-packages/django/core/management/base.py", line 17, in <module> from django.db.migrations.exceptions import MigrationSchemaMissing File "/home/ubuntu/mywasi-root/venv/lib/python3.5/site-packages/django/db/migrations/__init__.py", line 1, in <module> from .migration import Migration, swappable_dependency # NOQA ImportError: No module named 'django.db.migrations.migration' Why I see this error and how can I solve it? -
Python multiprocessing on same method that deals with data
I have a Django application where I am trying to manage the data for one of my models, since the number of its table rows in the database has gotten quite unruly. I have a model staticmethod that gets all the 'Vehicle' objects in my database, goes through them, check if their image url is still active, and if not deletes it. There are 1.2 million records, and some records have more than one image I have to check to see if they are all active, so its going to take a pretty long time to go through all the records. I know that you can use threading to run multiple processes, but I also know that for a method that deals with data, each thread has to be aware of the other thread. Is there a way that I can use multithreading to cut down the time it would take to go through a queryset and make those checks, e.g. If the first thread looks at queryset item 1, and 2, thread 2 will start looking at queryset item 3, and than thread 1 will skip to queryset item 4 if its done, and thread 2 hasn't finished with … -
AttributeError: 'NoneType' object has no attribute 'username' (gen = self.generator.username)
models.py I understood the problem but I could not find the solution but I did not like my project because it was different django = 1.10.6. can you help me .I got this error while trying to delete user in admin panel.I did not use the Django ready user model. I could not understand how to solve the error. I can tell English my bad hope problem. Thank you from now. from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.utils.timesince import timesince from django.utils import timezone class Notification(models.Model): Type = models.CharField(max_length=255, blank=True, null=True) recipient = models.ForeignKey( User, null=False, blank=False, related_name="notifications", on_delete=models.CASCADE ) generator = models.ForeignKey( User, related_name='activity_notifications', null=True, blank=True ) target_ctype = models.ForeignKey( ContentType, related_name='related_notifications', blank=True, null=True, on_delete=models.CASCADE ) target_id = models.CharField(max_length=255, blank=True, null=True,) target = GenericForeignKey('target_ctype', 'target_id') action_obj_ctype = models.ForeignKey( ContentType, related_name='action_notifications', blank=True, null=True, on_delete=models.CASCADE ) action_obj_id = models.CharField(max_length=255, blank=True, null=True,) action_obj = GenericForeignKey('action_obj_ctype', 'action_obj_id') read = models.BooleanField(default=False, blank=False) seen = models.BooleanField(default=False, blank=False) action_ve`enter code here`rb = models.CharField( max_length=255, default="You recieved a notification." ) description = models.TextField(null=True, blank=True) reference_url = models.CharField( max_length=1023, blank=True, null=True, default="#" ) timestamp = models.DateTimeField(auto_now=True) def __str__(self): timedlta = timesince(self.timestamp, timezone.now()) gen = self.generator.username fields = … -
How do I delete a field from my Django ModelForm?
I'm trying to hide and delete two fields from showing in a form I created in the Django administration page using ModelForm. I looked at answers that said I should use the "exclude" meta field, but I don't know why it's not working in my case. Here is my code: models.py: class Activity(models.Model): type = models.CharField(max_length=50, default="") title = models.CharField(max_length=200, default="") description = models.CharField(max_length=500) owner = models.ForeignKey(User, related_name="owner") college = models.CharField(max_length=200) location = models.CharField(max_length=200) room = models.CharField(max_length=200) startDate = models.DateTimeField(null=True, blank=True) endDate = models.DateTimeField(null=True, blank=True) attendee = models.ManyToManyField(Attendee, related_name="attendees",null=True, blank=True) volunteer = models.ManyToManyField(Volunteer, related_name="volunteers",null=True, blank=True) in froms.py: class ActivityForm(forms.ModelForm): class Meta: model = Activity fields = ('type', 'title', 'description', 'owner', 'college', 'location', 'room', 'startDate', 'endDate', 'activity_image', ) exclude = ('attendee', 'volunteer',) and in views.py I just imported this form. I'm trying to exclude the "attendee & volunteer" fields from displaying in the Django administration form. -
Django cannot import name RemovedInDjango20Warning
i am new to programming and i face a Django ( 2.0) issue. I am working on a project with a partner and although everything seems to go fine for her (in a new branch) , in PyCharm ( Prof edition ) i have to face some errors. I have installed in my Ubuntu 17.10 three different versions of python . 1)Default 2.7 , 2) 3.6.3 , 3) 3.6.3( including in Anaconda ) . Project's interpreter is Python 3.6.3 ( /usr/bin/Python3.6 ) I downloaded django-bootstrap3 and django-hamlpy and everything seems to be fine , i can import bootstrap from python console . Master is currently an empty django project and it works fine for both of us .i fetched the new branch to test it and i have the following errors: Traceback (most recent call last): File "/home/antonis/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/antonis/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/antonis/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/antonis/Desktop/supplies_tracker/supplies_tracker/views.py", line 5, in item_list return render(request, 'items/index.html.haml', {}) File "/home/antonis/.local/lib/python3.6/site-packages/django/shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "/home/antonis/.local/lib/python3.6/site-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "/home/antonis/.local/lib/python3.6/site-packages/django/template/loader.py", … -
Connecting a Symptom Object to and Identity Object in my Health App
I am creating a Health App that will take the Identity, Symptom, Disease and Treatment of the patient. I have created models: Identity, Symptom, Disease, Treatment. I am using form.ModelForm so that I can save the data to the db i.e. sqlite3. I have created class based views that will handle forms, take field values, sanitize the data, and render the required form and values. Problem: Each time I attempt to save values for the Symptom form it seems to save it, and redirect to a new form but I am not seeing it in the Admin Backend. Code: Model document from django.db import models from django.utils import timezone import datetime class Identity(models.Model): NIS =models.CharField(max_length = 200, primary_key = True) timestamp = models.DateTimeField(auto_now = True) first_name = models.CharField(max_length = 80, null = True) last_name = models.CharField(max_length = 80, null = True ) contact = models.CharField(max_length = 15, null = True) location = models.CharField(max_length = 100, blank = True) birthday= models.DateField(auto_now = False, auto_now_add = False, blank = True, null = True) def __str__(self): return '%s, %s' % (self.first_name ,self.last_name) class Symptom(models.Model): condition_name = models.CharField(max_length = 80, default = '') description = models.TextField(max_length = 1000, default = '') def __str__(self): return … -
Updating attributes based on existing fields from view in Django
I'm using Django to write an application for short URL generator. It generates a short key to be used as short URL when concatenated with the domain name. In the view, the passed key is used to fetch record from the database and redirect the user to that specific URL. While calling the view, I want to update the visit counter on the object instance of the model. This is how my app/views.py is class ShortUrlView(RedirectView): permanent = False query_string = False pattern_name = 'short-url' def get_redirect_url(self, *args, **kwargs): short_url_obj = ShortUrl.objects.find_key(kwargs['key']) if short_url_obj is not None: // update counter is model function to update counter short_url_obj.update_counter() return super().get_redirect_url(*args, **kwargs) else: raise Http404 Now, I have to write code for update_counter() function in the model so that it could be called using a model object just like save(). I can do this in the view itself by updating the visit_counter field and then call save() on it. But how to write the function in the model, as there will no parameter passed in the function call? -
Ordering by sum of difference
I have a model that has one attribute with a list of floats: values = ArrayField(models.FloatField(default=0), default=list, size=64, verbose_name=_('Values')) Currently, I'm getting my entries and order them according to a sum of all diffs of another list: def diff(l1, l2): return sum([abs(v1-v2) for v1, v2 in zip(l1, l2)]) list2 = [0.3, 0, 1, 0.5] entries = Model.objects.all() entries.sort(key=lambda t: diff(t.values, list2)) This works fast if my list of entries is very slow. But I'm afraid with a large number of entries, the comparison and sorting of all the entries get slow since they have to be loaded from the database. Is there a way to make this more efficient? -
Celery: how to get current progress of task-group without blocking?
I'm using Django, Celery, and django-channels. I do have a working solution, it's an OK solution, except that it seems very weird to me. What I'm trying to do is this: update client of a task progress, asynchronously while also updating other elements in the client. Here is my working solution, which actually doesn't utilize groups: task_group = [refresh_func.s(user_profile, search, dont_auto_add) for search in searches] for task in task_group: task.delay() result_dict = { 'type': 'results_update', 'completed':task_group.index(task) + 1, 'total': search_len, } Group(user_profile).send( { 'text': json.dumps(result_dict), } ) Yes, I'm not wrapping my list comprehension with group because if I do I can't iterate on tasks like I do above. See my failed attempt below. My main gripe with this solution is that it really doesn't indicate anything about the task's completeness. It will update the completed count regardless of whether the task was successful. I've scoured Celery's docs and StackOverflow on how to use the group primitive, specifically, their results, quoting: >>> from celery import group >>> from tasks import add >>> job = group([ ... add.s(2, 2), ... add.s(4, 4), ... add.s(8, 8), ... add.s(16, 16), ... add.s(32, 32), ... ]) >>> result = job.apply_async() >>> result.ready() # have … -
Django get_absolute_url in inclusion_tag Issue in Template
The error I'm getting is: NoReverseMatch at / Reverse for 'view_page' not found. 'view_page' is not a valid view function or pattern name. Basically I have a template tag for my app to display the navigation menu on each page, which is dynamic so I can't hard-code the links. I've written an inclusion tag and template: from django import template from ..models import Page register = template.Library() @register.inclusion_tag("tags/page_links.html") def page_links(): all_pages = Page.objects.all() return {'pages': all_pages} And the template tag html in the templates/tags directory: <ul> {% for page in pages %} <li><a href="{{ page.get_absolute_url }}">{{ page.link_name }}</a></li> {% endfor %} </ul> Each page object has an @permalink get_absolute_url() function to get the link. This works fine in other parts of the site but this inclusion tag does not. I'm using it like so: {% load static %} {% load page_tags %} ... <p><b>Navigation:</b></p> {% page_links %} ... But it appears that the pages are having trouble using the view_page view (which otherwise works) in the template tag. What am I missing here?