Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Application error when pushing django project on heroku
After pushing my project to Heroku, I get an application error. Here is log tail. Couldn't understand what is an error about. 2020-05-25T12:55:19.445488+00:00 app[api]: Release v1 created by user menhior1@gmail.com 2020-05-25T12:55:19.445488+00:00 app[api]: Initial release by user menhior1@gmail.com 2020-05-25T12:55:19.847136+00:00 app[api]: Enable Logplex by user menhior1@gmail.com 2020-05-25T12:55:19.847136+00:00 app[api]: Release v2 created by user menhior1@gmail.com 2020-05-25T13:05:38.136490+00:00 heroku[router]: at=info code=H81 desc="Blank app" method=GET path="/" host=zeyzak-crm1.herokuapp.com request_id=2448cb00-bc19-4bef-8438-427f79461d08 fwd="188.253.224.201" dyno= connect= service= status=502 bytes= protocol=https 2020-05-25T13:05:38.744109+00:00 heroku[router]: at=info code=H81 desc="Blank app" method=GET path="/favicon.ico" host=zeyzak-crm1.herokuapp.com request_id=05d800b7-6a7a-4c53-8d71-1c9549af2030 fwd="188.253.224.201" dyno= connect= service= status=502 bytes= protocol=https 2020-05-25T16:11:40.000000+00:00 app[api]: Build started by user menhior1@gmail.com 2020-05-25T16:12:18.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/ceb2701d-e110-4d9e-84b7-57167e335f93/activity/builds/b0593212-6cc0-46ff-a114-c52008789e8b 2020-05-25T17:47:14.000000+00:00 app[api]: Build started by user menhior1@gmail.com 2020-05-25T17:48:07.506138+00:00 app[api]: Attach DATABASE (@ref:postgresql-silhouetted-57617) by user menhior1@gmail.com 2020-05-25T17:48:07.506138+00:00 app[api]: Running release v3 commands by user menhior1@gmail.com 2020-05-25T17:48:07.519990+00:00 app[api]: @ref:postgresql-silhouetted-57617 completed provisioning, setting DATABASE_URL. by user menhior1@gmail.com 2020-05-25T17:48:07.519990+00:00 app[api]: Release v4 created by user menhior1@gmail.com 2020-05-25T17:48:08.140682+00:00 app[api]: Deploy 93818386 by user menhior1@gmail.com 2020-05-25T17:48:08.140682+00:00 app[api]: Release v5 created by user menhior1@gmail.com 2020-05-25T17:48:19.000000+00:00 app[api]: Build succeeded 2020-05-25T17:49:04.000000+00:00 app[api]: Build started by user menhior1@gmail.com 2020-05-25T17:49:46.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/ceb2701d-e110-4d9e-84b7-57167e335f93/activity/builds/a191374a-616a-44f3-99fe-62edd9c1f4ca 2020-05-25T20:45:20.752157+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=zeyzak-crm1.herokuapp.com request_id=305386ff-afb0-4d73-bc24-2f92b1c5a816 fwd="194.135.170.230" dyno= connect= service= status=503 bytes= protocol=https … -
Django Rest Framework: Should I use URL Slugs or query parameters to list items of specific category?
Right now I have a viewset that allows me to: List all the products on: www.example.com/api/products Retrieve the detail information of one product on: www.example.com/api/products/5 The problem is that in the mobile application the products will only be visible when you are inside a category and subcategory. The product model looks something like this: class Product(models.Model): name = models.CharField(max_length=255) description = models.TextField() image = models.CharField(max_length=255) category = models.ForeignKey(ProductCategory, related_name='products', on_delete=models.CASCADE) subcategory = models.ForeignKey(ProductSubcategory, related_name='products', on_delete=models.CASCADE) And the product Viewset looks like this: class RoutineViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): queryset = models.Product.objects.all() def get_serializer_class(self): if self.action == 'list': return serializers.ProductListSerializer else: return serializers.ProductDetailSerializer Should I be using a slug or ID in the endpoint to get the items? www.example.com/api/products/category/food/subcategory/snacks www.example.com/api/products/category/2/subcategory/3 Or should I be using query parameters? www.example.com/api/products/?category=2,subcategory=3 My instinct tells me that the easiest way would be to use query parameters and overwrite the "get_queryset" method to get different products depending on the query parameters. But I'm not sure if that is the standard way of doing something like this. -
Django database migrations stop with addition of "Meta" class
I've created a Django application and I have a model like such: class Company(models.Model): name = models.TextField(max_length = 200) When I run python3 manage.py makemigrations appname, everything works as expected, and a migration file for the class is created. The problem happens if the class in the model defines a Meta class as well: class Company(models.Model): name = models.TextField(max_length = 200) class Meta: app_label = "Companies" Now, if I run the makemigrations command, I get a "no changes detected" message, and no migration file is generated: > python3 manage.py makemigrations myApp No changes detected in app 'appname' Worse yet, if the model with the Meta class had no dependencies (foreign keys), a migration is created that will drop the model/table entirely. All models with a Meta class defined will not generate a migration, either an initial one or any subsequent migration for some reason. Classes that have Meta added after the fact will be removed at the next migration. I'm using Python 3.8.3 and Django 3.0.6 on Mac OS 10.15.5. -
Django Rolling Back Instance Save
I have the following code: def form_valid(self, form): data = self.request.POST email, password = data.get("email"), data.get("password1") usr = User.objects.create_user(username=self.student.reg_number, email=email, password=password) self.student.user = usr self.student.save() The line where I'm creating a user instance works, when used alone, i.e without referencing/assigning the usr object to the student object. So its like the moment I assign it to the student instance, it disappers or maybe undoes/rolls back the save that was previously done on line 4. What might be the cause of this? I have read this answer on a similar question but I did not understand the proposed solution. -
Having trouble with creating custom user in Django
I am new to Django and I am trying to create a custom user. However, I noticed my data is just inserting the raw data to database from my POST request. For example, if I insert my data from the terminal using create superuser, my data in my database looks something like this id | password | last_login | email | staff | adm 1 | pbkdf2_sha256$180000$bGUp7u590CDf$wlecM+W0h7/6q/rZhKP73IMH13msn87I/RoK/VJewKk= | NULL | <bound method BaseUserManager.normalize_email of <class 'qssgg.models.UserManager'>> | 1 | 1 | However, if I try to store data from my REST API POST request, it stores data like this | id | password | last_login | email | staff | admin | +----+----------+------------+-----------------------+-------+-------+ | 1 | hi | NULL | bobby000000@gmail.com | 0 | 0 | As you can see, the password is not getting encrypted and email is different. I am wondering why this is happening? I am following a tutorial and here is my code: models.py class UserManager(BaseUserManager): def create_user(self, email, password = None, isStaff=False, isAdmin=False): if not email: raise ValueError("User must have an email") if not password: raise ValueError("User must add password") userObj = self.model( email = self.normalize_email ) userObj.set_password(password) userObj.staff = isStaff userObj.admin = isAdmin userObj.save(using=self._db) … -
Add new domain into the django-hosts configuration file from a view?
I am creating a web app which will assign each user their own domain when they create an account. All users will be able to access the same functionality under the same app. How do I add a domain for a new user into the django-hosts configuration file? If this is not possible what are alternative solutions to achieve the same outcome? hosts.py from django_hosts import patterns, host host_patterns = patterns('path.to', host(r'api', 'api.urls', name='api') ) views.py def create_account(request): #add host to host_patterns in host.py -
Form Wizard can't access final "done" step
I'm using Django 3 and I try to implement a basic "example" Wizard Form from django-forms. My Problem is : 1/ can't retrieve inputs from previous forms steps 2/ can't access to "done.html" after submitting last steps Here's my code : views.py class ContactWizard(SessionWizardView): template_name = 'accounts/test_wizard.html' form_list = [ContactForm1, ContactForm2, ContactForm3] def done(self, form_list, **kwargs): form_data = process_form_data(form_list) return render(self.request, 'accounts/done.html', {'form_data': form_data}) def process_form_data(form_list): form_data = [form.cleaned_data for form in form_list] return(form_data) urls.py from forms.models import ContactForm1, ContactForm2, ContactForm3 from .views import ContactWizard urlpatterns = [ path('signup/', views.signup, name='signup'), path('login/', views.login, name='login'), path('logout/', views.logout, name='logout'), path('profile/', views.profile, name='profile'), path('test_wizard/', ContactWizard.as_view([ContactForm1, ContactForm2, ContactForm3]), name='test_wizard'), ] forms.py (actually, I'm using a forms/models.py to have a separate app for forms. But it seems to be ok as I see all forms. class ContactForm1(forms.Form): subject = forms.CharField(max_length=250) class ContactForm2(forms.Form): sender = forms.EmailField() class ContactForm3(forms.Form): message = forms.CharField(max_length=250) Thanks in advnce guys for your help ! -
Django Custom User is not showing a extra field with foreign key as Select list
I have a Custom User class CustomUser(AbstractUser): registration_code = models.ForeignKey(RegistrationCode, null=True) ... def __str__(self): return self.username class RegistrationCode(models.Model): code = models.CharField(max_length=30, null=True, blank=True) def __str__(self): return self.code Within the admin page I would like to be able to set the "registration_code". class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username', 'registration_code'] fieldsets = ( (None, { 'fields': ('email', 'username', 'registration_code') }), ) admin.site.register(CustomUser, CustomUserAdmin) But on the admin page I do not get a select list. But a default input field: And if I edit the registration_code and try to save I get: Cannot assign "'2'": "CustomUser.registration_code" must be a "RegistrationCode" instance. Which sounds logical because I need to enter a RegistrationCode instance. The same construction works for other models but for a Custom User it is not?? This is driving me crazy. Anybody an idea why I do not get the Select list? -
Filter Products by Catagory in Django
I have a filter list on my home page: <!-- ? Filter --> <div class="filter border-top border-bottom row"> <a href="#"> <img src="{% static 'store/images/bottoms.png' %}" alt=""> </a> <a href="#"> <img src="{% static 'store/images/outerwear.png' %}" alt=""> </a> <a href="#"> <img src="{% static 'store/images/tshirt.png' %}" alt=""> </a> <a href="#"> <img src="{% static 'store/images/shoes.png' %}" alt=""> </a> <a href="#"> <img src="{% static 'store/images/skateboard.png' %}" alt=""> </a> and trying to filter with something like this: class ProductListView(ListView): model = Product template_name = "store/home.html" def get_queryset(self): catagory = catagory.objects.filter(catagory) Can I pass the catagory name of the icon I click to the view to filter it? And also can I pass the filter back my home page (thats already listing all Products on) ? This is my home view: class ProductListView(ListView): model = Product template_name = "store/home.html" context_object_name='products' ordering = ['-date_posted'] Would it be easier to add the queryset to this and set the filter to all as default? Any help appreciated thank you. -
How do I save ModelFrom Data in the Model having ForeignKey of User Model in Django?
I have a Detail Model that has ForeignKey of User Model. I also have a UpdateStudentDetailForm ModelForm that is based on Detail model but also has an extra field that is a dropdown list of users (students), I use this ModelForm use to take input from a current user (teacher). User (teacher) select a user (student) from the dropdown list, fill other fields and submit the form. Now, I want that submitted data to be saved in Detail Model of the user (student) that was selected by user (teacher). What should I do in my views.py in order to accomplish this? My Detail Model in models.py is below: class Detail(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(max_length=50) skype_session_attendance = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(20)], verbose_name="Skype Session Attendances (of this subject, in numbers)", help_text="Enter the numbers of skype sessions of this subject, the student attended out of 20.") internal_course_marks = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(40)], verbose_name="Internal Course Marks (of this subject, in numbers)", help_text="Enter the total internal course marks of this subject, the student obtained out of 40.") programming_lab_activity = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(25)], verbose_name="Programming Lab Activities (of this subject, in numbers)", help_text="Enter the total numbers of programming lab activities of this subject, the student participated in, out of … -
Unable to log in to the PostCreateView template
I have built a blog project and I can't access the PostCreateView for some unknown reason. I keep getting Page 404 error although I have in the urls patterns I am also getting the error raised by score.views.PostDetailView Here is the views.py class PostCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = Post fields = ['title', 'design'] template_name = "post_form.html" success_url = "/score/" success_message = "Your Post has been submitted" def form_valid(self, form): form.instance.designer = self.request.user return super().form_valid(form) here is the PostDetail Views.py class PostDetailView(DetailView): model = Post template_name = "post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True context["total_likes"] = total_likes context["liked"] = liked return context Here is the Urls.py app_name = 'score' urlpatterns = [ path('', PostListView.as_view(), name='score'), path('<slug:slug>/', PostDetailView.as_view(), name='post-detail'), path('new/', PostCreateView.as_view(), name='post-create'), path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), ] here is the nav bar html that is taking me to the page <a class="nav-link waves-effect" href="{% url 'score:post-create' %}" >Upload Post</a> here is the post_form template <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4" style="padding-top: 20px;">Upload Your Post</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info ml-0" type="submit">Upload</button> </div> </form> -
Filter objects not in a many-to-many field
I am trying to add five "new words" to the user's vocabulary list. I need help selecting Terms which the user hasn't learned. My first version took all the terms in a text (Term.objects.filter(text__pk=pk)) and used a for loop to check each one to see if it was in the UserText's vocabulary. (When a user studies a text, a UserText is created to keep track of learned vocabulary and points) Very Slow. My second attempt looks like this but it isn't working Term.objects.filter(text__usertext__pk=user_text.pk).exclude(text__usertext__vocabulary__word=F('word__text')) Any help would be appreciated. My models look like this: # models.py class Text(models.Model): text = models.TextField() vocabulary = models.ManyToManyField("Word", through="Term") class Term(models.Model): text = models.ForeignKey(Text, on_delete=models.CASCADE) word = models.ForeignKey("Word", on_delete=models.CASCADE) order = models.PositiveIntegerField() class Word(models.Model): text = models.CharField(max_length=100) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) texts = models.ManyToManyField(Text, through="UserText") vocabulary = models.ManyToManyField(Word, through="UserVocabulary") class UserText(models.Model): user_profile = models.ForeignKey(Profile, on_delete=models.CASCADE) text = models.ForeignKey(Text, on_delete=models.CASCADE) vocabulary = models.ManyToMany("UserVocabulary", blank=True, null=True) -
How to add onclick to documentQuerySelectorAll, firing each element button to control each element span
my Website retrieves a list of elements, and I need to control each one element firing each button to change the text of each. <div id="plusButton"class="col-md-2"> <button id="countMinus" class="minus_1"><i class="fa fa-angle-left"></i></button> <span id="counter" class="counter-num_1">1</span> <button id="countPlus" class="plus_1"><i class="fa fa-angle-right"></i></button> </div> this is just one element, I need to do this for more then only one. I tried to do this with this code: document.querySelectorAll('#plusButton').forEach(function () { let counter = self.document.getElementById('counter') self.document.getElementById('countPlus').onclick = ()=>{ let increment = parseInt(counter.innerHTML) + 1 counter.innerHTML = `${increment}` } self.document.getElementById('countMinus').onclick = ()=>{ let decrement = parseInt(counter.innerHTML) - 1 counter.innerHTML = `${decrement}` } }) but it only worked for the first element. -
How can I resolve NotADirectoryError when calling runserver on pex of a Django site?
I am building a pex bundle of a Django site as follows: $ pipenv-pex --entry-point "manage.main" The resulting project.pex runs as expected for runserver --help: $ ./project.pex runserver --help usage: toptal_joglog.pex runserver [-h] [--ipv6] [--nothreading] [--noreload] [--nostatic] [--insecure] [--version] [-v {0,1,2,3}] [--settings SETTINGS] ... But if I try to actually run the server, I get a NotADirectoryError (traceback below). What directory is execute_from_command_line looking for (it seems to be finding the __main__ method in the pex file?) and how can I correctly invoke it? Watching for file changes with StatReloader Performing system checks... Traceback (most recent call last): File "/home/user/Documents/project/project.pex/.bootstrap/pex/pex.py", line 396, in execute File "/home/user/Documents/project/project.pex/.bootstrap/pex/pex.py", line 328, in _wrap_coverage File "/home/user/Documents/project/project.pex/.bootstrap/pex/pex.py", line 359, in _wrap_profiling File "/home/user/Documents/project/project.pex/.bootstrap/pex/pex.py", line 447, in _execute File "/home/user/Documents/project/project.pex/.bootstrap/pex/pex.py", line 544, in execute_entry File "/home/user/Documents/project/project.pex/.bootstrap/pex/pex.py", line 559, in execute_pkg_resources File "/home/user/Documents/project/project.pex/manage.py", line 18, in main File "/home/user/.pex/installed_wheels/76e2a7db05161ac57adcee837113974bb4f07b41/Django-3.0.6-py3-none-any.whl/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/user/.pex/installed_wheels/76e2a7db05161ac57adcee837113974bb4f07b41/Django-3.0.6-py3-none-any.whl/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/user/.pex/installed_wheels/76e2a7db05161ac57adcee837113974bb4f07b41/Django-3.0.6-py3-none-any.whl/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/user/.pex/installed_wheels/76e2a7db05161ac57adcee837113974bb4f07b41/Django-3.0.6-py3-none-any.whl/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/home/user/.pex/installed_wheels/76e2a7db05161ac57adcee837113974bb4f07b41/Django-3.0.6-py3-none-any.whl/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/user/.pex/installed_wheels/76e2a7db05161ac57adcee837113974bb4f07b41/Django-3.0.6-py3-none-any.whl/django/core/management/commands/runserver.py", line 95, in handle self.run(**options) File "/home/user/.pex/installed_wheels/76e2a7db05161ac57adcee837113974bb4f07b41/Django-3.0.6-py3-none-any.whl/django/core/management/commands/runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "/home/user/.pex/installed_wheels/76e2a7db05161ac57adcee837113974bb4f07b41/Django-3.0.6-py3-none-any.whl/django/utils/autoreload.py", line 599, in … -
How to handle exceptions with stripe
I am trying to integrate stripe with my django project, so I try to create a PaymentIntent and if a network communication with stripe failed I will try to do like this: try: intent = stripe.PaymentIntent.create( amount=100, currency='usd' ) return JsonResponse({ 'clientSecret': intent['client_secret'] }) intent = stripe.PaymentIntent.cancel( 'pi_1Gmkg0CpmL7GkvAyvWc0A7Fi' ) except stripe.error.CardError as e: pass except stripe.error.RateLimitError as e: pass except stripe.error.InvalidRequestError as e: pass except stripe.error.AuthenticationError as e: pass except stripe.error.APIConnectionError as e: try: intent_cancel = stripe.PaymentIntent.cancel( intent['id'] ) except Exception as e: # (If an exception is raised this means that the PaymentIntent was not created, I am right ?) # I redirect the user to the payment page and inform him # that a network problem has occurred and ask him to repeat his request pass except stripe.error.StripeError as e: pass except Exception as e: pass My questions are: 1 Is my way of handling the exception right ? 2 Can I apply this logic to the other exception ? 3 In the documentation they say that we should use an idempotency_key to retry the failed requests, how can I implement this ? and what about if I retry the failed request and it fails again, what should … -
handler404 returning Server Error (500) instead of 404.html - Django/Python
I spent several hours on this code and could not get to find out why I am getting server error (500) instead of 404.html in django program. Please see below codes and could someone help? settings.py: DEBUG = False ALLOWED_HOSTS = ['*'] urls.py: handler404 = "mysite.views.error_404" views.py: def error_404(request, exception): return render(request, '404.html') 404.html: {% extends "base.html" %} {% load static %} {% block main %} some html text here {% endblock %} -
Django - how get last item from queryset in template
I'm a complete beginner at Django and can't do something quite basic; link to the last (or first) item in the database. To start with this is the model I'm working with: class Artwork(models.Model): date = models.DateField(auto_now_add=True) art = models.ImageField(upload_to='artworks/%Y') title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) herochoices = [('left', 'left'), ('middle', 'middle'), ('right', 'right')] hero = models.CharField(choices=herochoices, max_length=6, null=True, blank=True, unique=True, error_messages={'unique':'Another artwork already uses this hero position.'}) slug = slugify(title, allow_unicode=False) def __str__(self): return self.title def get_absolute_urls(self): return reverse('artwork_list', kwargs={'slug': self.slug}) I created the following queryset in my view: class ArtworkDetailView(DetailView): model = Artwork template_name = 'artwork_detail.html' qs = Artwork.objects.all() And now inside my template I'm trying to provide a link to the last item in the queryset. However I have no idea what to populate the href attribute with in order to provide such link: {% extends 'base.html' %} {% block content %} <h1>{{ artwork.title|title}}</h1> <div class="row"> <div class="col-sm-1 float-left"> <p class="arrows"> {% if artwork.get_previous_by_date.id == '' %} <a href="{{ ????? }}"> {% else %} <a href="/artwork/{{ artwork.get_previous_by_date.id }}/{{ artwork.get_previous_by_date.title }}/"> {% endif %} <span class="material-icons" style="font-size: 30pt">keyboard_arrow_left</span> </a> </p> </div> I have tested that the if condition works fine by putting a url to https://www.google.com in … -
How to display Django Model Object using ajax in HTML template?
I'm trying to get Django query-set using ajax and display in HTML template. viwes.py from .models import Posts from django.http import JsonResponse from django.core import serializers def check(request): post = PostsData.objects.all() data = serializers.serialize("json", post) response = JsonResponse({'data': data}) return response template ajax <script> function check(){ $.ajax({ method: "GET", url: "/check/", success: function(res){ console.log(res.data) } }) } </script> output (ajax response) [{"model": "example.postsdata", "pk": 1, "fields": {"post": 1, "msg": "Hello", "image": "Lady"}}, {"model": "example.postsdata", "pk": 2, "fields": {"post": 1, "msg": "Vinay", "image": "viay"}}] I got the data in JSON enclosed in an array but I don't know how to use this array to show my data in templates. How do I display this data inside the HTML body? -
In Django, able to upload an image from a form, but unable to render it
I have a model that I create from a modelForm. This model contains an image. I'm able to upload an image through the form, and this is saved in my local static/ folder. However, when I try to render this image, I receive a 404 error. models.py class ProfileModel(models.Model): ... image = models.ImageField(upload_to = 'static', default='images/none.jpg') ... views.py # the page to create the model def create_profile(request): if request.method == "POST": form = ProfileForm(request.POST, request.FILES) if form.is_valid(): profile = form.save(commit=False) profile.image = request.FILES.get('image') profile(len(request.FILES)) # this is 1 profile.save() else: form = ProfileForm() return render(request, 'user/create_profile.html', {'form':form}) # the page that renders the model def profile(request, url): profile = ProfileModel.objects.get(url=url) return render(request, 'user/profile.html', {'profile': profile}) Confirmed that the images are uploaded to my local static/images folder. However, in the html file to render the image, I try to access the image: user/profile.html <section> <div class="container"> <img src="{{profile.image.url}}" class="img-fluid" alt="Profile Picture"> </div> </section> But the image gets a 404 error: Ex. GET /media/static/13015350_10207600423761936_1820820689078578327_n.jpg HTTP/1.1" 404 3094 -
Django Test DoesNotExist : `matching query does not exist` error when testing functions in the models
I'm still new to the language so my implementations might not be correct. I get this error when testing the methods in my models in Django with Unit testing. The problem is that two different functions has the same implementation but only one of them triggers the error. Can anyone explain why this happens and suggest any hints on how to resolve this? Thank you Here are the functions in models.py: class Staff(models.Model): ------------------------ # Get the current (latest) commission the staff has at the moment (Function 1) @property def current_commission(self): return Commission.objects.filter(staff=self).latest('date_applied').sale_commission class Sale(models.Model): staff_id = models.ForeignKey(Staff, on_delete=models.CASCADE) product_id = models.ForeignKey(LemonadeProduct, on_delete=models.DO_NOTHING) quantity = models.IntegerField(default=1) date_sale = models.DateTimeField(auto_now=True) @property (Function 2) def get_staff_commission(self): commission = Commission.objects.filter(staff=self.staff_id, date_applied__lte=self.date_sale).latest('date_applied') return "%.2f" % (self.product_id.price * self.quantity * (commission.sale_commission / 100)) Here are my test cases in tests.py: def create_commission(commission, days, staff): time = timezone.now() + datetime.timedelta(days=days) return Commission.objects.create(sale_commission=commission, date_applied=time, staff=staff) # Create your tests here. class StaffModelTestCase(TestCase): def test_current_commission(self): staff_1 = Staff(name='A', position='B') staff_1.save() com_1 = create_commission(10, 0, staff_1) com_1.save() # No errors in this line self.assertEqual(staff_1.current_commission, 10) class SaleModelTestCase(TestCase): def setUp(self): time = timezone.now() staff = Staff(name="C", position="B") staff.save() product = LemonadeProduct(name="Lemonade", price=20) product.save() sale_1 = Sale(staff_id=staff, product_id=product, quantity=1) sale_1.save() sale_2 … -
How do I create a serializer that reuses a unique key of my model?
I'm using Python 3.7, Django 2.2, the Django rest framework, and pytest. I have the following model, in which I want to re-use an existing model if it exists by its unique key ... class CoopTypeManager(models.Manager): def get_by_natural_key(self, name): return self.get_or_create(name=name)[0] class CoopType(models.Model): name = models.CharField(max_length=200, null=False, unique=True) objects = CoopTypeManager() Then I have created the below serializer to generate this model from REST data class CoopTypeSerializer(serializers.ModelSerializer): class Meta: model = CoopType fields = ['id', 'name'] def create(self, validated_data): """ Create and return a new `CoopType` instance, given the validated data. """ return CoopType.objects.get_or_create(**validated_data) def update(self, instance, validated_data): """ Update and return an existing `CoopType` instance, given the validated data. """ instance.name = validated_data.get('name', instance.name) instance.save() return instance However, when I run the below test in which I intentionally use a name that is taken @pytest.mark.django_db def test_coop_type_create_with_existing(self): """ Test coop type serizlizer model if there is already a coop type by that name """ coop_type = CoopTypeFactory() serializer_data = { "name": coop_type.name, } serializer = CoopTypeSerializer(data=serializer_data) serializer.is_valid() print(serializer.errors) assert serializer.is_valid(), serializer.errors result = serializer.save() assert result.name == name I get the below error ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/davea/Documents/workspace/chicommons/maps/web/tests/test_serializers.py", line 46, in test_coop_type_create_with_existing assert serializer.is_valid(), serializer.errors AssertionError: … -
Django formset create new forms from view
I have a formset and would like to create additional forms after the post is made but before saving. The additional form values are coming from a separate formset input on the same view via a CSV submission. How can I create the new forms for a formset? views.py class CreateAuthorView(CreateView): template_name = "author_add.html" model = Author form_class = AuthorForm def get_context_data(self, **kwargs): context = super(CreateAuthorView, self).get_context_data(**kwargs) if self.request.POST: context["books_file"] = BooksFileFormSet(self.request.POST, self.request.FILES) context["books"] = BooksFormSet(self.request.POST) else: context["books_file"] = BooksFileFormSet() context["books"] = BooksFormSet() return context def form_valid(self, form): context = self.get_context_data() books_file = context["books_file"] books = context["books"] self.object = form.save(commit=False) books.instance = self.object if books_file.is_valid(): # I am not sure if this is the best way to iterate through the files posted; any suggestion here would be appreciated for book_file in books_file.files: for index, book_file in enumerate(self.request.FILES.get(book_file).read().decode("UTF-8").split("\r\n")): if index != 0 and len(book_file) == 2: book_file = book_file.split(",") # Values from book_file are added to the empty BooksFormSet; example below books.page = book_file[0] books.content = book_file[1] books.save() return redirect(self.get_success_url()) -
Django Getting PK from Createview
I am creating a blog post with a specific primary key (pk). My other function requires to have the pk as an input (please check the views.py). I am trying to get the post id by getting it as an object id, although it indicated that object has no attribute 'id'. Any ideas how to get pk as a variable? Thanks, Ted #The template {% extends "Blog/base.html" %} {% load crispy_forms_tags %} {% block content%} <div class="content-section"> <form method = "POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"> Blog Post </legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> </div> {% endblock content%} #urls.py from django.urls import path from .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView from . import views urlpatterns = [ path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new', PostCreateView.as_view(), name='post-create'), ] #views.py from django.shortcuts import render from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView ) from .models import Post from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from .latex import tex from django.http import FileResponse, Http404 from django.urls import reverse class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['first_name', 'last_name', 'titles' ,'title', 'content', 'billing'] def form_valid(self, form): form.instance.author = self.request.user # Use this to get the information from … -
How to change filter panel width in Django admin
I have found anwers how to change column width but not filter width. In my case filter is filled witch just numbers so the Filter pannel could be much more narrow, but how to do it? Also, since there are a lot of numbers, can I arrange them in several columns (still talking about Filter panel), how? Django admin example image -
Sending notification on post_save signal in django
I am trying to create a simple notification system by using django-signals. I have a Notification Model like this: class Notification(models.Model): title = models.CharField(max_length=100) message = models.TextField() viewed = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) and Signals is implemented like this: from django.db.models.signals import post_save from django.dispatch import receiver from accounts.models import CustomUser, Notification @receiver(post_save, sender=GeneralAgreement) def create_general_agreement_message(sender, instance, created, **kwargs): if created: user_data = CustomUser.objects.values('id').filter(is_superuser=True) for i in user_new: Notification.objects.create(user_id=i['id'], title="New General Agreement Added!!", message="New General Agreement has been added to the database!!") Which creates a notification object when an agreement is added to the database and Agreement Model like this: class Agreement(models.Model): name = models.CharField(max_length=100) name_short_code = models.CharField(max_length=50) address = models.CharField(max_length=100) csv_import = models.BooleanField(default=False) if data is uploaded from csv, csv_import field will be saved as true which i have handled by using django-import-export If I upload a CSV with thousand of rows it will also create the notification for each agreement object created which is difficult to handle How do I send the notification with the count of the agreement created in total if uploaded from CSV avoiding the creation of notification for each agreement object?