Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display custom errors in the template
I have function with custom errors, how to display these errors in the template def auth_join(request, room, slug): if request.method == 'POST': user = request.user.username form_auth = AuthRoomForm(request.POST) if form_auth.is_valid(): room_pass = form_auth.cleaned_data.get('room_pass') password2 = form_auth.cleaned_data.get('password2') if room_pass != password2: messages.error(request, 'Doesn\'t match') return HttpResponse('error') else: # messages.success(request, 'match') user = CustomUser.objects.get(username=user) room = get_object_or_404(Room, slug=slug) if user.has_perm('pass_perm', room): return HttpResponseRedirect(Room.get_absolute_url(room)) else: return HttpResponse('You don\'t have access to this page') else: form_auth = AuthRoomForm() return render(request,'rooms/auth_join.html', {'form_auth':form_auth}) I mean maybe try to do something like that,what i should use istead HttpResponse and how to implement in the template {% if form_auth.errors %} {% for field in form_auth %} {% for error in field.errors %} <div class="ui red message"> {{error}} </div> {% endfor %} {% endfor %} {% endif %} -
How to avoid storing in the database if an error occurs in the next iteration step
Input data is a list of dictionaries. The list can consist of several hundreds of dictionaries and looks like this. data = { "vendor_name": "Ullamcorper Duis LLP", "country": "Belgium", "nda": "", "modules": [ { "module": "" } ], "contacts": [ { "email": "jack@gmail.com", "contact_name": "Jack Jhonson", "primary": true }, { "email": "jack2@gmail.com", "contact_name": "Jack Jhonson", "primary": false } ] }, { "vendor_name": "Habitant Associates", "country": "Turkey", "nda": "", "modules": [ { "module": "" } ], "contacts": [ { "email": "eget.metus.eu@elitdictum.edu", "contact_name": "Trevor Smith", "primary": true }, { "email": "at.risus.Nunc@iaculis.ca", "contact_name": "Madonna Z. Kemp", "primary": false } ] }, .... .... ] Since some fields (for example, vendor_name) must be unique and if n-element and n+1 item are equal, the error "Vendor already exists" appears. And this is correct, of course. It so happens that some information is written into the database before the error occurs. But I need the writing to be done on the all or nothing principle. views.py class CsvToDatabase(APIView): serializer_class = VendorsCsvSerializer def post(self, request, format=None): r_data = request.data for data in r_data: if data['nda'] == '': data['nda'] = None for contact in data['contacts']: if contact['email']: contact['email'] = contact['email'].lower() for module in data['modules']: if module['module']: module['module'] = … -
Render HTML for REST API JSON data
What tools/solutions available for rendering html after REST API call returns JSON data? I have a Django webapp, where I built a set of REST API common for processing all data through the UI/browser or mobile app. The API will only return JSON, no HTML. I want to be able to draw tables, and do other HTML things on the browser-based on the data returned by the API, I cannot retrieve, or be loading html before the API calls. Do handlebars etc work in this situation? What are other effective options? -
Get most recent related objects for all objects
Suppose I have the following model: from django import models class Post(models.Model): user = models.ForeignKey(to=User, on_delete=CASCADE) created = models.DatetimeField(auto_now_add=True) I want to get some information about the most recent post (e.g. likes) from a group of users posts = User.objects.filter(**params).annotate(most_recent_post=Max('post__created')).annotate(likes=Count('post__likes', filter=Q(post__created=F('most_recent_post')) When I try to make this query, I get the following error: OperationalError: misuse of aggregation function MAX() -
Get items by date by clicking day field Javascript Django
I'm developing calendar app with Javascript and Django . I don't now how to display item by date by clicking the day . Is there any solutions ? I have a guess that I need to get elements by ajax on clicking the date . Here is some code : models.py class Item(models.Model): title=models.CharField(max_length=200) date = models.DateTimeField(default=datetime.now,blank=True) is_published=models.BooleanField(default=True) views.py def calendar(request): item = Item.objects.order_by('-date').filter(is_published=True) context={ 'item':item, } return render(request,'main/calendar.html',context) Javascript calendar draw methods drawAll() { this.drawWeekDays(); this.drawMonths(); this.drawDays(); this.drawYearAndCurrentDay(); this.drawEvents(); } Here is constructor of class Calendar drawYearAndCurrentDay() { let calendar = this.getCalendar(); this.elements.year.innerHTML = calendar.active.year; this.elements.currentDay.innerHTML = calendar.active.day; this.elements.currentWeekDay.innerHTML = AVAILABLE_WEEK_DAYS[calendar.active.week]; } drawDays() { let calendar = this.getCalendar(); let latestDaysInPrevMonth = this.range(calendar.active.startWeek).map((day, idx) => { return { dayNumber: this.countOfDaysInMonth(calendar.pMonth) - idx, month: new Date(calendar.pMonth).getMonth(), year: new Date(calendar.pMonth).getFullYear(), currentMonth: false } }).reverse(); let daysInActiveMonth = this.range(calendar.active.days).map((day, idx) => { let dayNumber = idx + 1; let today = new Date(); return { dayNumber, today: today.getDate() === dayNumber && today.getFullYear() === calendar.active.year && today.getMonth() === calendar.active.month, month: calendar.active.month, year: calendar.active.year, selected: calendar.active.day === dayNumber, currentMonth: true } }); constructor(options) { this.options = options; this.elements = { days: this.getFirstElementInsideIdByClassName('calendar-days'), week: this.getFirstElementInsideIdByClassName('calendar-week'), month: this.getFirstElementInsideIdByClassName('calendar-month'), year: this.getFirstElementInsideIdByClassName('calendar-current-year'), currentDay: this.getFirstElementInsideIdByClassName('display_day'), currentWeekDay: this.getFirstElementInsideIdByClassName('calendar-left-side-day-of-week'), prevYear: this.getFirstElementInsideIdByClassName('calendar-change-year-slider-prev'), nextYear: … -
Irregular behaviour of celery
I am very new to Celery and I am trying to use it to schedule a function, but its not working properly it seems. Here is my settings.py: (Along with the default settings given by django) CELERY_BROKER_URL = 'amqp://guest:guest@localhost' CELERY_ACCEPT_CONTENT = ['json'] CELERY_RESULT_BACKEND = 'db+sqlite:///results.sqlite' CELERY_TASK_SERIALIZER = 'json' celery.py: rom __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mera_project.settings') app = Celery('mera_project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() init.py: from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app'] tasks_notes/tasks.py:(tasks_notes is my app name) from celery.decorators import periodic_task from celery.task.schedules import crontab from tasks_notes.models import BudgetInfo @periodic_task(run_every=(crontab(minute='*/15'))) def monthly_starting_value(): print("hi") return 0 views.py: from .tasks import monthly_starting_value def app_view(request): abcd = monthly_starting_value.delay() print("new"+str(abcd)) I had expected value zero and hi in my terminal, but instead of that I have got a random number as new 42bf83ef-850f-4b34-af78-da696d2ee0f2 and the random number keeps on changing in every 15 minutes. In my ``celery beat``` running terminal tab, I am getting something like: WARNING/ForkPoolWorker-9] hi Task tasks_notes.tasks.monthly_starting_value[42bf83ef-850f-4b34-af78-da696d2ee0f2] succeeded in 0.0009442089994990965s: 0 in every 15 minutes. I have even tried ``app.beat.conf_scheduleincelery.py``` and also tried running in admin phase, but its not working as expected. Where can I … -
How do I parse through this json data in a more efficient way with Python?
How do I parse through this json data in a more efficient way. I'd like to do it with a for loop so the code doesn't repeat itself. Here's the data endpoint: https://api.coingecko.com/api/v3/exchange_rates and the json response sample: { "rates": { "btc": { "name": "Bitcoin", "unit": "BTC", "value": 1, "type": "crypto" }, "eth": { "name": "Ether", "unit": "ETH", "value": 48.316, "type": "crypto" }, "ltc": { "name": "Litecoin", "unit": "LTC", "value": 169.967, "type": "crypto" } my view.py code: def btc_to_currency(request): exchange_endpoint = "https://api.coingecko.com/api/v3/exchange_rates" request_exchange_data = requests.get(exchange_endpoint) results_exchange_data = request_exchange_data.json() data_exchange = results_exchange_data["rates"] #print(data_exchange) btc = (data_exchange['btc']) xrp = (data_exchange['xrp']) xau = (data_exchange['xau']) xag = (data_exchange['xag']) return render(request, 'crypto/btc_to_currency.html', {'btc' : btc, 'xrp': xrp, 'xau': xau, 'xag': xag}) and my template html code: <table class="table is-bordered is-striped is-narrow is-hoverable is-fullwidth"> <thead> <tr> <th rowspan="2" class="is-size-7 has-text-centered">Name</th> <th rowspan="2" class="is-size-7 has-text-centered">Unit</th> <th rowspan="2" class="is-size-7 has-text-centered">Value</th> <th rowspan="2" class="is-size-7 has-text-centered">Type</th> </tr> </thead> {% load humanize %} <tbody> <tr> <th class="is-size-7 has-text-centered"><strong>{{ btc.name }}</strong></th> <td class="has-text-centered">{{ btc.unit }}</td> <td class="has-text-centered">{{ btc.value }}</td> <td class="has-text-centered">{{ btc.type }}</td> </tr> <tr> <th class="is-size-7 has-text-centered"><strong>{{ xrp.name }}</strong></th> <td class="has-text-centered">{{ xrp.unit }}</td> <td class="has-text-centered">{{ xrp.value|intcomma }}</td> <td class="has-text-centered">{{ xrp.type }}</td> </tr> <tr> <th class="is-size-7 has-text-centered"><strong>{{ xau.name }}</strong></th> <td class="has-text-centered">{{ xau.unit … -
save function in form and if status change a date should be created and then check or compare the status if true save the status to database
models.py class Item(models.Model): status_choices = [('Requested', 'Requested'), ('Processing', 'Processing'), ('Completed', 'Completed')] status = models.CharField(choices=status_choices, max_length=50, null=True, blank=True, ) completed_date = models.DateTimeField(blank=True, null=True) requested_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) froms.py class ItemForm(forms.ModelForm): class Meta: model = Item fields = ['status', created_at, requested at] def __init__(self, *args, **kwargs): super(ItemForm, self).__init__(*args, **kwargs) self.fields['status'].initial = 'Requested' def save(): pass i want to override my form and at the time of instance if i change the form value to completed. i want the date in my model filled with today's date in the field 'completed_at' and save it to database also can anyone help me? -
Strange non-breaking space when copying text from website in Chrome
I am developing a website in Django. It is a movie database. For creating a movie reference, I am using a join function like this: ''.join(i for i in movies) As a result, I get the following references for movies: Titanic. Directed by <i>James Cameron</i>. 1997. Everything is perfect on the backend side. On the frontend side, everything is visually OK, but when I copy the string with the movie reference and paste it into Microsoft Word, a non-breaking space appears before the italicized item instead of the regular space (I've tried italicizing other items as well, and it appeared everywhere before them): Titanic. Directed by°James Cameron. 1997. I do not add any non-breaking spaces, and I've tested out the backend side, no nbsp's appear there. Moreover, when I inspect the page in Chrome... it shows no non-breaking spaces: Titanic. Directed by <i>James Cameron</i>. 1997. How come that it appears on copying? And how can I avoid this behavior? P.S. I've tried this out on the book referencing site https://www.citethisforme.com/, and it's all the same. When adding a journal, this non-expected nbsp appears right before the italicized journal title element. -
Django create data with OnetoOneField
Hello thanks for your time: i'm trying to add some data to my model table trough management/commands/create_data.py: 1º Question in other project of mine i can call python manage.py create_data create_data.py although in this one is not working. How do i call the right command? 2º Question besides that i guess i'm gonna recieve an error at user field on People model because should be an id. How do i get the id? pets/models.py: User = get_user_model() class People(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='person') birthday = models.DateField() cpf = models.CharField(max_length=11, validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return '%s' % (self.user) pets/management/commands/create_data.py: User = get_user_model() class GenerateUser(): username = None password = None def __init__(self, username, password): with open('User.txt') as file: for rows in file: self.username = slugify(rows) self.password = '12345' class GeneratePeople(): user = None documento = None birthday = None def __init__(self, documento, birthday): with open('People.txt') as file: for rows in file: t1 = rows.split(', ') self.user = slugify(t1[0]) self.documento = t1[1] self.birthday = t1[2] class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( 'file_name', type=str, help='ok') def handle(self, *args, **kwargs): username = GenerateUser.username password = GenerateUser.password user = GeneratePeople.user documento = GeneratePeople.documento birthday = GeneratePeople.birthday one = User( username=username, password=password ) one.save() peop = … -
Django m2m_changed signal for GenericRelation, is it possible?
Can it be used for a generic relation? I don't see it mentioned in the docs. A naive try of getting the through table: In [4]: Asset.related_images.through --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-4-d541db71a7a5> in <module>() ----> 1 Asset.related_images.through AttributeError: 'ReverseGenericManyToOneDescriptor' object has no attribute 'through' -
django check query return value or not
I need to get the destinationId value as query result from database, it works fine when there is matching value in database.If no match is there it results in error "matching query does not exist.".How can i solve this issue, also i need to run another query based ob=n the result,how can i check value exist or not? Am new to django and python, please help def get_route_list(request): if request.method == "POST": #Get the posted form areaDigit = request.POST['areaDigit'] productId = request.POST['productId'] destination_id=Routing_Dest_Area.objects.get(areaDigit=areaDigit).destinationId else: data = '' print(data) return render(request, 'routing/test.html',{'data':destination_id}) -
Implement serach in a corpus of document with Haystack an Whoosh
Hy, I am looking to add a search in some text (convert from pdf) to my app. I choice to use Whoosh. For the moment I have created an index of the documents with a Schema, create_in and add_document from Whoosh The index seems correct, I can read it with open_dir and reader from Whooosh. The link with my Django models is the name of the file in the Schema which contains an id, I am not sure it is the good way to link index with models ... Now I try to add a frontend form to allow user to search the index with a simple form CharFiled Google like and retrieve the original pdf document and I don't find the way to do this, the docs I found explain mainly how to search in models fields and not in an indexed corpus. Thanks for your time. -
Heroku cannot read '/etc/secret_key.txt', No such file or directory:
I successfully deployed a django app to heroku with my settings.py as such: SECRET_KEY = 'the_real_long_secret_key_itself', which of course is not recommended, but that was find for me just in this scenario as it is just a test and can be changed. Now back to my local environment, I decided to hide the key without changing it yet and according to django documents like this: # on settings.py with open('/etc/secret_key.txt') as s: SECRET_KEY = s.read().strip() And it works when I run server locally. But now when I try to commit & push like this: (herokuvirtualenv)tester1@test:~/$ git add -A (herokuvirtualenv)tester1@test:~/$ git commit -m "some editing" (herokuvirtualenv)tester1@test:~/$ git push heroku master It runs but ends up with this error message: remote: with open('/etc/secret_key.txt') as s: remote: FileNotFoundError: [Errno 2] No such file or directory: '/etc/secret_key.txt I have used search engines and there seems to be many ways to do this and it point that this should work, but there seems to be something I am omitting here. Could someone please help out? -
Django change choice before validation
I am trying to update a choice field before it is validated in Django. The reason for this is the choice field in question value is the Id of a model that i want to update. def fuelLogSystemOne(request): entries = FuelLogSystemOneMod.objects.all().order_by('date') products = productsMod.objects.all() if request.method == 'POST': form = forms.AddFuelLogOneForm(request.POST, request.FILES) productid = form['product'].value() product = productsMod.objects.get(id=productid) product_id = request.POST.get('product') form.fields['product'].choices = [(product.product_type, product.product_type)] if form.is_valid(): bucketsRemoved = form['buckets_added'].value() product.stock -= bucketsRemoved product.save(['stock']) instance = form.save(commit=False) instance.staff = request.user instance.save() return redirect('home') else: form = forms.AddFuelLogOneForm() return render(request,'systems/fuellogsystemone.html',{'form':form,'entry':entries,'products':products}) The below part is where i am trying to change the form data before it gets validated so it doesn't say 'Select a valid choice. 1 is not one of the available choices' product_id = request.POST.get('product') form.fields['product'].choices = [(product.product_type, product.product_type)] But when I first submit the form it is still saying 'Select a valid choice.' At what point does Django validate the form because I am changing the form before the is_valid() method and it still hits this error? -
Django REST Framework - cookies not being set via Response.set_cookie() call...?
I have the following standard Response setup in my DRF application: response = Response(data=response, status=status.HTTP_200_OK) I'm then attempting to add a split JWT header.payload and signature to the response headers with a response.set_cookie() call, as follows: max_age = 365 * 24 * 60 * 60 expires = datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age) response.set_cookie( key='JWT_ACCESS_HEADER_PAYLOAD', value=header_payload, httponly=False, expires=expires.strftime("%a, %d-%b-%Y %H:%M:%S UTC"), max_age=max_age ) response.set_cookie( key='JWT_ACCESS_SIGNATURE', value=signature, httponly=True, expires=expires.strftime("%a, %d-%b-%Y %H:%M:%S UTC"), max_age=max_age ) return response I can't see anything wrong with what I have done thus far: Yet, for some reason, the only cookies set on the client side are as follows: What have I done wrong here?? The actual output in the headers seem to be a valid SetCookie value: JWT_ACCESS_HEADER_PAYLOAD=aSasas; expires=Sat, 03-Apr-2021 10:24:31 GMT; Max-Age=31536000; Path=/ JWT_ACCESS_SIGNATURE=asaSasaS; expires=Sat, 03-Apr-2021 10:24:31 GMT; HttpOnly; Max-Age=31536000; Path=/ -
Manage models inheritance in Django admin
I'm developing with my team a Django webapp which provides authentication and users profile creation. Basically, we are dealing with a model Profile which extends django.auth.contrib.models.User implementing One-to-One link method, as shown below model.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateField(default=datetime.date.today) # other custom fields def __str__(self): return self.user.username Since we have registered the model in admin.py, it appears in Django admin panel, as it should be. Then, we have introduced another model PersonalTrainer which is an intherited class of Profile one. admin.py from django.contrib import admin from usermanager.models import Profile, PersonalTrainer admin.site.register(Profile) admin.site.register(PersonalTrainer) Is there any programmatically method to organize PersonalTrainer instances in a such a way they appear both in Profile section and PersonalTrainer section? In other words, we'd like to have a PersonalTrainer instance which appears in auth User model, Profile model and PersonalTrainer model. -
Django messages not working in admin model_save()
I have the following save_model in MyModelAdmin, the print statement gives output in console, but on django admin, i can see default messages, but not my error message for some reason. class MyModelAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): try: transfer_money() super(MyModelAdmin, self).save_model(request, obj, form, change) except Exception as e: print(e) messages.add_message(request, messages.INFO, str(e)) -
How can I convert my class-based view to function-based views? - Django
I am trying to change all my class-based views to function-based views and I am having difficulty converting the following class: class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, UpdateView): model = Post fields = ['image', 'title', 'category', status', 'description'] template_name = 'blog/post-form.html' success_message = 'Your post has been updated.' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False def get_context_data(self, **kwargs): context = super(PostUpdateView, self).get_context_data(**kwargs) context['title'] = 'Update post' context['submit'] = 'Update' return context def get_success_url(self): author = self.object.author return reverse_lazy( 'profile', kwargs={'author': author.username}) The function and form should do exactly what this class-based view does, so if anyone can help me out, please let me know. -
Object level authorization in a Django Rest Framework viewset
I'm creating an API with Django Rest Framework (DRF) and wondering where I should handle object level authorization. So far I've created an Organization model and a custom user model with email being the unique identifier instead of username. Organizations and users are currently connected through a many-to-many field. What I'd like to do is make sure that when a user hits my API they're only able to do the standard CRUD actions on the models that are linked to the users respective organization. As an example here's my current UserViewSet where I've overriden then get_queryset method to filter the User queryset to only return other users who are apart of the same organizations as the user calling the API: class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer def get_queryset(self): User = get_user_model() user = self.request.user organizations = user.organization.all() return User.objects.filter(organization__in=organizations) What's considered best practice to extend these limitations to other viewset actions? For example, if I want to make sure that the user can only create and add other users into the organizations they're linked to, should I override the create method in the viewset and perform a validation there that the organization which was passed in the request data is the … -
Why does django gives me 405 error on the first instance
I'm writing this code class ParentCancelView(ProfileTypeRequiredMixin, UpdateView): profile_type = 'parent' model = Books template_name = 'library/student_parent_list_view.html' def post(self, *args, **kwargs): recipient = self.request.user.parent.recipient.first() queryset = self.get_queryset() pk = self.kwargs.get('pk') if pk: queryset.filter( pk=pk, recipient=recipient ).update(reserve_status='cancelled') return super(ParentCancelView, self).post(*args, **kwargs) urls.py url( r'^reserve/parent/(?P<pk>\d+)/$', views.ParentCancelView.as_view(), name='reserve_parent_cancel' ), html <form method="POST" action="{% url 'library:reserve_cancel' pk=book.pk %}"> {% csrf_token %} <button class="btn btn-xs btn-primary" type="submit" {% if book.reserve_status != 'for_approval' %}disabled{% endif %}>Cancel Reservation {{ book.pk }}</button> </form> when Im trying to cancel it works fine on second, third but not on first instance it has no error but it gave me 405, does any one what went wrong here? thanks -
Add extra non-model attribute to serializer
I have following scenario: I have a device model with a "deleted" field. When it's true, the device is deleted. I need a endpoint to change the value of that field. I want to do this in a request by giving the device_id and a deleted_flag. I was able to just change the deleted attribute without passing the deleted_flag attribute. But I'm stuck if I want to give the deleted_flag attribute to the serializer because it's a non model field.. This is my code: test: def test_undelete_device(self): self.client.force_login(self.admin_user) url = reverse( "admin-device-change-status", kwargs={"device_pk": self.device.id}, ) response = self.client.patch(url, data={"deleted_flag": False}) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data["deleted"], False) serializer: class AdminDeviceChangeStatusSerializer(serializers.ModelSerializer): deleted = serializers.BooleanField() deleted_flag = serializers.SerializerMethodField() class Meta: model = Device fields = ["deleted", "deleted_flag"] def validate_deleted(self, deleted): return deleted def validate_deleted_flag(self, deleted_flag): return deleted_flag def get_deleted_flag(self, deleted_flag): return deleted_flag view: def patch(self, request, device_pk): """ Change deleted status device """ device = get_object_or_404(Device, pk=device_pk) serializer_class = AdminDeviceChangeStatusSerializer serializer = serializer_class(device, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() if serializer.validated_data.get("deleted_flag") == False: device.deleted = True else: device.deleted = False device.save() return Response(serializer.data, status=status.HTTP_200_OK) stacktrace: TypeError: Object of type 'Device' is not JSON serializable -
My code is working on codepen but not on my editor
My code is working on codepen but not on my editor (PyCharm). This is part of django project. By not working I mean I get a blank page, with no output (no text). I have tried to read a few answers addressing a similar issue but none of these solutions seem to be working for me/or I am not applying them correctly. Specifically adding the full URL path for getting ScrollWatch through CDN. Here is a sample of my code html { % load script % } <html lang="en"> <head> <meta charset="UTF-8"> <title>The Gradient Boost</title> <link rel="stylesheet" href="{% static 'second/css/app/book.css' %}"> <script src="https://cdn.jsdelivr.net/npm/scrollwatch@2.0.1/dist/ScrollWatch-2.0.1.min.js"></script> </head> <body> <h2><div data-scroll-watch>First Text</div></h2> <h2><div data-scroll-watch>Second Text</div></h2> <h3><div data-scroll-watch>Third Text</div></h3> <script src="{% static 'second/js/app/book.js' %}"></script> </body> </html> css location -> static\second\css\app\book.css .watch-container { font-size: 2em; width: 75%; height: 150px; padding: 20px; margin: 50px auto; background-color: #0681CD; color: #fff; overflow: auto; text-align: center; } div { text-align: center; font-size: 1em; margin: 200px 0; opacity: 0; transition: opacity 1s; font-weight: normal } div.scroll-watch-in-view { opacity: 1; } and javascript location -> static\second\js\app\book.js (function() { var addElements = function() { var txt = document.createTextNode('Testing'); var el; el = document.createElement('div'); el.appendChild(txt); document.body.appendChild(el); // If we want newly injected elements to … -
argument of type 'QuerySet' is not iterable Django error
In my webapp, I have a friends feature, but one of the if statements produces an error Here is my UserProfileInfo model class UserProfileInfo(models.Model): connection = models.ManyToManyField(User,blank=True,related_name='follow_profile') And now here is my view: def friend_actions(request,username=None): current_user = request.user.userprofileinfo user = request.user # username = get("username") username = User.objects.get(username=username) other_user = get_object_or_404(UserProfileInfo,user__username=username) # other_user = UserProfileInfo.objects.get(username=username) url = other_user.get_absolute_url() if other_user in current_user.connection.all(): current_user.connection.remove(other_user) else: current_user.connection.add(other_user) return HttpResponseRedirect(url) However, this produces the following error: argument of type 'QuerySet' is not iterable Full traceback Traceback: File "C:\Users\User\.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\User\.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\User\.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\interests-site\interests-drf\mainapp\views.py" in friend_actions 453. if other_user in current_user.connection.all(): Exception Type: TypeError at /mainapp/profile/donnellan0007/connect/ Exception Value: argument of type 'QuerySet' is not iterable I am wondering how I can stop this error from occurring. I have been stumped by it all day -
Django hosting trouble with django.wsgi
I registered everything as it is written in the instructions for django hosting provider (jino), but errors popped up, which I can't even come close to understanding. [Thu Apr 02 22:32:40 2020] [error] [client 148.64.56.65] mod_wsgi (pid=61341): Failed to exec Python script file '/home/users/m/marselabdullin/domains/caparolcenterspb.ru/django.wsgi'. [Thu Apr 02 22:32:40 2020] [error] [client 148.64.56.65] mod_wsgi (pid=61341): Exception occurred processing WSGI script '/home/users/m/marselabdullin/domains/caparolcenterspb.ru/django.wsgi'. [Thu Apr 02 22:32:40 2020] [error] [client 148.64.56.65] Traceback (most recent call last): [Thu Apr 02 22:32:40 2020] [error] [client 148.64.56.65] File "/home/users/m/marselabdullin/domains/caparolcenterspb.ru/django.wsgi", line 4, in <module> [Thu Apr 02 22:32:40 2020] [error] [client 148.64.56.65] exec(open(activate_this).read(), dict(__file__=activate_this)) [Thu Apr 02 22:32:40 2020] [error] [client 148.64.56.65] FileNotFoundError: [Errno 2] \xd0\x9d\xd0\xb5\xd1\x82 \xd1\x82\xd0\xb0\xd0\xba\xd0\xbe\xd0\xb3\xd0\xbe \xd1\x84\xd0\xb0\xd0\xb9\xd0\xbb\xd0\xb0 \xd0\xb8\xd0\xbb\xd0\xb8 \xd0\xba\xd0\xb0\xd1\x82\xd0\xb0\xd0\xbb\xd0\xbe\xd0\xb3\xd0\xb0: '/home/users/m/marselabdullin/projects/caparol_center_spb_decision/env/bin/activate_this.py' [Thu Apr 02 22:33:16 2020] [error] [client 5.18.99.123] mod_wsgi (pid=37979): Failed to exec Python script file '/home/users/m/marselabdullin/domains/caparolcenterspb.ru/django.wsgi'. [Thu Apr 02 22:33:16 2020] [error] [client 5.18.99.123] mod_wsgi (pid=37979): Exception occurred processing WSGI script '/home/users/m/marselabdullin/domains/caparolcenterspb.ru/django.wsgi'. [Thu Apr 02 22:33:16 2020] [error] [client 5.18.99.123] Traceback (most recent call last): [Thu Apr 02 22:33:16 2020] [error] [client 5.18.99.123] File "/home/users/m/marselabdullin/domains/caparolcenterspb.ru/django.wsgi", line 4, in <module> [Thu Apr 02 22:33:16 2020] [error] [client 5.18.99.123] exec(open(activate_this).read(), dict(__file__=activate_this)) [Thu Apr 02 22:33:16 2020] [error] [client 5.18.99.123] FileNotFoundError: [Errno 2] \xd0\x9d\xd0\xb5\xd1\x82 \xd1\x82\xd0\xb0\xd0\xba\xd0\xbe\xd0\xb3\xd0\xbe \xd1\x84\xd0\xb0\xd0\xb9\xd0\xbb\xd0\xb0 \xd0\xb8\xd0\xbb\xd0\xb8 \xd0\xba\xd0\xb0\xd1\x82\xd0\xb0\xd0\xbb\xd0\xbe\xd0\xb3\xd0\xb0: …