Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django testing hangs with --keepdb flag
For performance tuning reasons, I want to run Django tests against a copy of my production database. As I understand it, this should be possible by: (1) adjusting Django settings like DATABASES = { 'default': { ... 'TEST': { 'NAME': 'my_database_copy', }, } } and (2) using the --keepdb flag, as in python manage.py test --keepdb.[1] But when I do this, the process hangs, looking like this: bash-4.2$ python manage.py test --keepdb Using existing test database for alias 'default'... (The process won't close with ctrl+c. I'm using Docker, and I stop it by restarting Docker.) There are no unapplied migrations for the database, and the test command (python manage.py test) works fine, if --keepdb is omitted. I confirmed that the database copy is properly restored and accessible because I can access it when I run python manage.py shell. [1] https://docs.djangoproject.com/en/3.1/topics/testing/overview/#preserving-the-test-database -
Line number: 1 - 'id
Estoy intentando importar y exportar registros desde el admin de django y si me exporta el archivo pero cuando abro el archivo estA en blanco a pesar de que hay registros en los datos del modelo que quiero exportar Y cuando quiero importar me aparece esto: Line number: 1 - 'id' Traceback (most recent call last): File "c:\PYTHON\DJANGO\Truelogisticinc\.env\lib\site-packages\import_export\resources.py", line 639, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "c:\PYTHON\DJANGO\Truelogisticinc\.env\lib\site-packages\import_export\resources.py", line 334, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "c:\PYTHON\DJANGO\Truelogisticinc\.env\lib\site-packages\import_export\resources.py", line 321, in get_instance import_id_fields = [ File "c:\PYTHON\DJANGO\Truelogisticinc\.env\lib\site-packages\import_export\resources.py", line 322, in <listcomp> self.fields[f] for f in self.get_import_id_fields() KeyError: 'id' model.py # DJANGO from django.db import models # Models from django.contrib.auth.models import User from users.models import Profile from records.models import Customers, Origins, Airlines, Warehouse, Grades, Products #from auth.models import user # Create your models here. class PackingLists(models.Model): #Packing Lists models.''' #Registers number_lote = models.CharField(max_length=45) order_date = models.DateField(auto_now_add=True) #Descriptions ship_date = models.DateField() awb_number = models.CharField(max_length=45, null=True, blank=True) id_fish = models.IntegerField() box_number = models.IntegerField() product = models.ManyToManyField(Products) weight = models.FloatField() size = models.CharField(max_length=20) origin = models.ForeignKey(Origins, on_delete=models.CASCADE, null=False, blank=False, related_name='pls_origins') ship_via = models.ForeignKey(Airlines, on_delete=models.CASCADE, null=False, blank=False, related_name='pls_shipsvia') warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE, null=False, blank=False, related_name='pls_warehouses') grade = models.ForeignKey(Grades, on_delete=models.CASCADE, null=True, blank=True, related_name='pls_grades') #user = … -
How to run django through pypy?
(venv) PS E:\trydjango\myblog> pypy3 manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\hp\AppData\Local\Programs\pypy3.6-v7.3.1-win32\site-packages\django\db\backends\sqlite3\base.py", line 67, in check_sqlite_version raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.6.21). -
how do i solve problem of receiver django?
i use two reciver but one of them is worked i dont now whats problem (Create_QueueSendProject reciver is worked but Create_QueueSendProject not work ) class Category(models.Model): title = models.CharField(max_length=254) creation_date = models.DateTimeField(auto_now_add=True) modification_date = models.DateTimeField(auto_now=True) class Meta: db_table = 'Category' def __str__(self): return str(self.title) class Project(models.Model): def get_upload_path(self, filename): return "{}/project_file/{}/{}".format(self.user.id,"prjid_"+self.id,filename) confirmation_choices = ( (ProjectConfirmationStatus.REJECTED, "Rejected"), (ProjectConfirmationStatus.ACCEPTED, "Accepted"), (ProjectConfirmationStatus.PENDING, "Pending") ) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) body = models.TextField (blank=False, null=False) file = models.FileField(upload_to=get_upload_path,max_length=254,null=True, blank=True,) category = models.ManyToManyField(Category, blank=True) confirmation_status = models.CharField(max_length=1, choices=confirmation_choices, default=ProjectConfirmationStatus.PENDING) description = models.TextField(default=None,blank=True, null=True) creation_date = models.DateTimeField(auto_now_add=True) modification_date = models.DateTimeField(auto_now=True) class Meta: ordering = ['creation_date'] db_table = 'Projects' def __str__(self): return 'id:{}-{}'.format(self.id,self.body[0:20]) class QueueSendProject(models.Model): project = models.OneToOneField(Project,on_delete=models.CASCADE) is_send = models.BooleanField(default=False) creation_date = models.DateTimeField(auto_now_add=True) modification_date = models.DateTimeField(auto_now=True) class Meta: db_table = 'Queue_send_projects' def __str__(self): return str(self.id) @receiver(post_save, sender=QueueSendProject) def Create_QueueSendProject(sender, instance, created, **kwargs): """send project in chanel telegram """ # import pdb; pdb.set_trace() if created : print("yessssssssss")#Not work instance.is_send=True instance.save() @receiver(post_save, sender=Project) def Create_QueueSendProject(sender, instance, created, **kwargs): """create QueueSendProject for project if confirmation_status update to ACCEPTED""" # import pdb; pdb.set_trace() if not created : if instance.confirmation_status==ProjectConfirmationStatus.ACCEPTED: queuesend_obj = QueueSendProject.objects.update_or_create(project=instance) -
How to migrate local Django model changes to production?
I'm attempting to migrate my local changes to my public production site Django site. The problem I am having is my local changes overwrite my production models, when I upload my local changes to production. Is their a way to merge my changes without totally ruining my production models. Is there a library that I can use that will better help me manage conflicts between the two code bases? -
get_queryset does not affect querying in django rest framework ModelViewSet
My ViewSet looks like this: class ClientViewSet(viewsets.ModelViewSet): queryset = models.Client.objects.all() serializer_class = serializers.ClientSerializer def filter_queryset(self, queryset): return models.Client.objects.filter(**self.request.data) def get_queryset(self): return models.Client.objects.filter(owner=self.request.user) The model looks like this: class Client(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return str(self.id) So, I'm trying to filter clients so that only the current user's clients are presented to them. However, GET api/clients still returns all the clients of all users. What have I done wrong? -
moduleNotFoundError: No module named 'booktime.main'
following a book, I created a django project named booktime then an app named main. as I try importing files within the app such as forms.py as in from main import forms the names main and forms are red-underlined, though works in some cases as in views.py where the server runs still but on running tests file I get no module named 'booktime.main' error -
How to use variables tag from Django in HTML ids
My issue is actually quite simple and I'm not sure that there is an answer to it but still. I'm trying to reduce some image rendering that is hardcoded into my HTML template by making a simple for loop that Django provides with a dict comprehension. Actually everything is working in my project even if the "id" is not equal to the value "for" of my label. Here are my code and a screenshot of it that in lights far better my issue that the whole code. <div class="form-check"> {% for data in images %} <input class="form-check-input invisible" type="radio" name="image" id="{{ data }}" value="media/{{ data }}" > <button type="button" class="btn btn-outline-success"><label class="form-check-label" for="{{ data }}"> <img class="rounded-circle account-img" src="media/{{ data }}" width="120" height="120"> </label></button> {% endfor %} <input class="form-check-input invisible" type="radio" name="image" id="Profil1.png" value='media/Profil1.png' > <button type="button" class="btn btn-outline-success"><label class="form-check-label" for="Profil1.png"> <img class="rounded-circle account-img" src="{{ "media/Profil1.png" }}" width="120" height="120"> </label></button> <input class="form-check-input invisible" type="radio" name="image" id="Profil2.png" value='media/Profil2.png' > <button type="button" class="btn btn-outline-success"><label class="form-check-label" for="Profil2.png"> <img class="rounded-circle account-img" src="{{ "media/Profil2.png" }}" width="120" height="120"> </label></button> <input class="form-check-input invisible" type="radio" name="image" id="Profil3.png" value='media/Profil3.png' > <button type="button" class="btn btn-outline-success"><label class="form-check-label" for="Profil3.png"> <img class="rounded-circle account-img" src="{{ "media/Profil3.png" }}" width="120" height="120"> </label></button> <input class="form-check-input invisible" type="radio" … -
{"detail":"Not found."} It could like comments but it couldn't like the replies
I have a problem on my project. I am trying to solve it all the day today but no luck. I am trying to make a POST-COMMENT-LIKE blog. The LIKE system works pretty well on Posts and Comments but it break when i am trying to like the replies of the comments. When i trying to like the reply it shown the message {"detail":"Not found."}. Any help for this?? Thank you!! :) The models.py: class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') parent = models.ForeignKey("self", null=True, blank=True, on_delete=models.CASCADE) comment_like = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='comment_like') content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) objects = CommentManager() def children(self): return Comment.objects.filter(parent=self) def get_api_url(self): return reverse("comments-api:thread", kwargs={"pk": self.pk}) def get_comment_like_url(self): return reverse("comments-api:comment-like-toggle", kwargs={"pk": self.pk}) # def get_content_type(self): # instance = self # content_type = ContentType.objects.get_for_model(instance.__class__) # return content_type @property def is_parent(self): if self.parent is not None: return False return True The serializers.py : class CommentDetailSerializer(ModelSerializer): user = UserDetailSerializer(read_only=True) reply_count = SerializerMethodField() content_object_url = SerializerMethodField() replies = SerializerMethodField() comment_like = SerializerMethodField() comment_like_by = SerializerMethodField() class Meta: model = Comment fields = [ 'id', 'user', #'content_type', #'object_id', 'content', 'reply_count', 'replies', 'timestamp', 'content_object_url', 'comment_like', 'comment_like_by', ] read_only_fields = [ … -
Django :app is not a registered namespace
I am very new to Django and want to know the reason behind the error "No Reverse Match" in my app.Also want to know why it was telling namespace is not registered? -
I have confusion adding/linking HTML multiple pages to my Django website
I am new to Django web development. I have successfully created an index.html page and it viewed on 127.0.0.1:8000 successfully. But the problem now is I have to link multiple pages, for example an about and contact section. I created about.html and contact.html pages in the same directory where my index.html page is. But when i click on about or contact page, it is not showing. How can I link these pages to my website? -
Django ORM: Bulk Create : More than one sql query
In the django documentation it is mentioned that bulk create generally executes one query This method inserts the provided list of objects into the database in an efficient manner (generally only 1 query, no matter how many objects there are) django documentation What are the scenarios in which django will create more than one query and are these queries executed atomically. -
Django ImageField has no url attribure associated with it
I'm trying to create a one page app where you can upload a picture to the database and it would display it in the index page. I can't get the photo to display, even though when calling in the html part {{post.picture}} it returns the path of the picture media settings: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' view: from random_tasks_app import forms from random_tasks_app.models import Post def index(request): posts = Post.objects.all() if request.method == 'POST': form = forms.UploadImageForm(request.POST, request.FILES) if form.is_valid(): form.save() else: form = forms.UploadImageForm() return render(request, 'index.html', {'form': form, 'posts' : posts}) models: from django.db import models class Post(models.Model): picture = models.ImageField(upload_to='photos/', blank=True, null=True) forms: from django.forms import ModelForm from random_tasks_app.models import Post class UploadImageForm(ModelForm): class Meta(): model = Post fields = '__all__' html file: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <form method = "POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> {%for post in posts%} <img src="{{ hotel.picture.url }}"/> {%endfor%} </body> </html> The error: raise ValueError("The '%s' attribute has no file associated with it." % self.field.name) ValueError: The 'picture' attribute has no file associated with it. thanks. -
Django open link which does pre-set things (click "men" on e-ccomerce site and have it automatically filter on men's clothing
Sorry about the rubbish title, I wasn't sure what to put, if anyone has any improvements, please comment and I will update accordingly. Problem I currently am working on an e-commerce website, and have finished setting up the shop section (where you can view products and filter based on your needs), now on the navbar and other locations, I have names such as "Men" or "Women", What I need is that these links go to the shop page and automatically filter based on the link So if I click "men", it should go to the shop page, and return back the items already filtered showing men's products (preferably all the options inside of the men category should already be ticked, but this is not necessary). Then you can carry on adjusting your filter as required as if you clicked on the shop page directly. Soulutions Tried First of all, I tried to set up a system where you can use a dynamic URL to see the link coming from, for example, "shop/women", but this would need be exactly the same as "shop/" just with the filtering, I tried to add this into my urls.py file like this path('shop/<str:category>', Shop.as_view(), name="shop"), … -
Django Rest Framework: How to ignore 'unique' primary key constraint when validating a serializer?
I am attempting to store large amounts of transit data in a PostgreSQL database, where a client uploads multiple records at a time (in the tens of thousands). I only want one arrival time per stop, per route, per trip and the unique identifier for that stop, route, and trip is the primary key for my table (and a foreign key in a different table). I am trying use Django's update_or_create in my serializer to either create the entry for that arrival time or update the arrival time with the latest data if it already exists. Unfortunately, while calling is_valid() on my serializer, it identifies that the repeat records violate the uniqueness constraint of the primary keys (which makes sense), giving me this error message: 'real_id': [ErrorDetail(string='actual with this real id already exists.', code='unique')] I want to override this behavior since if the primary key isn't unique it will just update the entry. I have already tried looping over and removing validators like so: def run_validators(self, value): for validator in self.validators: self.validators.remove(validator) super(ActualSerializer, self).run_validators(value) I have also tried removing all validators using the extra_kwargs field of my serializer Meta class like so: extra_kwargs = { 'name': {'validators': []} } I … -
React-Native and Django Rest Framework problem
I have rode that is not necessary the token in mobile app, but i have in the same back end a web app, so if i disable the Token in Django, the web app will not work. -
djangobyexample book - jquery bookmarklet not working
I'm working through Django By Example and in one chapter a jQuery bookmarklet is built within a Django app so that a user can easily save jpg images from a website into their user profile area within the Django app. The tutorial does give exact instructions on what to do which I have followed and although I have managed to get the bookmarklet button to appear in my bookmarks bar in Chrome, nothing happens when I click it when browsing a webpage with jpg images. This is my local Django dashboard where the bookmarklet button is added to the bookmarks bar and this part works fine. dashboard and this is how it must look like when clicked on the bookmarklet, this is the part where nothing happens for me when I clicked on bookmarklet. (how to solve this?) result After I dragged Bookmark it! button to my bookmarks toolbar and opened HTTP site i saw that button doesn't work. In the developers tool/console i have an error Uncaught SyntaxError: Unexpected end of input and this info in console. console error These are the relevant js files https://github.com/davejonesbkk/bookmarks/blob/master/images/templates/bookmarklet_launcher.js https://github.com/davejonesbkk/bookmarks/blob/master/images/static/js/bookmarklet.js The JavaScript launcher is getting called through a Django template tag "include" … -
session meaning in programming and OS
can someone make it clear the idea of representing "session" in programming(django(cuze this question created in my mind in the progress of coding with django)) and OS concept. -
Bad request error when fetching files from AWS with django
I'm creating a website and I'm ready to put it into production. I have chosen to use AWS to host my static files and it's being a little weird about serving up files. I may just be doing things completely wrong. Here's my settings (I do have the correct keys and domain names but I edited them out for security) """ Django settings for lunaSite project. Generated by 'django-admin startproject' using Django 3.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*******************************' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ # Default 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Custom "home", "blog", "reviews", "pages", "gallery", #Third Party "storages", ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'lunaSite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ["templates"], … -
Invalid block tag 'Static...' Django 3.1
I hope my message finds you well. I have this error: Invalid block tag on line 8: 'Static'/Style/style.css'', and I followed all the solutions I found here and it didn't work. enter image description here enter image description here enter image description here enter image description here -
Mocking for requests.Session.get
I have a new management command that grabs a csv from a url and saves it locally, then does some stuff with it afterward and deletes it. Here's where I retrieve it in my "download code": url = 'http://blahblahblah/output.csv' with requests.Session() as s: download = s.get(url) csv = open('temp_fallback.csv', 'wb') csv.write(download.content) # this works for url tests but not mock csv.close() It's working great for the real url, and things are peachy. I wrote a couple unit tests calling my management command and they're working, but now I'm adding a unit test to use a mocked response instead of hitting the live url. I'm trying it like so, where I'm hoping to substitute what happens for requests.Session.get): @patch('requests.Session.get') def test_mock_pass(self, mock_response): """ Test using mock response """ test_response = { 'content': 'bunch_of_content_here' 'status_code': 200, 'encoding': 'ISO-8859-1', 'reason': 'OK', 'elapsed': 'OK' } mock_response.return_value = test_response print("mock_response.return_value['content'] has: ", mock_response.return_value['content']) try: call_command('download_fallback_csv') except CommandError as e: self.fail("Failed download csv. {}".format(e)) But something is different between the response I get when calling the url vs the response I'm trying to mock: the tests work fine that use the url, but this mocked test fails during the csv.write with: "AttributeError: 'dict' object has no … -
Django filtering a model query with filter method
Why does this code: products_model = Product.objects.filter(sub_category__name__iexact=sub) supplier_filter = SupplierFilter(request.GET, queryset=products_model) products = supplier_filter.qs Give me this error: Field 'id' expected a number but got 'BYGGMAX'. Ive had trouble with this alot now. Can someone explain whats goin on. When i use the filter method its more complicated to filter the model, how so? Really interested in learning more on how this works. -
'django-admin' is not recognized as an internal or external command , pycharm
I don't know what is the problem but I downloaded Django and when I try to make a a Django project it creates this problem i tried several ways to make it work but nothing worked. 'django-admin' is not recognized as an internal or external command, operable program or batch file. -
Django: Getting the page an object is on
Let's say I have a class Foo. I want to know what page a particular instance of Foo will be on: eg: api.myapp.com/foos/?page=25. Given an object: Foo.objects.get(id=500), how can I determine what page my instance will be on? -
When don't we use "__all__" in ModelSerializer in Django Rest Framework
This is just my curiosity but I will be very happy if anyone answers my question. I am using Django Rest Framework but I'm a beginner. In serializers.py, I use ModelSerializer and "all" to fields attribute. This is an example. class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = "__all__" And then, I just thought when don't we use "__all__" in serializers.py?? As long as we create models.py in advance, I think we usually use all fields in each Model. I would like you to teach me when we omit specific fields that come from each Model. Thank you.