Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to tell Django not to use the cache for a request?
I am using Django's caching framework with Memcached: https://docs.djangoproject.com/en/2.2/topics/cache/#django-s-cache-framework It's working great. The only issue I am having is sometimes, I want to make a request to my Django server and tell it to bypass the cache. But I couldn't find any documentation on this. How do I make a request to a Django server and tell it to not use the cache for this particular request? -
Django: AttributeError: 'MoneyField' object has no attribute 'related_model'
When I run the command: python manage.py migrate I got the error: AttributeError: 'MoneyField' object has no attribute 'related_model'. I try to found something with related_model I a didn't find anything. Is it possible to log any error from when runs Django Migrations or get more details about the error? -
How to make a filter of a child model to another child model?
I'm close to do a very "clean" model in Django. Person is a child of Entity. With field user added. Profession is a child of Activity with custom manager to filter Activity of type 'profession' (hard-coded type) You can do something like: Entity.objects.filter(activities__activity_type__name='profession') It works. But we can do cleaner: Person.objects.filter(activities__activity_type__name='profession', activities__name="the job") It works. What I would like to do is: Person.objects.filter(professions__name="the job") Is there a way to do this? I can't find out how to query all the persons (not entities) who have a specific Profession class Entity(BaseModel): is_physical = models.BooleanField(default=True) class PersonManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_physical=True) class Person(Entity): objects = PersonManager() user = models.OneToOneField(User, blank=False, null=False, on_delete=models.CASCADE) And for the Profession model class Activity(BaseModel): name = models.CharField(max_length=200, blank=True, null=True) activity_type = models.ForeignKey(ActivityType, on_delete=models.CASCADE, blank=True, null=True) class ProfessionManager(models.Manager): @cached_property def activity_type_profession(self): try: return ActivityType.objects.get(name__iexact='profession') except ActivityType.DoesNotExist: return None def get_queryset(self): return super().get_queryset().filter( activity_type=self.activity_type_profession) class Profession(Activity): objects = ProfessionManager() -
29/5000 combobox with filter in /admin.py
Afternoon guys, I need a help Have APP model "box" in it I have a Professional FK I have another APP model with the "Professional" and in it I have a FK Specialties In my Admin "Box" appears the combobox with the Pros but I don't know how to make the specials combo appear. Note ... this combo with "Professional" specialties has to appear because a Professional can have more than one specialty In short ... when I choose the professional has to appear the combo with his specialties registered in my localhost / admin / .... -
django last_executed_query: what is the purporse of the sql, params paremeters passed in the function
I am working on a Django project and using Postgresql as database. I wanted to know what does sql, params do in the below function which i found at /lib/python3.7/site-packages/django/db/backends/postgresql/operations.py def last_executed_query(self, cursor, sql, params): # http://initd.org/psycopg/docs/cursor.html#cursor.query # The query attribute is a Psycopg extension to the DB API 2.0. if cursor.query is not None: return cursor.query.decode() return None I found it being used at https://stackoverflow.com/a/47542953/2897115 def str_query(qs): """ qs.query returns something that isn't valid SQL, this returns the actual valid SQL that's executed: https://code.djangoproject.com/ticket/17741 """ cursor = connections[qs.db].cursor() query, params = qs.query.sql_with_params() cursor.execute('EXPLAIN ' + query, params) res = str(cursor.db.ops.last_executed_query(cursor, query, params)) assert res.startswith('EXPLAIN ') return res[len('EXPLAIN '):] Since (sql, params) or here (query, params) are not being used then last_executed_query return the same as connections[qs.db][queries][-1] -
Django-cms, children variable in template, page navigation doesn't show in newer version
I'm trying to run project using Django-cms 3.6.0. It was created using Django-cms 2.3.8, I'm trying to use the old code. In this new version the menu with subpages links doesn't appear. children variable in template doesn't seem to contain anything. I expect it to show links to 4 subpages of a page. I've added pages manually in admin UI in new version of django-cms. subbase.html: {% extends "base.html" %} {% load i18n %} {% load menu_tags cms_tags %} ... {% block left_menu %} <nav id="lMenu"> {% show_menu 1 1 0 1 "menu/sub_menu.html" %} {% block left_content %}{% endblock left_content %} </nav> {% endblock left_menu %} sub_menu.html: {% load menu_tags %} <ul class="subMenu"> {% for child in children %} <li><a href="{{ child.attr.redirect_url|default:child.get_absolute_url }}" title="{{ child.get_menu_title }}">{{ child.get_menu_title }}</a></li> {% endfor %} </ul> I've checked in database, using manage.py shell, that those pages has child pages: from cms.models.pagemodel import Page pages = Page.object.all() children = pages[2].get_descendant_pages() And now, e.g., calling pages[2].get_menu_title(), children[0].get_menu_title() returns expected proper names of the pages, as added through UI. I haven't found much about this children variable in docs. Should this still work this way in 3.6? What is the proper way to refer to child pages … -
excluding html elements with reportlab and django?
I have a page where users may want to download as PDF but I want to exclude the footer and the navbars so i saw the docs mentioned something like this import io from django.http import FileResponse from reportlab.pdfgen import canvas def some_view(request): # Create a file-like buffer to receive PDF data. buffer = io.BytesIO() # Create the PDF object, using the buffer as its "file." p = canvas.Canvas(buffer) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.drawString(100, 100, "Hello world.") # Close the PDF object cleanly, and we're done. p.showPage() p.save() # FileResponse sets the Content-Disposition header so that browsers # present the option to save the file. buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename='hello.pdf') but how can I exclude elements? -
How to compress images in front end before uploading to server?
I am making a small django website for image hosting and I have a bandwidth problem. Is there any way to implement image compressor in front end before uploading to website. Will image compressor work in Mobile browser? -
django object creation - how does it create an object?
I have 2 functions and i'm wondering if they are equivalent def get_action(payment): payment_action = PaymentAction.objects.create( payment=payment, status=status, metadata=kwargs ) payment.status = status payment.save() return payment_action ______________________ def get_action(payment): payment.status = status payment.save() return PaymentAction.objects.create( payment=payment, status=status, metadata=kwargs ) My concern is, in the first case the payment action with the updated payment isn't WRITTEN INTO the db. Like, i have to explicitly call payment_action.save() at the end for it to be equivalent to the second snippet. Could someone please clarify? -
How can I render only the attributes of my model in returned JSON?
I'm using Python 3.7 and Django. I have a view that returns the following # Ajax request that returns articles with similar words in the titles def get_hints(request): ... s = ArticlesService() objects = s.get_hints(article) data = serializers.serialize('json', objects) return HttpResponse(data, content_type="application/json") The "get_hints" method returns an array of model objects. The thing is, on the Javascript side, the JSON is returned like so ... [{model: "mydb.article", pk: 60945, fields: { title: "Cooking Eggplant", path: "https://thecookingblog.com/abcde", label: "" }, ...] Is there a way to have the JSON returned without the "model" and "fields" and just have the object's attribute returned as more traditional JSON, e.g. { title: "Cooking Eggplant", path: "https://thecookingblog.com/abcde", label: "" } ? -
Why getting "Apps aren't loaded yet." error when import app models to another app in django
In a django project, I try to import classes from my app 'catalog' into another app named 'planning'. In the app 'planning', there's a python script that do query to MySQL DB defined in 'catalog' app. However, still getting the django error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet For the discussion herein, I simplified the projet path to '...' and projet name to "project_name" I looked several stackoverflow posts related to that similar issue, but none of the proposed solutions work in my case. Somebody know what I miss? (I'm using PyCharm community) • All apps in INSTALLED_APPS • virtualenv activated • all __init__.py files are empty • no circular relation between the apps 'catalog' and 'planning' • I added the following in the environment variables: DJANGO_SETTINGS_MODULE=project_name.settings • I tried to execute from a standalone script exec(open('.../run_script.py).read()) • I tried adding the following script: if __name__ == '__main__': import sys, os, django path = "path/to/project" if path not in sys.path: sys.path.insert(0, path) from django.conf import settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings") django.setup() main() The only way I was able to import the 'catalog' app w/o error and do query from 'planning' app is manually through: python manage.py shell Here's the traceback obtained from every … -
How to customize the validation error messages of ModelSerializer?
I made a serializer named RegistrationSeriaizer that inherits ModelSerializer. and I want to custom default error messages generates by the serializer. I want to make validation generated by ModelSrializer to return a my custom error messages. not the default. # This is my model. class Person(AbstractBaseUser): """ A custom User model that represents users """ GENDER_CHOICES = [ ('M', 'Male'), ('F', 'Female'), ] first_name = models.CharField(_("First name of User"), max_length=50) last_name = models.CharField(_("Last name of User"), max_length=50) country_code = CountryField(_("Country code of User"), max_length=10) # Using phonenumber_field third package to # define phonenumber in E.164 format phone_number = PhoneNumberField(_("Phone number of User"), unique=True) gender = models.CharField(_("Gender of User"), max_length=1, choices=GENDER_CHOICES) birth_date = models.DateField(_("Birth date of User")) avatar = models.ImageField(_("Image of User"), upload_to='images/') email = models.EmailField(_("Email of User"), blank=True, unique=True, max_length=255) objects = PersonManager() USERNAME_FIELD = 'phone_number' REQUIRED = [ 'first_name', 'last_name', 'country_code', 'gender', 'birth_date', 'avatar', ] def __str__(self): return self.first_name + ' ' + self.last_name # This is my serializer class RegistrationSerializer(serializers.ModelSerializer): class Meta: model = Person exclude = ['last_login'] I want the validation error messages to look like this. { "errors": { "first_name": [ { "error": "blank" } ], "last_name": [ { "error": "blank" } ], "country_code":[ { "error": … -
Unable to import Celery after deploying to Azure
Probably a very familiar story with predictable outcome and this will be a Path issue, but I'm at a loss to track it down. Very simple Django app using Celery (current incarnation doesn't even attempt to run Tasks, I'm only trying to get the Django app running with the Celery module imported). As per standard instructions. The __init__.py file for my project contains from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery_setup import app as celery_app __all__ = ('celery_app',) Note that the usual celery.py is renamed celery_setup as other post suggested this may be a cause of the import issues. In celery_setup.py the offending import statement is: from celery import Celery Running locally using a venv no issues at all and the Celery module is picked up and loaded. However after deploying to an Azure WebApp I can watch the log messages hitting the wsgi.py file only to bail out when it looks for the Celery module. This is giving and error of: ImportError: cannot import name 'Celery' from 'celery' (/home/site/wwwroot/antenv/lib/python3.7/site-packages/celery/__init__.py) Using Kudu I can verify that this path exists and … -
django does not change the login page
I changed the database drastically with django. Then we migrated and confirmed that the table was created. If you try to log in to the management screen as a superuser after starting the server, the screen will not change. It reacts when the wrong password is entered. The server was restarted and postgre was also reinstalled. But it does not change. It will look like you've been waiting for a long time. -
form fail to save data to database with foreign key
my second view 'team' is not saving to database, can somebody tell what am doing wrong. i am having this problem with any form am creating from model forms with foreign key even through i have passed the related parent field data through the URL. def startup(request): if request.method == 'POST': form = StartupNameForm(request.POST) if form.is_valid(): result = form.save() return redirect('str_team', startup_id = result.pk) else: form = StartupNameForm() return render(request, 'application/str_name.html', {'form': form}) def team(request, startup_id): stup = Startup.objects.get(id=startup_id) if request.method=='POST': form = TeamForm(request.POST or None) if form.is_valid(): instances = form.save(commit=False) for instance in instances: instance.startup_id = stup.id instance.save() return redirect('str_dashboard') else: form = TeamForm () return render(request,'application/str_team.html', {'form':form}) from django.urls import path from . import views urlpatterns = [ path ( 'str_dashboard/' , views.str_dashboard , name = 'str_dashboard' ) , path ( 'application/' , views.startup, name = 'str_name' ) , path ( 'application-1/<int:startup_id>' , views.team, name = 'str_team' ) , ] -
How to change the view of a list item
I am using Django, and within my models.py, I created some lists. My project is about car entry and exit control. So I created a specific list for when the user requests a car, it has the following states: "Waiting, Confirmed or Denied". I need to know how to change these states when certain events happen, such as the request is denied or approved. This is a part of my models.py code: SITUATION = [ ("WAITING", "WAITING"), ("DENIED", "DENIED"), ("CONFIRMED", "CONFIRMED") ] class RequestCar (models.Model): id = models.AutoField (primary_key = True) secretary = models.CharField (max_length = 15, choices = SECRETARIES) dateTimeReserve = models.DateTimeField (auto_now_add = True, db_column = 'date_time_reserve') dateExit = models.DateTimeField (verbose_name = 'Expected Exit Date', db_column = 'exit_date') exitTime = models.CharField (max_length = 3, verbose_name = 'Expected Exit Time', choices = TIME) requester = models.CharField (max_length = 50) email = models.EmailField () numPassengers = models.IntegerField (verbose_name = 'Number of Passengers', db_column = 'num_pasage') reason = models.CharField (max_length = 150) itinerary = models.CharField (max_length = 50) expectationTime = models.CharField (max_length = 7, verbose_name = 'What is the expected time of absence?',choices = TIME) driverAwait = models.CharField (max_length = 3, verbose_name = 'Does the driver wait in place?',choices = DRIVER_AGUARD, … -
Adding new header to existing default HTTP header in all requests made from front end to backend
I am working on DJANGO what i want is to add a javascript which takes in the every request going to server and add new additional header to it so that i can extract that value on server side in django and use it. -
Django modelformset custom saving and declarative fields
My modelformset_factory uses the Rate model: class Rate(models.Model): rate = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True ) UOM = models.ForeignKey(UOM, related_name = 'UOM_rates', blank = True, null = True, on_delete = models.SET_NULL) Here is my RateForm modelform: class RateForm(ModelForm): ''' Modelform for ServiceRate model ''' costcode = forms.CharField(max_length = 40) # declaratively defined field class Meta: model = Rate fields = ['costcode', 'rate', 'UOM', ] class BaseRateFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): project = kwargs.pop('project') super(BaseRateFormSet, self).__init__(*args, **kwargs) relevant_rates = self.queryset = Rate.objects.filter(<some_filter_conditions_having_to_do_with_project>) def save(self, commit = False, *args, **kwargs): project = kwargs.pop('project') instances = super(BaseRateFormSet, self).save(commit = False, *args, **kwargs) The problem I have is how do I get the costcode for each form in the modelformset to relate to the Rate? Usually, in the custom save method, we would want to say something to this effect: for instance in instances: # Custom saving behavior # Need to access form in self.forms corresponding to the instance in instances! Note that a costcode is a model related to Part model (not shown here to keep the setup less complicated) in the project, so I'd like to create the costcode given the user input and relate it to the Rate using the parts. In … -
Django migrations freeze and are killed in production
So I use AWS and docker to deploy my django project. When I do makemigrations and migrate locally everything works fine. But when I deploy to production and try to migrate there migrations freeze and terminal is stuck until process is killed. There is no error so I am struggling to understand whats going wrong and how to find the bug. I also make sure to put the site in maintenance mode before I run the migrate just to make sure that the table is not being accessed when migrating but its still not helping. Important to note is that sometimes migrations go through and most of the time they dont. I basically have to retry 10 times before all of them have been migrated. Very common is that if I have for ex 3 migration files for the exakt same app 2 of them might be migrated instantly OK and the third freeze up (even if its the same app/same table). The table in question is very small with very little data in it and im doing very simple stuff like add column, add ordering etc etc to the app... Here is the last migration im trying to apply … -
Which is the right place to do CRUD action in Django Rest Framework?
I am creating a simple API to learn DRF. I've found that it's possible to do crud action in serializers.py or views.py I read DRF documentation sections below: saving instances viewset actions Still not quite sure on what option to use. -
Django migrate ModuleNotFoundError
I'm trying to learn django, so I'm pretty new to all this. I set up my virtual env, installed django to it, and started it as follows (I'm making a little message board thing for practice thus mb): $ pipenv install django==2.2.0 $ pipenv shell (mb) $ django-admin startproject mb_project . (mb) $ python manage.py startapp posts Then I added posts to my installed apps: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'posts.app.PostsConfig', ] However, when I run python manage.py migrate to create the db.sqlite3 file I get the following error: PS C:\Users\User\Desktop\DjangoStuff\mb> python manage.py migrate Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\User\.virtualenvs\mb-do-ON0u4\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\User\.virtualenvs\mb-do-ON0u4\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\User\.virtualenvs\mb-do-ON0u4\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\User\.virtualenvs\mb-do-ON0u4\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\User\.virtualenvs\mb-do-ON0u4\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\Users\User\.virtualenvs\mb-do-ON0u4\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'posts.app' I'm not sure what else to look at … -
Django Two tables for users authorization
I have to implement a backward-compatible Django server with PHP app. Legacy app is using LegacyUser model for authorization which more or less like: class LegacyUser(models.Model): id = models.BigAutoField(primary_key=True) email = models.CharField(max_length=255, unique=True) password = models.CharField(max_length=120, blank=True, null=True) ... other_data_fields ... USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] EMAIL_FIELD = 'email' In a new system, I do not have to add new records of LegacyUser (but I can). For now, the legacy system does not allow to create multiple users per Group. Actually LegacyUser should be considered as a group but I was implemented as a user. Right now I have to implement multiple Users per each LegacyUser so I have added proper Django user for authorization like: class User(AbstractUser): username = None email = models.EmailField(unique=True) legacy_user = models.ForeignKey(LegacyUser, on_delete=models.DO_NOTHING) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['publisher'] class Meta: managed = True db_table = 'user' and in base.py settings: ... AUTH_USER_MODEL = 'api.LegacyUser' SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=15), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'AUTH_HEADER_TYPES': ('Bearer',), 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'id', } AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', #Supports User 'common.auth.backends.LegacyBackend' #Supports LegacyUser ] ... The new application should enable to login both LegacyUser and User. After authorization LegacyUser.id should be used as USER_ID_CLAIM. This means if I have … -
Django Rest Framework returns relative path instead of full url with SerializerMethodField
I am experiencing a strange issue. I have been developing an application using Django and DRF along with react in frontend. My app has two models, Place and Cover. Every place has a cover image and here is the database schema. Image Table +----+---------------------+----------+----------------------+ | pk | file | title | description | +----+---------------------+----------+----------------------+ | 1 | /media/my-image.jpg | My Image | My Image Description | +----+---------------------+----------+----------------------+ Place Table +----+------+-------+ | pk | code | cover | +----+------+-------+ | 1 | abcd | 1 | +----+------+-------+ My operation is simple. I will request for place details using the place code and DRF will return the details. And here is what I wrote initially. class ImageSerializer(ModelSerializer): class Meta: model = Image fields = ["pk", "file", "title", "description"] class PlaceDetailSerializer(ModelSerializer): cover = ImageSerializer() class Meta: model = Place fields = ["code", "cover"] class PlaceDetailView(RetrieveAPIView): serializer_class = PlaceDetailSerializer permission_classes = [] queryset = Place.objects.filter(deleted=False, published=True) lookup_field = 'code' lookup_url_kwarg = 'code' And here is the output of the request { "code": "3469324020", "cover": { "pk": 13, "file": "http://127.0.0.1:8000/media/my-image.jpg ", "title": "My Image", "description": "" } } Everything is fine so far. As I wanted the full url of my image and that's exactly … -
Serializer not saving data to model
Goal: Get a teacher object using the token, and then insert the request.data into the model along with the teacher object, since the model requires a teacher object for the foreign key. views.py def put(self, request, *args, **kwargs): token = '0c023159d66477d15f389ed9c951fe0f29e4bb81' instance = self.get_object(token) serializer = NoticeBoardSerializer(instance,data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) def get_object(self, token): user = Token.objects.get(key=token).user if user: teacher = Teacher.objects.get(teacher__username = user) return teacher else: return Response({"error":"error"}) serializers.py class NoticeBoardSerializer(serializers.ModelSerializer): creator = serializers.CharField(source=("creator.teacher.username"), read_only=True) class Meta: model = NoticeBoard fields = ('__all__') -
Problem with writing a django rest serializer
I'm trying to write a Django Rest Framework serializer. It is supposed to take in a simple primitive data and return data with some of the related objects data. The model I'm serializing is Model_C Here are the models: class ModelA(models.Model): name = models.Charfield(max_length=16) attr1 = models... ... class ModelB(models.Model): name = models.CharField(max_length=16) attr1 = models... ... class ModelC(models.Model): model_a = models.ForeignKey(ModelA) model_b = models.ForeignKey(ModelB) text = models.CharField(max_length=32) date = models.DateTimeField() Here is the api view: class ModelCApiView(RetrieveUpdateDestroyAPIView): serializer_class = ModelCSerializer def get_queryset(self): return self.serializer_class.Meta.model.objects.all() def post(self, request): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): obj = serializer.save() return Response(data=serializer.data, status=status.HTTP_201_CREATED) else: return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST) The data fed to the serializer are as follows (with or without the ID): {'id': '1', 'model_a': 1, 'model_b': 1, 'text': 'some text', 'date': '2019-08-28 08:00:00'} Now, the thing is that the serializer should save the instance and return the serialized model WITH SOME OF THE related data: {'id': '1', 'model_a': {'id': 1, 'name': 'some model a name'}, 'model_b': {'id': 1, 'name': 'some model b name', 'attr1': 'some attr value'}, 'text': 'some text', 'date': '2019-08-28 08:00:00'} So the only thing that is created is ModelC instance. The api view is not supposed to create ModelA or ModelB …