Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What's the best way to mock a Django User?
I'm trying to instantiate a User instance through a Mock. That mock instance is being passed to another model Profile where I'm checking for any validation errors when a cleaning method is called. However I'm getting: AttributeError: Mock object has no attribute '_state' There is this previous post: How to mock users and requests in django. Nevertheless, I want to avoid any database calls. What can be done differently so that a Mock will in this case? #models.py class Profile(models.Model): hobby = "Hobbyist" develop = "Developer" coding_level = ( (hobby, hobby), (develop, develop) ) user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) birth = models.DateField(verbose_name="Date Of Birth") coding_level = models.CharField( verbose_name="Experience", max_length=20, choices=coding_level, default=hobby, blank=False ) bio = models.TextField( verbose_name="User Bio", validators=[MinValueValidator(10)] ) github = models.URLField( verbose_name="GitHub link", validators=[check_submitted_link], unique=True ) avatar = models.ImageField(upload_to="images/%Y/%m/%d/") #test_models.py class TestProfile__001(SimpleTestCase): def setUp(self): self.test_user = Mock( spec=User, username="test_username", email="test@email.com" ) self.profile_data = { 'user': self.test_user, 'birth': '2019-10-07', 'coding_level': 'hobby', 'bio': "", 'github': "http://www.test.com", 'avatar': "image.txt" } def test_create_profile_fail(self): with self.assertRaises(ValidationError): test_profile = Profile(**self.profile_data) test_profile.clean_fields() -
RuntimeError: Conflicting 'product_product_options' models in application 'catalogue': on Oscar 2
I am using Django==2.2.6 And django-oscar==2.0.2. Trying to custom the Oscar models but every its not working... The error is .. File "/home/dipto/env/oscar/lib/python3.6/site-packages/django/db/models/base.py", line 316, in new new_class._meta.apps.register_model(new_class._meta.app_label, new_class) File "/home/dipto/env/oscar/lib/python3.6/site-packages/django/apps/registry.py", line 229, in register_model (model_name, app_label, app_models[model_name], model)) RuntimeError: Conflicting 'product_product_options' models in application 'catalogue': and . Following this.... Created a App with the name of "catalogue" Added it as Django app to INSTALLED_APPS Added a models.py and admin.py In catalogue app models.py from django.db import models from oscar.apps.catalogue.abstract_models import AbstractProduct class Product(AbstractProduct): Test_URL = models.URLField() from oscar.apps.catalogue.models import * In catalogue app init.py default_app_config = 'catalogue.apps.CatalogueConfig' In catalogue app apps.py from django.apps import AppConfig class CatalogueConfig(AppConfig): name = 'catalogue' label= 'shop mane' -
How to override custom model clean method if a modelform does not include some fields of the model?
I have this model: class Exam(Model): student = OneToOneField(Student, on_delete=CASCADE) has_taken_exam = BooleanField(default=False,) score = FloatField(choices=SCORE_CHOICES, null=True, blank=True, exam_date = DateField(null=True, blank=True, ) non_empty_fields = \ { 'score': 'please enter your score', 'exam_date': 'please specify your exam date', } def clean(self): errors = {} if self.has_taken_exam: for field_name, field_error in self.non_empty_fields.items(): if getattr(self, field_name) is None: errors[field_name] = field_error if errors: raise ValidationError(errors) and have this modelform class ExamForm(ModelForm): class Meta: model = Exam exclude = ('student', 'exam_date', ) when I submit this form in template, I get the below error: ValueError at / 'ExamForm' has no field named 'exam_date'. and During handling of the above exception ({'score': ['please enter your score'], 'exam_date': ['please specify your exam date']}), another exception occurred: The error happens in my view where I am validating the form. My database logic is such that I need to have an exam_date field and it should be mandatory to fill if has_taken_exam is checked. However, in ExamForm, for business reasons, I do not need the exam_date. How can I tell ExamForm to turn a blind eye to the exam_date, as I am not saving the modelform instance? -
ImportError: cannot import name 'views' from '__main__' in django
i am new at webdev i make simple webapp but trying from one day. but this issue not solved my urls.py file enter code here from django.urls import path from . import views urlpatterns=[ path('',views.home,name='home') enter code here (test) C:\Users\abc\projects\amar>C:/Users/abc/envs/test/Scripts/python.exe c:/Users/abc/projects/amar/f1/urls.py Traceback (most recent call last): File "c:/Users/abc/projects/amar/f1/urls.py", line 3, in <module> from . import views ImportError: cannot import name 'views' from '__main__' (c:/Users/abc/projects/amar/f1/urls.py) in views.py- enter code here from django.shortcuts import render home(request): return render(request,'home.html') enter code here and in settings.py template i also mention path- enter code here 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], -
JSONField show specific field in template
i have a Rank class and it has a JSONField field and example value is {"Playoff": 10, "Tournament": 15} models.py class Rank(models.Model): ... json=JSONField(default=dict) class Game(models.Model): ... status=models.ForeignKey(Status...) now i want to show exact matching field's value so for example, game.gamestatus.name is Tournament and i want to show json.Tournament value like {{ t.json.{{game.status.name}} }} (that's wrong i know) How can i do ? what should you suggest to me -
How to iterate through the newly selected objects in a ManyToManyField in the save method of a model?
I know that there's no way I'm the first to ask this question, but I cannot find the answer so please don't eat me. If I have a model with a field that is a ManyToManyField; I know that I can get the selected objects prior to the save but this isn't helpful if the selected objects have changed. models.py class AddOn(models.Model): name = models.CharField(max_length=100) class Invoice(models.Model): additional_options = models.ManyToManyField(AddOn) def save(self, *args, **kwargs): # this prints the objects that were selected prior to the save. # this isn't helpful if the selected objects have changed. print(self.additional_options.all()) Is there a better way to do this than using the post_save signal? -
Django not sending correct json response
I have set up a simple project and when a post request is made, it is expected to return a response depending on what value the user entered. I am testing my api logic in postman. At the moment, no matter what value I enter, the same json response is sent back. This is not the expected logic. views.py: def function(request): if request.method == 'POST': if request.POST.get("number") == 1: print("Number is 1") return JsonResponse({'message':'Number is 1'}) else: print("Number is not 1") return JsonResponse({'message':'Number is not 1'}) Even if the value of number is equal to 1, the message: Number is not 1, is returned. Thank You. -
Where my media files goes? Django + Heroku + MySQL
First of all, I have no idea what I should do here. I think I viewed all things about this problem. I have builded Django app with MySQL as DB (ClearDB MySQL heroku addon), and deployed it to heroku. Site works fine until I want add some items in DB. I have library-like app, so, it contains not only text, but images too. Uploading comes from admin panel and creates in media root folder with book name. (see my github repo bellow for more info). All CSS and JS files works great, but idk where my images goes. I think i missded something about what happend with media when you deploy Django app to heroku. GitHub -
Mixing of insert queries on threads in django
Have developed a django site in which some scraping code is running. I noticed a problem that when two scraping code run parallel (in different threads), the insert queries to django orm model are getting mixed up e.g in one thread if i have a value of a=1,b=1 and in the other i have the value of a=2,b=2 the value saved in the database is sometimes (1 out of 1000 and gets worse when threads increase) a=1,b=2. Have checked the values before being sent to the model.save() method, the values are fine but get distorted after that. I am using django 2.2 and for integrating mongodb have used djongo. Also to support elasticsearch index i am using django elasticsearch dsl. Dont know on which step the query is getting distorted. Also on each thread, asynchronous threading is being used. A sample of my script is : from project.views import start_new_thread @start_new_thread def site(site,loop): try: import pytz from urllib import parse from bs4 import BeautifulSoup import re from project.models import thread,post from datetime import datetime from .sentiment_analysis import calculate_sentiment import aiohttp import asyncio import async_timeout href=[] tthread=[] link=set() author={} async def fetch(session, url): async with async_timeout.timeout(30): async with session.get(url) as response: … -
Page not found (404) in django 2
I'm working in my blog project for learning the django But my urls doesn't work correctly when i create post my post created successfully and save in my database and I can see my post card in my blog But when I click the post card for show detials of post getting this error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/post/2019/10/5/testing-urls-design/ Raised by: Blog.views.post this is part of my models for blog app : models.py class Post(models.Model): image = models.ImageField(upload_to='Posts_image') title = models.CharField(max_length=256) slug = models.SlugField(max_length=256,null=True,blank=True) content = HTMLField('Content') date = models.DateTimeField(auto_now_add=True) categories = models.ManyToManyField(category) tags = TaggableManager() publish = models.BooleanField(default=False) def __str__(self): return self.title def get_absolute_url(self): kwargs = { 'year':self.date.year, 'month':self.date.month, 'day':self.date.day, 'slug':self.slug, } return reverse('blog:post-detail', kwargs=kwargs) This part for create slug in models.py def create_slug(instance, new_slug=None): slug = slugify(instance.title, allow_unicode=True) if new_slug is not None: slug = new_slug qs = Post.objects.filter(slug=slug).order_by("-id") exists = qs.exists() if exists: new_slug = "%s-%s" %(slug, qs.first().id) return create_slug(instance, new_slug=new_slug) return slug def slug_generator(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) pre_save.connect(slug_generator, sender=Post) after this part you see my views.py def post(request, year, month,day, slug): post = get_object_or_404(Post, date__year=year, date__month=month, date__day=day, slug=slug) comment_form = CommentForm(request.POST or None) new_comment = … -
ForeignKey to abstract model
I have an abstract Product model, and I wanted it to be able to hold more than one image, so I decided to make another Image model and have a ForeignKey to Product, however I quickly realised that's not possible. The reason I decided to go for abstract base model is performance gains since every child model is in its own table. Having a different Image model for each subclass sounds bad to me, since there will be more than 20 subclasses. class Product(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=50) category = models.ForeignKey('Category', on_delete=models.CASCADE, blank=False) class Meta: abstract = True class Book(Product): author = models.CharField(max_length=50) publisher = models.CharField(max_length=50) class Shoes(Product): colour = models.CharField(max_length=50) size = models.CharField(max_length=50) class Image(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='images') image = models.ImageField(upload_to=get_image_path, blank=True, null=True) How can I overcome the issue? -
Django REST Framework: error when testing POST request with list
I have a test view: @api_view(['POST']) @permission_classes([AllowAny]) @authentication_classes([]) def test_view(request): return Response(request.data) It is registered in urls.py: urlpatterns = [ path('api/test/', test_view) ] When I try to POST [{"a": 1}, {"a": 2}] manually through the REST Frameworks UI, everything works fine. However, if I write a test for it, an unexpected error occurs. Here is the test from rest_framework.test import APITestCase class ViewTest(APITestCase): def test_it(self): response = self.client.post('/api/test/', [{"a": 1}, {"a": 2}]) print(response) which produces the following error: Traceback (most recent call last): File "C:\development\HeedView\backend\clients\api\tests.py", line 13, in test_it response = self.client.post('/api/test/', [{"a":1}, {"a": 2}]) File "C:\development\HeedView\venv\lib\site-packages\rest_framework\test.py", line 300, in post path, data=data, format=format, content_type=content_type, **extra) File "C:\development\HeedView\venv\lib\site-packages\rest_framework\test.py", line 212, in post data, content_type = self._encode_data(data, format, content_type) File "C:\development\HeedView\venv\lib\site-packages\rest_framework\test.py", line 184, in _encode_data ret = renderer.render(data) File "C:\development\HeedView\venv\lib\site-packages\rest_framework\renderers.py", line 921, in render return encode_multipart(self.BOUNDARY, data) File "C:\development\HeedView\venv\lib\site-packages\django\test\client.py", line 194, in encode_multipart for (key, value) in data.items(): AttributeError: 'list' object has no attribute 'items' How to explain this behavior? -
how to relate models effectively using Django Rest Framework
I am trying to create an application to keep the accounts of a store. Each time an invoice is uploaded to the system it must create the products in another table called "products" but if the product already exists, only the price and quantity must be updated. Each invoice can have several products How should I propose the relationship between the tables?. One to many, one to one, many to many? Is there any way to represent the relationship in a way that creates a list of products on each invoice?. A supplier can bring more than one product. Is there a way in which you can create the records in the product table without creating duplicates?. It is not necessary to have the same product more than once if the price and quantity in the inventory were updated when entering a new invoice. For example, the invoice to be entered has the following information: Number List item Provider Products: (list) Product a Product b Product c Total Date If product A exists, the invoice must update the price and quantity in the inventory. If product C does not exist, the invoice must create the product. Until now, this is … -
DJANGO , how to convert django app in exe
I try to convert django app with pyinstaller but the app.exe wont start. Have some idea or some guide tutorial for do that. Thanks -
What's the equivalent of Django extends base.html in .net c#?
In Django I can do something like this <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Favorite Books</title> </head> <body> {% block content %} {% endblock content %} </body> </html> And in the other html file I can have {% extends __base.html %} {%block content%} Some html here {% endblock content%} I'm learning c#.net now. What's the equivalent of that in this framework? -
Reload Database Objects without reloading entire Page
I have a django project with two main templates. One will post stuff to a database and the other one will display the stuff in the database. Is there any way that the display template could reload the database objects without reloading the entire page? -
DRF how to make a PATCH request with file upload
So there are lots of questions about PATH in DRF (Django Rest Framework) but no one actually talks about how to actually send the request. I have a PATCH method that I want to use to modify an object and add another image. How do I do that? Here's what it looks like: def get_object(self, pk): return Attendance.objects.get(pk=pk) def patch(self, request, pk): testmodel_object = self.get_object(pk) file_serializer = AttendanceSerializer(testmodel_object, data=request.data, partial=True) # set partial=True to update a data partially if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) # I got this code from another question on here and made a few changes of my own. # Please let me know if I'm doing something wrong As you can see, the way we choose the object we want to modify is by giving it's primary key BUT where do put this primary key? Is there a special param? Do we need to make a param or is there an other way? I am using the python requests library and I normally do the following when I need to create a new object (NOTE that my post method is pre-configured for image upload with multiparse and stuff.) like this response = … -
I am trying to create django rank model field which depends on score
class Sport(models.Model): score = models.PositiveIntegerField() rank = models.PositiveIntegerField() If the score is high rank is 1 and if the score is low rank is also low.not able to write a model for this can anyone help me with this -
how to pass django variable inside quotes?
I would like to change the photo on the sliders and for this I created the SliderImage model, in index.html I want to pull out the pictures using a loop, but it uses an unfamiliar tag for me and tried to pass the variable in quotes inside STATIC, but to no avail, I get this /static/%7B%7B%20slider.get_absolute_image_url%20%7D%7D" style="background-image: url("/static/%7B%7B%20slider.get_absolute_image_url%20%7D%7D");"> index.html {% for slider in slider %} <div class="hs-item set-bg" data-setbg="{% static '{{ slider.get_absolute_image_url }}' %}"> <div class="container"> <div class="row"> <div class="col-xl-6 col-lg-7 text-white"> <span>New Arrivals</span> <h2>denim jackets</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Quis ipsum sus-pendisse ultrices gravida. Risus commodo viverra maecenas accumsan lacus vel facilisis. </p> <a href="#" class="site-btn sb-line">DISCOVER</a> <a href="#" class="site-btn sb-white">ADD TO CART</a> </div> </div> <div class="offer-card text-white"> <span>from</span> <h2>$29</h2> <p>SHOP NOW</p> </div> </div> </div> {% endfor %} models.py from django.conf import settings from django.db import models class SliderImage(models.Model): img = models.ImageField(upload_to='media/slider_photo/', verbose_name='Photo') @property def get_absolute_image_url(self): return "{0}{1}".format(settings.MEDIA_URL, self.img.url) def __str__(self): return "{}".format(self.img) views.py def index(request): slider = SliderImage.objects.all() return render(request, 'main/index.html', {'slider': slider}) -
Uploading images without ModelForm
I am creating a page for adding products to the web shop by the user, and I am having troubles with uploading images. I have a form with an <input type="file"> and after selecting the files, the files (images) should be temporarily uploaded to the server. After the upload is complete, image preview should be displayed. During the upload, loading spinner GIF with client-side progress indication should be displayed too, along with the option to cancel the upload. Each uploaded image should have an option to be deleted, once uploaded. Because of all this and other reasons, I'm not using a ModelForm, but creating everything manually. So, my plan is to attach an onchange listener to that input, and upon files selection, a POST XMLHttpRequest would be sent from JavaScript, which would call a view that would save the images into some kind of table for temporarily uploaded images, and the ID of the row would be something like request.session.session_key, but a little bit different. My issue with this approach is generating that session key, which should be unique and it should last as long as the page is opened. So, refreshing the page would mean generating a new key. … -
Getting data from a POST request
POST data not always making to my logic, despite updating the django model properly def new_record(request): form = RecordForm(request.POST or None) if request.method == 'POST': if form.is_valid(): form.save() return HttpResponseRedirect('/new_record') else: form = RecordForm() item1 = request.POST.getlist('checkbox_1') item2 = request.POST.getlist('checkbox_2') item3 = request.POST.getlist('checkbox_3') print(item1) print(item2) print(item3) if 'on' in item1: print("Checkbox 1 is true") write_pdf_view(textobject='textobject', exam_record_number='123') else: print("Checkbox 1 is False") if 'on' in item2: print("Checkbox 2 is true") else: print("Checkbox 2 is False") if 'on' in item3: print("Checkbox 3 is true") else: print("Checkbox 3 is False") return render(request=request, template_name='main/new_record.html', context={"form": form} ) What I'm hoping to do is basically check if a checkbox is selected and pass a value into a function if this is true, for now I've fixed y write_pdf_view values to something I know exists and that's not working either (I imported that above) I feel like this might be trivial for someone with experience, I'm a new hobbyist just looking to learn! Any help much appreciated. -
How to effectively sort or filter objects on a site page?
I have an online store website written in django. I want to add sorting (and filters) to the product page by various parameters. How to do it effectively? 1) Store several databases already sorted (by date, by popularity, etc.). 2) Sort when prompted from the database. -
What is a good User content management system for both Backend & Frontend?
For a school project, we are doing a website (React & Django Rest Framework) where any user can upload content (audio / picture) inside Albums that they created in first place. Currently, we use DigitalOcean Spaces as Django Storage Backend as our provider. Which works well, but when we load the images on the Front (React), it's SUPER SLOW which is why I'm adressing you this message right now. So, my question is, what would be the strategy, on the backend first (provider, endpoints, urls, ...) and then on the frontend (request placeholder after having the first URL returned by our backend ? ). The ideal goal is to have the same experience than Pinterest but with Medium-like loading state (small image, expanded and blurred while loading the full res one) ? Thanks in advance ! -
Running integration tests separately from unit tests in django
The convention for creating tests in django is to place tests in modules named tests_*.py and to run then as python manage.py test. This will run all tests defined tests in all modules named tests. The challenge I have come across is that integration tests may require significant setup of resources e.g. connection to external services. I would imagine mocking out those services in integration tests would cause integration tests to loose their meaning. I am inquiring therefore of the best practice in running only unit tests and only run integration tests when unit tests are running properly. The only way I can imagine is to place integration tests in files named with a different pattern such as integration_*.py and then use the pattern parameter when running integration tests as specified by the django documentation Like this python manage.py test --pattern="integration_*". In this way when python manage.py test is called integration tests will be ignored. Does anyone have a suggestion or recommendation. -
How can I make a view for a section of Index.html separately?
So, I have a website where the user clicks "my blog" on the navbar, which scrolls down to that section of the index.html (ex. 8000/#blog-section). I already have the Contact form working on the index page. Now I am trying to create the blog logic to render out three blog posts, but it is showing up blank? Can I create a separate view for the same "index.html" page? Views.py def index_view(request): posts = Post.objects.all().order_by('-created_on') context ={ 'posts': posts, 'name': name, } form = ContactForm if request.method == 'POST': form = ContactForm(data=request.POST) if form.is_valid(): # Send email goes here name = request.POST.get('name') subject = request.POST.get('subject') email = request.POST.get('email') message = request.POST.get('message') template = get_template('contact_form.txt') context = { 'subject': subject, 'email' : email, 'message' : message } content = template.render(context) email = EmailMessage( "Message from Portfolio", content, "New inquiry | Portfolio" + '', ['myemail@gmail.com'], headers = {'Reply to': email} ) email.send() return HttpResponseRedirect("/") return render(request, 'index.html', {'form': form}, context) Urls.py /blog from django.urls import path from . import views urlpatterns = [ path("", views.blog_index, name="blog_index"), path("<int:pk>/", views.blog_detail, name="blog_detail"), path("<category>/", views.blog_category, name="blog_category"), ] Urls.py /portfolio from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from …