Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-storages S3boto3 upload status
I'm using django-storages to upload several files using a Model with a FileField in Django Rest Framework. Everything works fine, the frontend aplication just waits until the upload finish and the promise is resolved i the fron while in the backend a database registry is save in the database. But when the files are too large or there is network issues, the promise just time out and the upload sometimes is done and sometimes is not, and sometimes it uploads the file without loading the link to the database. Is there any way to generate a progress indicator that shows me the upload status, I could request for the status with my frontend aplication, with a recursive request instead of a Promise that is timed out. Is there is any other sugestion i am open to hear one. -
Heroku versus AWS
I am trying to deploy a personal website (python django based framework) which contains text and few images. Can someone tell if their are any advantages and disadvantages of deploying to heroku versus AWS. PS: I have deployed it on AWS but the images are not loading. So I am considering Heroku but not sure if I should use Heroku or AWS would be more stable. -
How can I print this Django raw SQL query? Preferably to a table
I have been working on a Django app to help us clean up some old Tableau workbooks. It gives users a front end web ui to decide which books to keep and which to delete. I'm going to be handling a lot of this by way of SQL and Django. Here is the SQL query I have written: from django.db import connection username = str("lastname, firstname") def dictfetchall(cursor): # Returns all rows from a cursor as a dict desc = cursor.description return [ dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall() ] def query(): cursor = connection.cursor() cursor.execute("SELECT Owner_Name,Owner_Email,Id,Name FROM tableau_books WHERE Owner_Name = %s", (username,)) results = dictfetchall(cursor) for item in results: print(item) Right now, this function just queries the fields I want and prints them in a legible way. Here is my view where I'm calling it: def dashboard(request): if request.method == 'POST' and 'run_script' in request.POST: # import function to run from main_app.queries import query # call function query() return render(request, 'dashboard.html') Lastly, here is my button I'm using to actually run the code in html: <form method="post"> {% csrf_token %} <button type="submit" name="run_script">Find Workbooks</button> </form> Is there an easy way to, instead of printing … -
How to increase quantity for each multiple items with the same slug url
How does one increases the quantity for each multiple item with the same slug url? When i added two items with the same slug url to cart, then i try to increase the quantity it only increases the first item in cart and not the second item. enter image description here Models.py class Item(models.Model): title = models.CharField(max_length=250) image = models.ImageField(null=True) price = models.IntegerField() old_price = models.IntegerField(null=True, blank=True) description = HTMLField() category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField(max_length=250, unique=True) timestamp = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) class Meta: ordering = ['-timestamp'] db_table = 'items' verbose_name_plural = 'Items' def __str__(self): return self.title class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) variation = models.ManyToManyField(Variation) def __str__(self): return f"{self.quantity} of {self.item.title}" Views.py def update_cart(request, pk, slug): item = get_object_or_404(Item, pk=pk) print(item) if request.method == 'POST': pk = request.POST.get('pk', None) #retrieve id qty = request.POST.get('quantity', None) order_item_qs= OrderItem.objects.filter( item=item, user=request.user, ordered=False ) if order_item_qs.exists(): item = order_item_qs.first() item.quantity = qty item.save() return redirect("shop:order-summary") Urls.py path('update-cart/<int:pk>-<slug:slug>/', update_cart, name='update-cart'), Order-sumarry template: <form method="POST" action="{{ order_item.item.get_update_cart_url }}"> {% csrf_token %} <p> <input type="button" value="-" class="minus"> <input type="number" value="{{ order_item.quantity }}" name="quantity" id="qty1" class="quantity_class" min="1" required> <input type="button" … -
unique_together in a model.Models vs uniquetogethervalidator of serializers
If i have a model A with (field1 and field2 are fields of model) `unique_together = ('field1', 'field2')` in Meta class and a serializer which is a model serializer on model A, then why should I or why should not I use Uniquetogethervalidator in Meta of serializer. Why we need this validator if we already have condition in Model? Or what is difference between using a unique_constraint in model and uniquetogethervalidator in serializer ? -
for loop with an integer in django's templates tags
In my Django template {{review.stars}} is an integer from 1 to 5, but instead of showing a simple number I want to show a number of star icons equal to the {{review.stars}} integer. I should write something like: for n in range(1, review.stars+1): add star icon but obviously I can't write something like that in Django template tags. What's the pythonic way to run a loop a variable number of times? -
Django dynamically add fields without creating new model instances
I'm attempting to create a form that allows someone to enter multiple phone numbers. I'd like to make it possible to click a button to add an additional field to the form but I am not quite sure how to do that. I looked at FormSets but I don't want to create a new model instance every time someone adds a new phone number. Thanks in advance -
django-objects tag filter
I'm calling a post.objects.all object on my html page. on the same page last-post. I made a filter for this but I get an error. calling the last 3 posts I want to do I can't type .objects.order_by () because it's probably an object. views.py : posts=post.objects.all() context = { 'posts': posts, 'category':category, } return render(request, "post/post-list.html", context) html: {%for post in posts|lasted %} filter.py @register.filter def lasted(post): return post.objects.order_by('post_date')[:3] AttributeError at /post/index/ 'Page' object has no attribute 'objects' Request Method: GET Request URL: http://127.0.0.1:8000/post/index/ Django Version: 2.2.7 Exception Type: AttributeError Exception Value: 'Page' object has no attribute 'objects' Exception Location: C:\Users\Barbaros\Desktop\All\env\lib\site-packages\django\template\defaultfilters.py in lasted, line 73 Python Executable: C:\Users\Barbaros\Desktop\All\env\Scripts\python.exe Python Version: 3.7.4 Python Path: ['C:\\Users\\Barbaros\\Desktop\\All', 'C:\\Users\\Barbaros\\Desktop\\All\\env\\Scripts\\python37.zip', 'C:\\Users\\Barbaros\\Desktop\\All\\env\\DLLs', 'C:\\Users\\Barbaros\\Desktop\\All\\env\\lib', 'C:\\Users\\Barbaros\\Desktop\\All\\env\\Scripts', 'c:\\users\\barbaros\\appdata\\local\\programs\\python\\python37-32\\Lib', 'c:\\users\\barbaros\\appdata\\local\\programs\\python\\python37-32\\DLLs', 'C:\\Users\\Barbaros\\Desktop\\All\\env', 'C:\\Users\\Barbaros\\Desktop\\All\\env\\lib\\site-packages'] Server time: Fri, 22 Nov 2019 20:36:41 +0000 -
Find users of security group with django-python3-ldap
Very new to LDAP and AD. I'm using django-python3-ldap to authenticate users of my django app. We want to make it so that only a subset of our users can access our django app, so yesterday they added the security group 'MyAppGroup.' Only problem is, I don't seem able to add this to the search base. User lookup always fails. Working search base (returns ALL users): "ou=Basic Users, ou=BIGAPP Users,dc=subd,dc=domain,dc=com" When I asked, they said that MyAppGroup was a security group, and that "Basic Users" and "BIGAPP Users" were "AD Members." dsquery group -name "MyAppGroup" returns: CN=MyAppGroup,OU=BIGAPP Groups,dc=subd,dc=domain,dc=com This result does not work as the search base. Do I need to add a custom search filter for this to work? Any help is appreciated. -
Django - how to dynamicaly create models in tests? (Django 2.x)
I would like to test my custom subclassed Django model field. I could use existing models from my project but they are quite complicated and hard to setup. I have found two SO question but the are quite old (2009 and 2012). #1 #2 So I wanted to ask if anyone knows a better way to achieve this. Django wiki has a dedicated page for custom fields, but there I haven't found anything about testing there. Thanks for any tip or suggestion. -
Empty Serialised Response in Django Rest Framework
I have a model, a view and a serializer which produce the following response representing a medical test: { "name": "electrocardiogram", "cost": "180.00", "results": [ { "id": "bff25813-5846-4eac-812f-7e57d8fbb496", "lots more things" : "were here, but I hid them for brevity's sake" "video": [] } ] } As you can see, it is a nested object which is put together by some nested DRF serializers. This is great, but I want to put a couple of custom database calls into my view logic as I want to keep track of which tests a user runs. To do this I have written. class RunTestView(generics.RetrieveAPIView): serializer_class = TestSerializer def get_object(self): if 'test' not in self.request.query_params: return Response({'Error': 'test not in request'}, status=status.HTTP_400_BAD_REQUEST) test = get_object_or_404(Test, id=self.request.query_params['test']) return test def get(self, request, *args, **kwargs): if 'case_attempt' not in request.query_params: return Response({'Error': 'case_attempt not in request'}, status=status.HTTP_400_BAD_REQUEST) case_attempt = get_object_or_404(CaseAttempt, id=request.query_params['case_attempt']) # get the test object which we will later serialise and return test = self.get_object() # if we've gotten this far, both case_attempt and test are valid objects # let's record this in the TestsRunTracking model if it is not already there if not TestsRunTracking.objects.all().filter(case_attempt=case_attempt, test=test, user=request.user).exists(): tracking = TestsRunTracking(case_attempt=case_attempt, test=test, user=request.user) tracking.save() # … -
How to edit object in forms if the form has __init__ method?
I have a form that have choice field and must be filtered by request.user and for this I use the init method. When it is initialized, the data is ready to be selected which is good but when I want to edit that object, it doesn't show the data stored in selected choice instead shows an empty select field. Is important that in both cases (create and edit) that object in choice field to be filtered by request.user. How can I edit the object if the form uses a init method? class EditarePereche(forms.ModelForm): boxa = forms.IntegerField(label="Boxa", min_value=1) sezon = forms.CharField(label="Sezon reproducere", initial=datetime.now().year) mascul = forms.ModelChoiceField(queryset=None, label="Mascul", empty_label="Alege mascul") femela = forms.ModelChoiceField(queryset=None, label="Femela", empty_label="Alege femela") serie_pui_1 = forms.TextInput() serie_pui_2 = forms.TextInput() culoare_pui_1 = forms.ModelChoiceField(queryset=None, label="Culoare pui 1", empty_label="Alege culoarea", required=False) culoare_pui_2 = forms.ModelChoiceField(queryset=None, label="Culoare pui 2", empty_label="Alege culoarea", required=False) data_imperechere = forms.DateInput() primul_ou = forms.DateInput() data_ecloziune = forms.DateInput() data_inelare = forms.DateInput() comentarii = forms.TextInput() # Functie pentru filtrarea rezultatelor dupa crescator def __init__(self, *args, crescator=None, **kwargs): super(EditarePereche, self).__init__(*args, **kwargs) self.fields['mascul'].queryset = Porumbei.objects.filter(crescator=crescator, sex="Mascul", perechi_masculi__isnull=True) self.fields['femela'].queryset = Porumbei.objects.filter(crescator=crescator, sex="Femelă", perechi_femele__isnull=True) self.fields['culoare_pui_1'].queryset = CuloriPorumbei.objects.filter(crescator=crescator) self.fields['culoare_pui_2'].queryset = CuloriPorumbei.objects.filter(crescator=crescator) class Meta: model = Perechi fields = "__all__" -
Serve to docker service with nginx in different endpoint
I'm building a multiservice webapp with two different services. The webfront and the API. I've manage to server the front, and make it communicate with the api internally, but i'm new to nginx and I've no idea how to do it. This is my actual ninx.conf for a django front. upstream webapp{ server front:8000; } server { listen 80; location / { proxy_pass http://webapp; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /staticfiles/ { alias /home/webapp/web/staticfiles/; } } The front is running with gunicorn in port 8000, and its served in http://localhost/. The api is running with gunicorn in port 5000 and I would like to access it like http://localhost/api This is how i define the service in the docker-compose file: api: build: context: ./API dockerfile: Dockerfile command: gunicorn -b 0.0.0.0:5000 api:api --limit-request-line 0 ports: - 5000:5000 -
Unresolved Imports in VS Code Django Project
I want to open a folder at the level above a Django project directory (project_parent below) in VS Code and have the linter correctly resolve the Django project imports: | project_parent | -- | django_project_dir | -- | -- | manage.py If I do this, the linter is confused and I get a bunch of warnings on imports from the Django modules in the project: unresolved import 'module.models' Python(unresolved-import) If I open VS Code at the the Django project folder level, the linter resolves all of the imports. This isn't ideal though because I have to close and re-open VS Code at the level above to see other related code (Ansible, bash scripts, etc.) My question is how to update VS Code settings to add the Django project directory to the linter path? Env: VS Code: 1.40.1 Python: 3.7.2 Django: 2.2.1 Related question: Pylint "unresolved import" error in visual studio code the solution here is just to open the project at the level of the Django project dir which I don't want to do. my issue is not related to "python.pythonPath" setting, the python path is fine and all of the package level imports are resolved by the linter. -
Reverse for 'product' with no arguments not found. 1 pattern(s) tried: ['product/(?P<slug>[^/]+)/$']
I am Django newbie and learner, just follow the tutorial and got stuck. When I add a SlugField in django models.py and make a get_absolute_url but the reverse error is coming in navbar. Reverse for 'product' with no arguments not found. 1 pattern(s) tried: ['product/(?P[^/]+)/$'] models.py from django.db import models from django.urls import reverse from django.conf import settings # Create your models here. # Choices CATEGORY_CHOICES = ( ('S','Shirt'), ('P','Pants'), ('J','Jacket'), ('W','Watches'), ('E','Electronics'), ('SO', 'Shoes'), ) LABEL_CHOICES = ( ('P', 'primary'), ('S', 'secondary'), ('D', 'danger'), ) class Item(models.Model): title = models.CharField(max_length=200) price = models.FloatField() category = models.CharField(choices=CATEGORY_CHOICES,max_length=3) image = models.ImageField(upload_to='images/') slug = models.SlugField() label = models.CharField(choices=LABEL_CHOICES, max_length=1) def __str__(self): return self.title def get_absolute_url(self): return reverse('core:product', kwargs={"slug": self.slug}) class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) def __str__(self): return self.item class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) item = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() orderd = models.BooleanField(default=False) def __str__(self): return self.user.username -
Django Edit Profile - 'bool' object is not callable
So I just followed this tutorial to create a profile for a user and allow them to edit it but I get this error when I go and visit the edit page 'bool' object is not callable File "C:\Users\...\account\userprofile\views.py", line 64, in profile_edit_view if request.user.is_authenticated() and request.user.id == user.id: TypeError: 'bool' object is not callable models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings class UserProfile(models.Model): user = models.OneToOneField(User, related_name="user", on_delete=models.CASCADE) photo = models.ImageField(upload_to = "account/userprofile/photos", verbose_name="Profile Picture", max_length=255, null=True, blank=True) location = models.CharField(max_length=100, default='', blank=True) website = models.URLField(default='', blank=True) bio = models.TextField(default='', blank=True) @receiver(post_save, sender=User) def create_profile(sender, **kwargs): user = kwargs["instance"] if kwargs["created"]: user_profile = UserProfile(user=user) user_profile.save() post_save.connect(create_profile, sender=User) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserChangeForm class ProfileEditForm(forms.ModelForm): class Meta: model = User fields = ['first_name', 'last_name', 'email'] views.py def profile_edit_view(request, pk): # querying the User object with pk from url user = User.objects.get(pk=pk) # prepopulate UserProfileForm with retrieved user values from above. user_form = ProfileEditForm(instance=user) # The sorcery begins from here, see explanation below ProfileInlineFormset = inlineformset_factory(User, UserProfile, fields=('location', 'website', 'bio')) formset = ProfileInlineFormset(instance=user) if request.user.is_authenticated() and request.user.id == user.id: … -
how can I remove hyphen from confirmation links in django?
I am new with django , but I am trying to remove - from the confirmation links however when I tried to apply over models it doesnt work as I want to do it, on the other side the links keeps the same every link. I also tried to save token instead of saving the instance , but the same views def post(self, request): form = SignUpForm(request.POST) if form.is_valid(): with transaction.atomic(): user = form.save(commit=False) user.is_active = False user.save() email_subject = 'Next Step: Activate Your Account' current_site = get_current_site(request) html_message = render_to_string('email/activate.html', { 'user': user, 'domain': current_site.domain, 'token': account_activation_token.make_token(user), }) mail = EmailMessage(email_subject, html_message, to=[form.cleaned_data.get('email')]) mail.content_subtype = "html" mail.send() return JsonResponse({'message': 'success'}) else: return JsonResponse({"message":form.errors}) models.py class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) token = models.CharField(max_length=36, blank=False, unique=True, null=False) signup_confirmation = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() @receiver(post_save, sender=User) def generate_token(sender, instance, **kwargs): instance.token = str(uuid4()).replace('-', '') instance.save() tokens from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) account_activation_token = AccountActivationTokenGenerator() urls http://127.0.0.1:8000/account/activate/5bn-b706f83b79e21de52910/ # 13 min http://127.0.0.1:8000/account/activate/5bn-b706f83b79e21de52910/ # 20 min http://127.0.0.1:8000/account/activate/5bn-b706f83b79e21de52910/ # 45 min http://127.0.0.1:8000/account/activate/5bn-755ea8cee1faa6a91c2b/ # one hour ago -
Bulk insert to mongo DB using threadpool inside a celery task
When I tried bulk insert to mongoDB collection inside threadpool mongoDB memory goes on increase. What is the best way to implement this in a celery task? -
debugging django apps and printing values
Being new to django , I am trying to debug few things and print their values . This is my views.py for the app and here is the code .I tried to print the customers but I get some response which i couldn't understand . class CustomerViewSet(viewsets.ModelViewSet): serializer_class=CustomerSerializer def get_queryset(self): active_customers=Customer.objects.filter(active=True) import pdb; pdb.set_trace() print('active_customers',active_customers) return active_customers I tried the method of importing pdb and printing active_customers in the terminal and here is the response . <QuerySet [<Customer: >, <Customer: >, <Customer: nsxns xn dsnc d>]> Where can I print the values that is sent as response .What are some good ways to trace the flow of data in the django rest framework ? -
Eclipse error 'Tcl_WaitForEvent: Notifier not initialized' Django server stops after hitting a breakpoint 2nd time
Use Eclipse to start django webserver in debug mode, and set a break point. The following sequence with cause Eclipse to unload (webserver stop) the server. Eclipse version: Eclipse Java EE IDE for Web Developers. Version: Neon Release (4.6.0) Build id: 20160613-1800 Sequence: 1) Load a page to hit break point. The page is loaded. 2) Load same page and server will stop. Error in Eclipse console: Tcl_WaitForEvent: Notifier not initialized If not setting breakpoint, all works fine. How to solve the problem? -
Basic tag system using ManyToManyField
I'm writing a simple Django powered notetaking app, and currently I'm implementing basic tagging system for my notes. The requirement is to have a Tag model with added_by field on it as a ForeignKey to User. First I have tried to modify django-taggit source, as well as extend its Tag model, however haven't had any success. So, I decided to implement my own tagging system from scratch. For this purpose I'm using a ManyToManyField: class Note(models.Model): slug = models.SlugField() title = models.CharField(max_length=255) [...] tags = models.ManyToManyField(Tag) This is my form: class NoteForm(forms.ModelForm): class Meta: model = Note fields = [ 'title', 'description', 'notebook', 'tags' ] widgets = { 'tags': forms.TextInput() } Everything renders nicely, but when I try to submit the create form, I get an error: So, inside that TextInput is a comma separated string. I assume that's not what Django expects, but I don't know how to convert that into something Django would accept. I have tried to debug this, but it seems that my form_valid isn't getting executed at all. I have also tried to put some debug statements in clean_tags in my ModelForm, which is also not getting executed. How can I overcome the issue? -
I want help in creating a function for adding items in cart without logging in
I am trying to make a website like any other eCommerce sites and I want add if any user is not logged in then also he/she should be able to add items to the cart. Any help regarding this will be grateful! thank-you very much... -
one more stupid question about django, django templates and django-stars-ratings module
i'm trying to implement a rating system for my Django project I have two models rn, Article and Comment. I'm using Django-stars-rating app (here's the docs: https://django-star-ratings.readthedocs.io/en/latest/) Currently i print ratings for each instance of Article without any issue via {% rating article 10 10 True %} In the docs they say that we can override template via template_name argument in {%%} command, but i don't have any idea how to do this. I've tried this {% rating article 10 10 True widget_custom.html %} but it's now working. By the way, i have comments form for Articles. i want to have opportunity for users to rate article right in comment form, but when i simple add {% ratings e %} to form, user can vote, but score immediately recounts. I'm stucked there for a three days. Help, please. P.S. If anybody knows any solution for creating such a system, please give links, i'll be very grateful. Thanks in advance. -
Include field in form but not model django
In Django I have a modelForm with several text fields and a checkbox field for front-end only use. However, I do not want to add the checkbox field's value to the database with the text field's values when I submit the form. Is there a way to "ignore" a field in a model? -
Django 2.2 Breaking Change with runserver command
Somewhere in the upgrade from 2.1.0 to 2.2.0, the Django command: manage.py runserver begins to require the notebook module, which is a part of the jupyter package. It's unknown why it is needed, and very little documentation exists to justify its inclusion. To move past this issue, we've added jupyter to the requirements, but it is suggested that we find a way to not install jupyter on our production and staging servers. Note: This breaks when upgrading from Django 2.1.14 to 2.2.0 Note: This does not affect the operation of openscout_uwsgi or supervisor Note: This seems to be linked directly with the runserver manage.py command, and by association or inheritance, the runsslserver command Note: This can also be corrected by pip installing the jupyter package, and immediately uninstalling the jupyter package. Uninstalling the jupyter package leaves behind some directories, and a binary executable Note: Our assumption is that it is a django issue, between 2.1 and 2.2, howevver, we can't be certain. It may be an issue buried in dependency list. I.e., Django 2.2 requires package X version Y, which does not correctly require jupyter. The following is the error produced by the ./manage.py runserver command: Traceback (most recent call …