Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django using the auth_user table in relationships
I'd like to use the auth_user table in one-to-many and many-to-many relationships. Is this a bad idea? Can I do it? How do I do it? Everything is happening through Admin. So, I just need the models. -
Django ManytoManyField query does not exist
I've created models for the logic of friend list and friend request. In the FriendRequest I've defined a method which adds User relation to FriendList if accept method is called. However I'm unable to do so because of the error shown below. I don't understand the error as I'm adding the User in the model. views.py friend_request = FriendRequest.objects.get(id=request_id) if request_option == 'accept': friend_request.accept() if request_option == 'decline': friend_request.decline() models.py class FriendList(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user") friends = models.ManyToManyField(User, blank=True, related_name="friends") def add_friend(self, account): if not account in self.friends.all(): self.friends.add(account) self.save() class FriendRequest(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sender") receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name="receiver") is_active = models.BooleanField(blank=False, null=False, default=True) timestamp = models.DateTimeField(auto_now_add=True) def accept(self): receiver_friend_list = FriendList.objects.get(user=self.receiver) if receiver_friend_list: receiver_friend_list.add_friend(self.sender) sender_friend_list = FriendList.objects.get(user=self.sender) if sender_friend_list: sender_friend_list.add_friend(self.receiver) self.is_active = False self.save() def decline(self): self.is_active = False self.save() raise self.model.DoesNotExist( friends.models.FriendList.DoesNotExist: FriendList matching query does not exist. -
RabbitMQ : How to check queue content when processing a task using celery?
I have setup a basic message and task queue using RabbitMQ and Celery in my Django app. According to my understanding the when I use delay menthod, that pushes my tasks to the rabbitMQ queue and one of my workers from my celery app fetches the same from queue to execute the same. Is there any way in which when I push the task to the queue using delay I can view the same on my message queue RabbitMQ management portal? Since the tasks are almost instantly fetched and processed there is no chance of viewing them on the portal. This is what I tried which I think is wrong by adding a sleep timer in my task method. sudo nano tasks.py from __future__ import absolute_import, unicode_literals from celery import shared_task import time @shared_task def add(x, y): time.sleep(100) return x + y Started my celery app (myprojectenv) root@ubuntu-s-1vcpu-1gb-blr1-01:/etc/myproject# celery -A myproject worker -l info Pushed the tasks for processing (myprojectenv) root@ubuntu-s-1vcpu-1gb-blr1-01:/etc/myproject# python3 manage.py shell Python 3.8.10 (default, Mar 15 2022, 12:22:08) [GCC 9.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from app1.tasks import add >>> add.delay(1,2) On celery window [2022-06-10 06:16:15,182: INFO/MainProcess] celery@ubuntu-s-1vcpu-1gb-blr1-01 ready. … -
Validation Error {'__all__': ['Model with this field1, field2, field3 and field4 already exists.']} not getting handled by Django in admin
When I enter duplicate values for field1, field2, field3 and field4 in the django admin form, the debug screen with Validation Error appears Validation Error {'all': ['Model with this field1, field2, field3 and field4 already exists.']} instead of getting handled by the djnago admin form. The solution was I had excluded the field1 in my django admin.py file for the Model, I removed it from exclude and entered field1 in the fields of my Model Form. P.S. : readonly fields do not work in this scenario, you need to include the field in normal field, but you can add it as in custom form as widget readonly. -
Best way to send many choices through Django Rest Framework
I am using Django Rest Framework in conjunction with Vuejs to create a recipe costing calculator. I have an lot of unit choices (eg. grams, kilograms, liters etc.). What is the best way to send this data through to the frontend? I've created an endpoint for it at /ingredients/get-all-unit-choices/ that returns only an object with all the unit choices. Is this a good approach or is there a cleaner way to declare the choices and send it through to the frontend? And in general is it a good approach to create a lot of endpoints that do and return certain things? unitchoices.py WEIGHT_CHOICES = ["pound", "kilogram", "ounces", "grams", "tonnes"] VOLUME_CHOICES = [ "millileter", "litre", "gallon", "teaspoon", "tablespoon", "fluid-ounce", "quart", "pint", "cup", ] QUANTITY_CHOICES = ["each", "dozen", "hundreds", "thousands"] TIME_CHOICES = ["hours", "minutes", "seconds"] LENGTH_CHOICES = ["millimeter", "meter", "centimeter", "inch", "foot", "yard"] grouped_unit_choices = { "Weight": WEIGHT_CHOICES, "Volume": VOLUME_CHOICES, "Quantity": QUANTITY_CHOICES, "Time": TIME_CHOICES, "Length": LENGTH_CHOICES, } View This is the view that gets called by the ingredient/get-all-unit-choices/ endpoint. I also had to create the grouped_unit_choices dictionary so that I can display the <optgroup> in the html to have some order to them @api_view(["GET"]) def get_all_unit_choices(request): """helper view for returning all valid … -
no module named 'multiselectfield' (docker / Django)
I am trying to run a database on my server using docker. I am using django and postgreSQL. After adding the multiselectfield library to my repo it keeps failing to run the container with following error: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/usr/local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.8/site-packages/django/apps/config.py", line 224, in create import_module(entry) File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'multiselectfield' Even though i pip installed the library on all python versions i have installed (requirement already satisfied....) It is included in the requirements.txt and is installed as well when building the container. -
Filter Embedded Documents that match a condition in MongoEngine, Django, GraphQl
Document Structure Data class Data(EmbeddedDocument): v = FloatField() q = StringField() co2 = FloatField() price = FloatField() ts = DateTimeField() Meters Data class MetersData(DynamicDocument): meta = {'collection': 'dk_heating'} _id = ObjectIdField() ident = StringField() meteringPointId = StringField() customer = StringField() cvr = StringField() type = StringField() unit = StringField() address = StringField() period = EmbeddedDocumentField(Period) hourly_data = ListField(EmbeddedDocumentField(Data), db_field='data') daily_data = ListField(EmbeddedDocumentField(Data)) monthly_data = ListField(EmbeddedDocumentField(Data)) # monthly_data = EmbeddedDocumentListField(Data) yearly_data = ListField(EmbeddedDocumentField(Data)) I am using this Query. Query MetersData.objects.filter(address=address, customer=customer).fields( monthly_data={"$elemMatch": {"q": "E"}}, address=1, customer=1, cvr=1, ident=1, meteringPointId=1, type=1, unit=1, period=1) It returns me only the first matching element. I have read the documentation and it reads that $elemMatch is supposed to return only the first matching result. But in my case, I need all the matching results. Result of the Query I have searched everywhere but I am unable to find a solution. -
How to test foreignkeys to self in django
Django allows a foreign key to "self" as in class Profile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, verbose_name="User", related_name="user_profiles", ) entity = models.ForeignKey( Entity, on_delete=models.CASCADE, verbose_name="Entity", related_name="entity_profiles", ) email = models.EmailField( max_length=255, help_text=_("Automatically generated to use entity email domain"), ) supervisor0 = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, verbose_name="Supervisor0", related_name="supervisor0_profiles", help_text=_("Employees only."), ) supervisor1 = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, verbose_name="Supervisor1", related_name="supervisor1_profiles", help_text=_( "Employees only. Only the executive head is his/her own \ supervisor." ), ) supervisor2 = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, verbose_name="Supervisor2", related_name="supervisor2_profiles", help_text=_( "Employees only. Only the executive head is his/her own \ supervisor." ), ) supervisor3 = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, verbose_name="Supervisor3", related_name="supervisor3_profiles", help_text=_( "Employees only. Only the executive head is his/her own \ supervisor." ), ) The supervisor0 is the user and being supervisor0 identifies him/her as an employee. The other supervisors also have to be already in the database for them to be able to be referenced. The help_texts explain the situation of the executive head. The question is how to test these relationships to "self". I have no problem with relationships to other models. Using pytest, I record only supervisor0 in the ProfileFactory for the moment. class ProfileFactory(factory.django.DjangoModelFactory): class Meta: model = Profile user … -
How i can to prevent to create multiple instance while multi request in django?
Hi everyone i have project include about payment function between user and user. But i have a problem when many user buy a product.the many payment object will created more than product avaliable. How i can to solve this ? products_avaliable = Product.objects.filter(on_sell=true) for product in products_avaliable: payment = Payment() payment.buyer = .... payment.seller = product.owner payment.save() product.on_sell = False product.save() when add deley products_avaliable = Product.objects.filter(on_sell=true) for product in products_avaliable: payment = Payment() payment.buyer = .... payment.seller = product.owner payment.save() time.sleep(10) # simulate to slow server or many request product.on_sell = False product.save() when i try to time.delay before payment create (simulate when server to slow or may request by user) the payment will create many object -
Django could not detect newly added database after adding router
I have three database out of which one is set to default. I have already created router for ringi database and it working perfectly fine. Now i would like to add one more database and after creating the new router for database named cms, its not working. So my project name is wshp and one of router for ringi database, i placed it in same folder as settings.py. I created another app called mypage and created router for cms and name of router is cmsrouter. settings.py DATABASE_ROUTERS = ['wshp.router.myrouter','app_mypage.cms_router.cmsrouter'] DATABASE_APPS_MAPPING = { 'ringi':'ringi_db', 'cms':'cms_db' } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mypage', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', }, 'ringi_db':{ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'ringi', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', }, 'cms_db':{ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'cms', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', } } cms_router.py class cmsrouter: def db_for_read(self, model, **hints): if model._meta.app_label == 'cms': return 'cms_db' else: return None def db_for_write(self, model, **hints): if model._meta.app_label == 'cms': return 'cms_db' else: return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'cms' or \ obj2._meta.app_label == 'cms': return True else: return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'cms': … -
form.errors won't display upon invalid form submission
I'm having difficulty with displaying custom defined errors on a page when a user submits an invalid form submission. I set novalidate on the form element with the intent of disabling a browser's default form validation messages. At the same time the error messages that are defined on QuestionForm are not displaying on the page. It's not clear to me why the form error messages aren't showing? Is setting novalidate causing this to occur? class Page(TemplateView): def get_context_data(self, **kwargs): context = super().get_context_data() context['search_form'] = SearchForm() return context class AskQuestionPage(Page): template_name = "posts/ask.html" extra_context = { 'title': "Ask a public question" } def attach_question_tags(self, tags): question_tags = [] for name in tags: try: tag = Tag.objects.get(name=name) except Tag.DoesNotExist: tag = Tag.objects.create(name=name) finally: question_tags.append(tag) return question_tags def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = QuestionForm return context def post(self, request): context = self.get_context_data() form = context['form'](request.POST) if form.is_valid(): tags = self.attach_question_tags( [tag.lower() for tag in form.cleaned_data.pop("tags")] ) try: question = form.save(commit=False) question.profile = request.user.profile question.save() except IntegrityError: form.add_error(None, "This post is already posted") context['form'] = form else: question.tags.add(*tags) form.save_m2m() return SeeOtherHTTPRedirect( reverse("posts:question", kwargs={ "question_id": question.id }) ) return self.render_to_response(context) <div class="question_posting_form"> <h2>{{ title }}</h2> {% if form.non_field_errors %} <ul class="non_field_errors"> {% for … -
Login page is not appearing while it directly catch register form
login.html {% extends 'main.html' %} main.html extended {% block content %} block content added {% if page == 'Login' %} if url is login will open login section {% csrf_token %} Sign Up {% else %} {% csrf_token %} {% for field in form %} {{field.label}} used for auto filling of fields {{field}} fields are fetched directly from model.py {% endfor %} Already signed up yet? Login {% endif %} {% endblock content %} -
Is there a way to override ClockedSchedule model from Django Celery Beat?
I want to add unique=True attribute to clocked_time field of ClockedSchedule model. Current Scenario is, when multiple threads try to get_or_create schedule, it creates more than one of similar records given schedule is not found, and when next time some thread tries to get the schedule it throws MultipleObjectsReturned exception. So, I was thinking adding a DB constraint might work here. Attaching the code for reference: schedule, created = ClockedSchedule.objects.get_or_create(**clocked_options) return schedule And the model looks like: class ClockedSchedule(models.Model): """clocked schedule.""" clocked_time = models.DateTimeField( verbose_name=_('Clock Time'), help_text=_('Run the task at clocked time'), ) class Meta: """Table information.""" verbose_name = _('clocked') verbose_name_plural = _('clocked') ordering = ['clocked_time'] def __str__(self): return '{}'.format(self.clocked_time) Let me know your thoughts, thanks! -
Ajax get request stays on readystate 1, but when i log the response text in the console it displays it without a problem
I cant display the result in my html because the request stays in state 1 and the response text displays undefined. When I access the url it displays the value I want to show on my html. Why is this happening? I'm using django on server side btw. Kinda new to ajax but I haven't been able to find an answer to this problem on other already solved questions. Code that executes the request: const getHighScore = (gameID, levelID) => { let ajaxPrueba = $.ajax({ url: `/get-data/${gameID}/${levelID}`, type: 'get', success: function(data) { return data; }, failure: function(data) { console.log('Got an error dude'); } }); return ajaxPrueba; } The parameters i pass on are 1 for gameID and 1 for levelID The url i'm talking about Also this is what the console returns: ajaxPrueba = $.ajax({ url: `/get-data/1/1`, type: 'get', success: function(data) { return data;… Object { readyState: 1, getResponseHeader: getResponseHeader(e), getAllResponseHeaders: getAllResponseHeaders(), setRequestHeader: setRequestHeader(e, t), overrideMimeType: overrideMimeType(e), statusCode: statusCode(e), abort: abort(e), state: state(), always: always(), catch: catch(e) , … } abort: function abort(e) always: function always() catch: function catch(e) done: function add() fail: function add() getAllResponseHeaders: function getAllResponseHeaders() getResponseHeader: function getResponseHeader(e) overrideMimeType: function overrideMimeType(e) pipe: function pipe() progress: function … -
Deserializing json to a python object without actually save the object in DB
I use Django and the model classes to access data from DB. I would like to add cache layer on top of DB. For example, let's say I have a User model and UserSerializer (inherited from ModelSerializer). When storing an User object in cache, I need to serialize the object to json import json serializer = UserSerializer(obj) serialized_data = json.dumps(serializer.data) However, when I retrieve this json from cache, I had trouble to convert it back to User object data = json.loads(serialized_data) deserializer = UserSerializer(data=data) user_obj = deserializer.save() # this return an User object but intenally it will create a new record in DB Any better ideas that I can use the serializer that django provided to deserialize json to object without actually creating the record in DB? -
Hyperlinks in Django Quill Editor are not displaying as expected
Problem I added the Quill Editor to my Django admin. When I input hyperlinks in the QuillEditor such as "www.example.com", instead of creating the hyperlink exactly as I type it, the URL will appear on the template page as "localhost:8000/plants/www.example.com". Directing me to a broken page instead of www.example.com Context I've read through the full quill documentation but I don't see a way to make sure hyperlinks added in the QuillEditor display without the project domain being prepended to the front of the hyperlink url. Heres how I input the URL 'www.example.com' in the django admin: Here is how the URL appears on the actual template page (you can see the url in the bottom left when I hover over it: Maybe I need to edit something in the urls.py? plants > urls.py urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('accounts/', include('django.contrib.auth.urls')), path('', include('pages.urls')), path('plants/', include('plants.urls')), ] -
Wrap python decorator with another decorator
I have a common decorator call throughout my Django codebase: @override_settings( CACHES={ **settings.CACHES, "default": generate_cache("default", dummy=False), "throttling": generate_cache("throttling", dummy=False), } ) def test_something(): ... The decorator code is too verbose. I'd love to wrap this code into a new decorator called @use_real_cache so the test function looks much cleaner: @use_real_cache def test_something(): ... How can I wrap a decorator with another decorator? -
Using fonts in django HTML email templates
I have a html template for a password reset email that I am trying to set up instead of the default django email. The code is as follows: <!DOCTYPE html> <html> <head> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300&display=swap" rel="stylesheet" /> <style> body { font-family: "Inter", sans-serif; font-size: 20px; color: #434343; margin: 0; } .main-container { max-width: 60%; } .centered-contents { display: flex; justify-content: center; } .pswd-button { background: #677db6; border-radius: 25px; color: #ffffff; cursor: pointer; text-decoration: none; padding: 15px; padding-top: 10px; padding-bottom: 10px; } .top-bar { width: 100%; background-color: #d9d9d9; display: flex; align-items: center; } .top-bar-title { color: #677db6; margin: 20px; } </style> </head> <body> <div class="top-bar"> <p class="top-bar-title">Nombre de Web</p> </div> <div class="centered-contents"> <div class="main-container"> <p style="font-size: 24px"> Hola <span style="color: #677db6">nombre</name></span>! </p> <p> Está recibiendo este correo porque ha solicitado un cambio de contraseña en <span style="color: #677db6">web</span>. Para continuar, por favor utilice el botón que se muestra a continuación: </p> <div class="centered-contents"> <a class="pswd-button" href="#"> Restablecer Contraseña </a> </div> <p> Le recordamos su nombre de usuario: <span style="color: #677db6">usuario</span> </p> <p> Si no ha solicitado ningún cambio de contraseña, no se preocupe. Puede ignorar este correo. </p> <p>Atentamente,</p> <p>El equipo técnico de <span style="color: #677db6">Web</span></p> </div> </div> </body> </html> And, rendered … -
generated json to csv to django model
Is there any way to do what I'm trying to do - generate json from api url request, transform it to csv, store in Django model? No idea how to make this work views.py def view(request): if request.method == 'GET': data1 = request.GET.get("data1") data2 = request.GET.get('data2') url = f'https://api.com/{data1}?d={data2}&format=json' response = requests.get(url=url) df = pd.json_normalize(response.json()) file = df.to_csv('data.csv') csv_file = File.objects.create(csv_file=file) csv_file.save() return render(request, 'template.html') models.py class File(models.Model): file = models.FileField() -
Want a unicode character in django crispy strictbutton
I'm trying to get a chevron to be the value in a crispy strictbutton. It should look like this: https://icons.getbootstrap.com/icons/chevron-down/ But, all I get is code in a little box: unicode in the box I've tried this: def __unicode__(self, this_char): return u"%s" % this_char StrictButton(self.__unicode__('\uF282'), css_class="btn btn-outline-secondary btn-sm", id="button-id-right") and this: StrictButton('\uF282', css_class="btn btn-outline-secondary btn-sm", id="button-id-right") and get the same result. I've tried embedding the html string hoping the browser would catch it - didn't work. Thanks -
Is there an efficient way to get the Django model of a modeladmin object from within an Admin action?
I have an action that is added to multiple Django model admins. Part of that action relies on the modeladmin and queryset like so: def my_action(modeladmin, request, queryset): queryset_model_name = queryset.first().__class__.__name__ model_to_update = apps.get_model(app_label='main', model_name=queryset_model_name) # more code here that relies on both queryset_model_name and model_to_update Is there a way to refactor this? Possibly a way to get the model string itself directly from modeladmin instead? I did a search through the django doc page for ModelAdmin but came up short. Any assistance would be appreciated! Thank you in advance. -
Is there a way to convert from ISO Date format to an Month, DD, YYYY at local time in Python
I am trying to convert my last_updated field from ISO Date format 2022-06-05T14:38:59.927753-07:00 into June 5th, 2022 at 2:38pm My code is try: if timefield.school_id: school = SchoolBell.object.get(school_id=timefield.school_id) return '{}'.format(datetime.strftime(school.last_updated)) except School.DoesNotExist: return '' Is there a way to call it inside the table field last_updated into the word format -
Django python requests library send and receive array values through POST
I am sending a POST request (with indexed array value) in Django (Python 3+) like: def wordgrpocc_ajax(request): woccs= [] postVars= request.POST print('postVars= '+str(postVars)) # OUTPUT: postVars= <QueryDict: {'syear': ['0'], 'eyear': ['0'], 'word_id[]': ['629c48a694c367c0e07f1d3a', '629c481e94c367c0e07ee8bc', '629c48c694c367c0e07f2864']}> url = skpsettings.API_URL+"word/group/occurrence" headers = {'Content-type': 'application/json'} bresplist = requests.post(url= url, data=json.dumps(postVars), headers=headers) woccs= bresplist.text return HttpResponse(woccs, content_type="application/json") Output of the print in above def: postVars= <QueryDict: { 'syear': ['0'], 'eyear': ['0'], 'word_id[]': ['629c48a694c367c0e07f1d3a', '629c481e94c367c0e07ee8bc', '629c48c694c367c0e07f2864']}> When I catch the request (in skpsettings.API_URL+"word/group/occurrence"), the array value is corrupted. Only the last value of the array is received: @csrf_exempt def api_WordGroupYearOcc(request): wocclist= [{}] if request.method == "POST": postVars= json.loads(request.body) word_ids= postVars.get("word_id") #word_ids= request.POST.getlist('word_id', []) syear = int(postVars.get("syear", 0)) eyear = int(postVars.get("eyear", 0)) print('postVars= '+str(postVars)) # OUTPUT: postVars= {'syear': '0', 'eyear': '0', 'word_id[]': '629c48c694c367c0e07f2864'} Output of the print in above def: postVars= {'syear': '0', 'eyear': '0', 'word_id[]': '629c48c694c367c0e07f2864'} What am I doing wrong? Thanks in advance. -
Browser loads an empy css
css located in my_blog/my_blog/blog/static/blog/style.css manage.py in my_blog/my_blog head of html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="{% static 'blog/style.css' %}"> <title>{% block title%} My blog {% endblock %}</title> </head> I'm using pycharm pro. Browser successfully load css file, but it's empty. Why this is happenning? -
How Django async view handle simultaneous requests
I test 2 views in Django 3.2: def sync_view(request): return HttpResponse("Hello, sync Django!") async def async_view(request): await asyncio.sleep(10) return HttpResponse("Hello, async Django!") start uvicorn as uvicorn myapp.asgi:application First request to async_view, right after to sync_view. My expectation that sync_view will response immediately, however it is handled only after 10 seconds. What is wrong? Why requests are not handled simultaneously?