Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'Uploads' object is not iterable in Django
I am trying to have each model object have it's own page with all the other model objects attached to it, using the modal id, I tried using the {{ img.queryset.all.id }} html tag to display the photo, but that didn't work. I know the problem is in either the views.py or single_page.html, and maybe the models.py but I believe that is unlikely the problem. When I click onto the photo it bring it to a page with the photo icon, it doesn't display it because the photo is unknown. While every time I use {% for x in img %} it says 'Uploads' object is not integrable. If anyone could help that would be great. modals.py class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, null = False, blank = True) first_name = models.CharField(max_length = 50, null = True, blank = True) last_name = models.CharField(max_length = 50, null = True, blank = True) phone = models.CharField(max_length = 50, null = True, blank = True) email = models.EmailField(max_length = 50, null = True, blank = True) bio = models.TextField(max_length = 300, null = True, blank = True) profile_picture = models.ImageField(default = 'default.png', upload_to = "img/%y", null = True, blank = True) … -
SQL Query Failure using Django, Djongo, and mongoDB During user registration with allauth
I am getting a failed sql exception when users attempt to register with a site I wrote in Django, using djongo to interface with mongoDB. The above exception ( Keyword: None Sub SQL: None FAILED SQL: ('SELECT (1) AS "a" FROM "account_emailaddress" WHERE ("account_emailaddress"."user_id" = %(0)s AND "account_emailaddress"."verified") LIMIT 1',) Params: ((7,),) Version: 1.3.6) was the direct cause of the following exception: 'return self.cursor.execute(sql, params)' -
relation "itouch_photo" does not exist
i have an app hosted in heroku while i did not set debug = false, when i visit the website it's throws me an error like this: relation "itouch_photo" does not exist LINE 1: ...ch_photo"."price", "itouch_photo"."location" FROM "itouch_ph... and also it highlight my template: {% for photo in photos reversed %} I did not use command prompt i developed an app through heroku dashboard. how can i slove that: the models: class Photo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.CharField(max_length=30,null=True, blank=False) image = CloudinaryField('image') description = models.TextField(null=True) date_added = models.DateTimeField(auto_now_add=True) phone = models.CharField(max_length=12, null=False, blank=False) price = models.CharField(max_length=30,blank=False) location = models.CharField(max_length=20, blank=False) def __str__(self): return str(self.category) the views: def dashboard(request): photos = Photo.objects.all() context = {'photos': photos} return render(request, 'dashboard.html', {'photos': photos} ) def home(request): photos = Photo.objects.all() context = {'photos': photos} return render(request, 'home.html', {'photos': photos} ) i think the problem is coming from this model up here -
How to handle redirect for login_required in htmx partial view?
I have two views. class IndexView(TemplateView): template_name = 'index.html' @require_POST @login_required def partial_view(request): return render(request, 'partials/stuff.html') I want the index page to be "public" but if user takes action (which triggers partial view), they should be redirected to LOGIN_URL, if not logged in. The problem is that my partial view will return the entire LOGIN_URL page. So there's a page within a page now. Is it possible to redirect the "parent" page when using partial views? -
How to upload an image from vue js to django rest framework?
I am using django-rest-framework as my backend and I want to upload an Image from the frontend(vuejs2) note: the backend works perfectly and I can upload the photo using django admin -
Django rest framework: how to make a view to delete multiple objects?
I am building a simple Photos-Albums app with Django Rest Framework (DRF). I would like to be able to delete multiple albums at once by supplying an array of ids. I am using viewsets.ModelViewSet for the basic views. class AlbumViewSet(viewsets.ModelViewSet): queryset = Album.objects.all() serializer_class = AlbumSerializer I have managed to create a view to show the albums before the delete operation by adding this function to my views.py file. @api_view(['GET', 'DELETE']) def delete_albums(request): """ GET: list all albums DELETE: delete multiple albums """ if request.method == 'GET': albums = Album.objects.all() serializer = AlbumSerializer(albums, many=True) return Response(serializer.data) elif request.method == 'DELETE': ids = request.data albums = Album.objects.filter(id__in=ids) for album in albums: album.delete() serializer = AlbumSerializer(albums, many=True) return Response(serializer.data) If I run curl -X delete -H "Content-Type: application/json" http://localhost:8000/albums/delete -d '{"data":[1,2,3]}' then it will delete albums with ids 1,2,3. This is OK, except that: It's not class-based, and I'd prefer to have everything class-based if possible I would prefer to have a form in the view that lets me input an array e.g. [1,2,3], hit a delete button, and then see the results of the query in the browser, much like when one posts a new object through the interface. Can anyone … -
Is There A Way To Improve Performance Of Data Dictionary Model To Dict Appraoch?
I am currently getting a bunch of records for formsets in my Django application with the method below... line_items = BudgetLineItem.objects.filter(budget_pk=dropdown) line_item_listofdicts = [] for line_item in line_items: line_item_dict = model_to_dict(line_item) del line_item_dict['id'] del line_item_dict['budget'] del line_item_dict['archive_budget'] del line_item_dict['new_budget'] del line_item_dict['update_budget'] line_item_listofdicts.append(line_item_dict) UpdateBudgetLineItemFormSet = inlineformset_factory(UpdateBudget, UpdateBudgetLineItem, form=UpdateBudgetLineItemForm, extra=len(line_item_listofdicts), can_delete=True, can_order=True) The good news is that it works and does what I want it to. However it's super slow. It takes about 13 seconds to render the data back to my app. Not optimal. I've spent the morning trying to do various prefetches and select_relateds but nothing has worked to improve the time it takes to render these fields back to the screen. The fields in question are largely DecimalFields and I've read that they can be a bit slower. I'm trying to use this data as "input" to my formsets in a CreateView. Again it works...but it's slow. Any ideas on how to make this approach more performant? Thanks in advance for any thoughts. -
Choose a specific manager for a related field for a model
I am in a situation where I need to use a custom manager for a related field which is different from the base_manager for the related fields. Let's say that I have a model Item which is in one to many relation with another model Purchase. Now, Item has 2 managers: objects = ItemManager() #which by default excludes the out_of_stock=True items complete = CompleteItemManager() #which gives all the items. For all the other models related to Item, ItemManager is the default one. But in Purchase, I would want to use the CompleteItemManager for the related Item. So let's say there was once a purchase for an item which is now has out_of_stock=True and we just have the id of that purchase say old_purchase_id, now if try to run the below query: purchase = Purchase.objects.filter(id=old_purchase_id) # gives error It would give an error like "Item matching query does not exist" as the manager being used for the related items is ItemManager which excludes such out of stock items. What can be done in that case? Ideally I would want something to override the manager to be used for a given related field per model, so that even if all other models … -
I'm trying to set-up Wagtail on Cloud Run
I'm trying to set-up wagtail and using the Wagtail on Cloud Run guide on https://codelabs.developers.google.com/codelabs/cloud-run-wagtail#5. I'm on step 6 and here's the errors I'm facing after executing the migrate.yaml command ''' tep #1 - "migrate": Traceback (most recent call last): Step #1 - "migrate": File "/workspace/manage.py", line 10, in Step #1 - "migrate": execute_from_command_line(sys.argv) Step #1 - "migrate": File "/layers/google.python.pip/pip/lib/python3.9/site-packages/django/core/management/init.py", line 419, in execute_from_command_line Step #1 - "migrate": utility.execute() Step #1 - "migrate": File "/layers/google.python.pip/pip/lib/python3.9/site-packages/django/core/management/init.py", line 413, in execute Step #1 - "migrate": self.fetch_co ''' -
Redirect to another view django
I want to redirect to anothe view if validate_token method return false but when i do like the code below it does not redierct me to the other app context it just return a html page without django templating def home_view(request, *args, **kwargs): if 'token' in request.session: if model.validate_token(): return render(request, "home.html", {}) else: return render(request, "login.html", {}) else: return render(request, "login.html", {}) -
GeoDjango heroku 'DatabaseOperations' object has no attribute 'spatial_aggregate_name'
I'm trying to deploy my app on Heroku, which works locally but is throwing this error when deployed on heroku: AttributeError : 'DatabaseOperations' object has no attribute 'spatial_aggregate_name' For context I the api call that is triggering the error is trying to return all addresses from a table that are in a certain boundary. my DATABASE settings in settings.py: INSTALLED_APPS = [ 'map.apps.MapConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.postgres', 'rest_framework', 'django.contrib.gis', 'coreapi', 'listings', 'drf_yasg', ] DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'neighborhoods', 'USER': 'django', 'PASSWORD': db_pass, 'HOST':'bonfiredb.cyuiw6tqzaag.us-west-1.rds.amazonaws.com', 'PORT':'5432' } } # Heroku: Update database configurations from $DATABASE_URL. import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) # Activate Django-Heroku. django_heroku.settings(locals(), staticfiles=False) I'm using the heroku goe buildpack. I just can't seem to figure out why it is working locally but not on heroku. Here is my traceback: > Django Version: 4.0.2 Python Version: 3.9.4 Installed Applications: > ['map.apps.MapConfig', 'django.contrib.admin', > 'django.contrib.auth', 'django.contrib.contenttypes', > 'django.contrib.sessions', 'django.contrib.messages', > 'django.contrib.staticfiles', 'django.contrib.postgres', > 'rest_framework', 'django.contrib.gis', 'coreapi', 'listings', > 'drf_yasg'] Installed Middleware: > ['django.middleware.security.SecurityMiddleware', > 'whitenoise.middleware.WhiteNoiseMiddleware', > 'django.contrib.sessions.middleware.SessionMiddleware', > 'django.middleware.common.CommonMiddleware', > 'django.middleware.csrf.CsrfViewMiddleware', > 'django.contrib.auth.middleware.AuthenticationMiddleware', > 'django.contrib.messages.middleware.MessageMiddleware', > 'django.middleware.clickjacking.XFrameOptionsMiddleware'] > > > > Traceback (most recent call last): File > "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", > line 47, in inner … -
Django Celery apply_async doesn't exexute all queries
I have used celery apply_async (also tried delay) with django. The task executes only 3 out of 10 queries where I am performing an update operation on mongo db database. -
How to debug Django tests in vscode
I've been searching a lot for this, no answer. Using StackOverFlow a long time, but this is my first question. How to debug tests with Django, using TestCase and no other frameworks ? I got configurations for debugging django test , but it doesn't even hit the breakpoints.configs Started to question is it even possible ? p.s. Searching for answer for two days. If there is an answer I haven't found, sorry for spam. -
Django filter OrderingFilter default choice
I have created an ordering filter with django filters and I have been wondering how I can set the default choice and remove the empty choice. class MyFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains') o = django_filters.OrderingFilter( choices=( ("created", _("Created, old to new")), ("-created", _("Created, new to old")) ), fields = ( "created", "created" ) ) When I render the filter form the empty choice "----" is being shown as default. I would like to set one the of filtering choices as default and remove the empty choice. -
Pafy Youtube Error 403 when converting video
I'm getting this error when converting a video using pafy GdataError at / Youtube Error 403: The request cannot be completed because you have exceeded your <a href="/youtube/v3/getting-started#quota">quota</a>. This is my code (views.py): def download_video(request): global context form = DownloadForm(request.POST or None) if form.is_valid(): video_url = form.cleaned_data.get("url") if 'm.' in video_url: video_url = video_url.replace(u'm.', u'') elif 'youtu.be' in video_url: video_id = video_url.split('/')[-1] video_url = 'https://www.youtube.com/watch?v=' + video_id if len(video_url.split("=")[-1]) != 11: return HttpResponse('Enter correct url.') video = pafy.new(video_url) stream = video.streams video_audio_streams = [] for s in stream: video_audio_streams.append({ 'resolution': s.resolution, 'extension': s.extension, 'file_size': filesizeformat(s.get_filesize()), 'video_url': s.url + "&title=" + video.title }) stream_video = video.videostreams video_streams = [] for s in stream_video: video_streams.append({ 'resolution': s.resolution, 'extension': s.extension, 'file_size': filesizeformat(s.get_filesize()), 'video_url': s.url + "&title=" + video.title }) stream_audio = video.audiostreams audio_streams = [] for s in stream_audio: audio_streams.append({ 'resolution': s.resolution, 'extension': s.extension, 'file_size': filesizeformat(s.get_filesize()), 'video_url': s.url + "&title=" + video.title }) context = { 'form': form, 'title': video.title, 'streams': video_audio_streams, 'description': video.description, 'likes': video.likes, 'thumb': video.bigthumbhd, 'duration': video.duration, 'views': video.viewcount, 'stream_video': video_streams, 'stream_audio': audio_streams } return render(request, 'home.html', context) return render(request, 'home.html', { 'form': form }) Maybe the error is triggered from another file and I have to change something in … -
Arbitrary Relationship to Another Django Model's Fields?
I'm trying to build a notification system that can trigger based on a user-defined threshold in any field in another model. Ideally this would be something like a ForeignKey relationship, except it saves the external model's field name rather than its instance. My idea is to make a model for storing the notification preference, but I don't know how to save the user's choice of the other field's model: class Report(models.model): a = models.FloatField() b = models.FloatField() c = models.FloatField() class Notification(models.model): report = models.ForeignKey(Report) threshold = models.FloatField() threshold_field = ??? # this has to be a relationship to any field available in Report model I know you can do ForeignKey relationships to pre-defined field with the to_field argument, but this option has to be any field in Report. My idea is to just save threshold_field as a CharField and then use Python's getattr function when retrieving the Report data, but this isn't clean and could break if the field names in Report were to change. There might be an option to override the save method, but I haven't found a way for that to work. -
URLs not matching when admin page set to root url in django app
I building a Django app with drf, the API urls not match correctly when I set admin site at root URL urlpatterns = [ path('', admin.site.urls), path('api/auth/', include("account.urls")), path('api/main/', include("main.urls")), ] when I hit the main API URLs it returns the admin login page, can't fix this yet please help me out. -
update field with number of row in another table django
I'm building a web crawler contain links blogs etc ... , I have field called number_of_crawled_Links and I want to make the value of that filed is the number of rows in another model Where Links Stored any idea how to do that -
Django: Display inline through direct relation
I have models: class CustomUser(AbstractUser): employee_number = models.CharField(max_length=255, blank=True, db_index=True) position = models.ForeignKey( 'orgunits.Position', on_delete=models.CASCADE, related_name='employees' ) class Position(models.Model): orgunit = models.ForeignKey( OrgUnit, on_delete=models.CASCADE, verbose_name=_('orgunit'), related_name='positions', ) name = models.CharField(_('name'), max_length=255) class OrgUnit(models.Model): name = models.CharField(_('name'), max_length=255) type = models.CharField(_('type'), max_length=55) address = models.TextField(_('address'), null=True, blank=True) I would like to display all CustomUser instances assigned to OrgUnit: class OrgUnitEmployeesInline(admin.TabularInline): model = CustomUser class OrgUnitAdmin(admin.ModelAdmin): model = OrgUnit inlines = OrgUnitEmployeesInline, But of course there is an error: <class 'orgunits.admin.OrgUnitEmployeesInline'>: (admin.E202) 'authentication.CustomUser' has no ForeignKey to 'orgunits.OrgUnit'. because Position has ForeignKey to 'orgunits.OrgUnit'. Also I tried this: class OrgUnitEmployeesInline(admin.TabularInline): model = CustomUser fk_name = 'position' but error: <class 'orgunits.admin.OrgUnitEmployeesInline'>: (admin.E202) fk_name 'position' is not a ForeignKey to 'orgunits.OrgUnit'. How can I display users in orgunits inline? -
How to Use --noreload in Django app with gunicorn on remoter server ( ubuntu VM )
What is the equivalent of Python3 manage.py runserver --noreload on remote Virtual machine with gunicorn,django and nginx. The problem is that i'm calling a function to download data using Apscheduler and if i run --norelaod command on local the files are downloaded perfectly, but on cloud i'm using gunicorn and the function is called twice or thrice hence a lot of extra files, so how do i use something like --noreload on gunicorn? -
Whenever i try this, i get a None
username = request.POST['username'] pwd = request.POST['pwd'] User = authenticate(username='jjmster301', password='123') if User is not None: login(request, User) return redirect('/') else: if users.objects.filter(username = username, password = pwd).exists(): messages.info(request, f"Responses >>> {User}") #messages.info(request, f"Response >>> {users.objects.all()}") return redirect('login') -
Django - automatically create User on Athlete create (tied together with a OneToOneField)
I have a model called Athlete that has a OneToOne relation to the User model which is an AbstractUser, I'm trying to create a user whenever I create an Athlete and automatically tie them together but I'm getting an error: Manager isn't available; 'auth.User' has been swapped for 'users.User' Here's my User Model: class User(AbstractUser): is_athlete = models.BooleanField(default=False) is_coach = models.BooleanField(default=False) is_owner = models.BooleanField(default=False) def save(self, *args, **kwargs): self.is_athlete = Athlete.objects.filter(user=self).exists() self.is_coach = Coach.objects.filter(user=self).exists() self.is_owner = Organization.objects.filter(owner=self).exists() super().save(*args, **kwargs) and the Athlete Models (so far): class Athlete(models.Model): user = models.OneToOneField(User, blank=True, null=True, on_delete=models.SET_NULL) coach = models.ForeignKey(Coach, blank=True, null=True, on_delete=models.SET_NULL, related_name='coach') def save(self, *args, **kwargs): try: User.objects.get(email=kwargs.get('email')) print('User with this mail already exists') except User.DoesNotExist: print('User with this mail does not exist') new_user = AuthUser.objects.create_user(email=email) self.user = new_user new_user.save() super().save(*args, **kwargs) -
Python paho MQTT stop execution if not connect
In my python project i use pahoMQTT for connect and pub/subscribe from an MQTT broket. I initialize my procedure like this: def run_sync_client(): #MQTT # Instantiate and check connection about MQTT instance client1 = mqtt.Client(getMacAddr()) client1.on_connect = on_connect # attach function to callback client1.message_callback_add(mqtt_sub_pol, on_message_poll) client1.on_message = on_message # attach function to callback client1.on_publish = on_publish # attach function to callback client1.on_subscribe =on_subscribe # attach function to callback client1.tls_set(mqtt_ca_crt, mqtt_cli_crt, mqtt_cli_key) client1.tls_insecure_set(True) time.sleep(1) try: client1.connected_flag = False client1.connect(mqtt_server, mqtt_port) # connect to broker except Exception: logging.error("Cannot connect MQTT Client1") # END MQTT ... # Rest of code my callback on_connect method is: def on_connect(client1, userdata, flags, rc): client1.connected_flag = True So my problem is when something whent wong in client1.connect() procedure because Exception is raised and the program execution stops, as the system remain in waiting for the connection. My question is, how can i stop the connection trying after a while anc continue with the rest of the code execution? So many thanks in advance -
Django model_to_dict but for a Queryset
I want to be able to essentially do what the dumpdata command does, but instead of showing up in a Django fixture format like with the "models" and "pk" fields, it shows up purely like the data in an instance put through the model_to_dict function. Is there a neat way to use this efficiently on a Queryset? Or does it have to be like this? import json from django.forms.models import model_to_dict from app.models import MyModel data = [model_to_dict(instance) for instance in MyModel.objects.all] json.dumps(data) -
django values_list() and image reverse foreign key
I have a problem with the images, they are not displayed in the template, can someone help me with some solution class Product(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) myshop = models.ForeignKey(MyShop, on_delete=models.CASCADE, related_name="shop_product") title = models.CharField(max_length=255) description = models.TextField(blank=True) class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product_image") image = models.ImageField(upload_to='products/images', validators=[validate_image_file_extension, validate_file_size, FileExtensionValidator(['JPEG', 'JPG', 'PNG'])]) {% for product in products %} {% for image in product.product_image.all %} {% if image.is_feature %} <img src="{{ image.image.url }}" alt="" width="80" height="80"> {% endif %} {% endfor %} {% endfor %} products = Product.prod_obj.select_related( 'myshop' ).filter(id__in=product_ids).values_list('myshop', 'title', 'description', 'product_image', named=True)