Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connecting Mongodb to Django
I try to make a project and I need to connect mongodb to django and I have this error. I looked over all the pages about this error and I think that I did all that stuff and still didn't manage to solve it. Do you know what I need to do? django.core.exceptions.ImproperlyConfigured: 'django' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' -
How to add foreign-key column to dj-stripe admin?
I would like to add plan names to dj-stripe django admin so I can see a readable name for what each subscription is associated with. Adding "cancel_at" worked, but I can't use the name of a Product from a Plan. In my_app\admin.py I do this: from djstripe.models import Subscription from djstripe.admin import StripeModelAdmin, SubscriptionItemInline ... class SubscriptionAdmin(StripeModelAdmin): list_display = ("plan__product__name", "customer", "status", "cancel_at") list_filter = ("status", "cancel_at_period_end") list_select_related = ("customer", "customer__subscriber") inlines = (SubscriptionItemInline,) def _cancel(self, request, queryset): """Cancel a subscription.""" for subscription in queryset: subscription.cancel() _cancel.short_description = "Cancel selected subscriptions" # type: ignore # noqa actions = (_cancel,) admin.site.unregister(Subscription) admin.site.register(Subscription, SubscriptionAdmin) ... Which produces this error: Subscription has no field named 'plan__product__name' How do I add extra columns in dj-stripe that require foreign key lookups? -
AttributeError: 'NoneType' object has no attribute 'username' Django Rest Serializers POST request
I'm making a post request to the django backend from the react frontend. For this I send a json object But the backend is giving me an error. I have given my serializer data in the form of the below json objects removing the default fields like id, created and updated fields and sent the remaining fields. The POST is not successfull showing the error as mentioned below.. Internal Server Error: /create_message/ Traceback (most recent call last): File "C:\Users\Ajay\Desktop\New folder\Mars\marsgc\main\serializers.py", line 31, in get_messager return obj.messager.username AttributeError: 'NoneType' object has no attribute 'username' The function call at the frontend is: let add_message = async (message) => { await fetch(`http://localhost:8000/create_message/`,{ method: 'POST', headers:{ 'Content-Type':'application/json' }, body:JSON.stringify(message) }) } const new_message = async (e) => { e.preventDefault() const messager = user; const body = message; const room_in = room.id; await add_message({body,messager,room_in}) } A general django rest message object is { "id": 2, "body": "Hi", "created": "2022-02-20T17:41:47.796395Z", "updated": "2022-03-13T17:20:26.949428Z", "messager": "ajay", "room_in": 17 }, My models are class Topic(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Room(models.Model): host = models.ForeignKey(User,on_delete=models.CASCADE,null=True) topic = models.ForeignKey(Topic,on_delete=models.CASCADE,null=True) name = models.CharField(max_length=200) description = models.TextField(blank=True,null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ['-updated', '-created'] def … -
Django models not giving href value in html format
My model name is cat I am fetching this in html template using safe just like {{cat.languages|safe}} See my model Here is url in html -
Recreating Django Project - MakeMigrations Error
I recently attempted to recreate an existing Django project consisting of one app. So I started the project under the new name I wanted, made the app, and then manually dragged over the old existing app files from the old project app folder into the new app folder. Both projects are looking identical but when I attempt to do an initial migration on the new project it runs this error django.db.utils.OperationalError: no such table: inventory_register Inventory is the name of the app and Register is the name of one of my models. Am I possibly migrating too much too soon considering i have a lot of forms, signals ect im essentially trying to migrate at once? Also happy to provide anymore info that could help clarify -
to return True when the post has a like from the creator of the post
to return True when the post has a like from the creator of the post how to make such an analog on django user = { 'id': 121 } likes = [{ 'userInfo': { 'id': 121 } }] hasSelfLike = any(like['userInfo']['id'] == user['id'] for like in likes) print(hasSelfLike) models.py class Task(models.Model): user_info = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, name='userInfo') title = models.CharField(max_length=100) text = models.TextField(max_length=10000) def get_hasSelfLike(self): return self.likes.values_list('userInfo_id', 'userInfo__id') #returns always True class Like(models.Model): task_id = models.ForeignKey(Task, on_delete=models.CASCADE, blank=True, null=True, related_name='likes', name='taskId') user_info = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, name='userInfo') -
django factory boy factory with OneToOne relationship
I am using factory boy to create test factory for my django App. And I have trouve defining my factory because my model has a One-to-One relation with itself. My model looks something like this: class MyModel(models.Model): previous: MyModel= models.OneToOneField( "self", related_name="next", null=True, blank=True ) next: MyModel And my factory looks like this: class MyModelFactory(factory.django.DjangoModelFactory): next = None previous = None But then I can't define properly my model in the test: first_model: MyModel= MyModelFactory() second_model: MyModel= MyModelFactory(previous=first_task) So we can see for second_model.previous we can find first_model. But for first_model.next we have nothing. Well it's obvious cause we didn't put anything inside when we define first_model. However, it's obvious we shouldn't make something like: first_model: MyModel= MyModelFactory(next=second_task) second_model: MyModel= MyModelFactory(previous=first_task) cause the second task has not been defined yet when we define the first model. So I don't know in this case what should I do to have first_model.next = second model and second_model.previous = first_model at the same time. -
ZipFile to File to FileField Django Python
I'm doing a call from a API that give me a zip file with two file in it. I manage to extract the file i need (cause it's a PDF) and now i just can't find a solution to save it in my filefield without creating the file in my pc. with ZipFile(io.BytesIO(response3.content)) as z: # response3 is my response to the API for target_file in z.namelist(): if target_file.endswith('pdf'): z.extract(member=target_file) # that's how i can have acces to my file and know it is a valid PDF # here begin the trick with io.BytesIO() as buf: z.open(target_file).write(buf) buf.seek(0) f = File.open(buf) # File is an import of django.core.files rbe, created = RBE.objects.update_or_create(file=f) With this code i get an error with write of z.open(...).write as below: z.open(target_file).write(buf) io.UnsupportedOperation: write Thanks :) -
Django Channels can't "socket.send" when trying to constantly send data to client from server
I am trying to create a game on django using channels. For that I need server to send data to client after certain amount of time. I managed to achieve it but now I can not socket.send anything back to the server. I am having hard time trying to figure out why is that. What I try to achieve is having server constantly sending the data and receive data from the client to save it to database. Second part being where I am stuck currently. consumers.py from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async from channels.db import database_sync_to_async from django.utils.crypto import get_random_string from .models import Model import asyncio import json import random from hashlib import pbkdf2_hmac @database_sync_to_async def get_round(): a = Model.objects.last() return a.round_number class Game(AsyncWebsocketConsumer): async def connect(self): self.connected = True self.room_name = 'gameName' self.room_group_name = 'game_room' await self.channel_layer.group_add( self.room_group_name, self.room_name ) await self.accept() while self.connected: await asyncio.sleep(5) server_seed = get_random_string(length=64) public_seed = random.randint(0, 999999) round = await get_round() hash = pbkdf2_hmac('sha256', bytes(server_seed, 'utf-8'), bytes(public_seed), round) result = int(hash[0:8].hex(), 16) % 15 await self.send(text_data = json.dumps({ 'round_result': result })) async def disconnect(self): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) self.connected = False async def receive(self, text_data): data = json.loads(text_data) print(data) # … -
Django Test: Incorrect type. Expected pk value, received str
I have a simple model having a foreign key: class Job(models.Model): resource = models.ForeignKey(Resource, on_delete=models.RESTRICT, related_name="resource_jobs") required_resource = models.FloatField(default=0) Here is the viewset: class JobViewSet(ModelViewSet): queryset = Job.objects.all() serializer_class = JobSerializer I am writing a test to create this Job object like this. self.detail_url: str = "factory:jobs-detail" self.resource = Resource.objects.create(**self.resource_data) self.job_data = { "resource": self.resource, "required_resource": 20, } def test_create(self) -> None: response: Response = self.client.post( self.list_url, data=self.job_data ) print(response.data) self.assertEqual(response.status_code, 201) Upon running the test I get an error: {'resource': [ErrorDetail(string='Incorrect type. Expected pk value, received str.', code='incorrect_type')]} How do I pass this object in this dictionary. Thank you for any help. -
Django the JSON object must be str, bytes or bytearray, not NoneType
I am creating an ecommerce website with the help of Django and I am using Local Storage as my cart and also using some jquery and ajax to post my data on server side but when I am sending my local storage to the server Side I am getting the error like this, See the error My cart.html is like this from where I am sending the data to checkout, <form action="/checkout" method="post" > {% csrf_token %} <button class="button-78" role="button">Proceed to buy</button> </form> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script> <script> $('.plus').click(function(e){ console.log("hello"); e.preventDefault(); cartt=JSON.parse(localStorage.getItem('cart')); console.log(cartt) var idstr=this.id.toString(); cartt[idstr]=cartt[idstr]+1; localStorage.setItem('cart',JSON.stringify(cartt)) $.ajax({ type:"POST", url:"http://127.0.0.1:8000/cart", data:{ prodd:localStorage.getItem('cart'), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:function(){ location.href = "/cart" } }); }); $('.minus').click(function(e){ e.preventDefault(); cartt=JSON.parse(localStorage.getItem('cart')); var idstr=this.id.toString(); cartt[idstr]=cartt[idstr]-1; localStorage.setItem('cart',JSON.stringify(cartt)) $.ajax({ type:"POST", url:"http://127.0.0.1:8000/cart", data:{ prodd:localStorage.getItem('cart'), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:function(){ location.href = "/cart" } }); }); $('.button-42').click(function(e){ e.preventDefault(); cartt=JSON.parse(localStorage.getItem('cart')); var idstr=this.id.toString(); delete cartt[idstr]; localStorage.setItem('cart',JSON.stringify(cartt)) $.ajax({ type:"POST", url:"http://127.0.0.1:8000/cart", data:{ prodd:localStorage.getItem('cart'), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:function(){ location.href = "/cart" } }); }); $('.button-78').click(function(e){ $.ajax({ type:"POST", url:"http://127.0.0.1:8000/cart", data:{ prodd:JSON.stringify(localStorage.getItem('cart')), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success:function(){ location.href = "/checkout" } }); }); </script> And this is my views.py file, def checkout(request): if request.method == "POST": global context dict=json.loads(request.POST.get('prodd')) ldict=list(map(int,dict.keys())) objects=product.objects.filter(pk__in=ldict) print(dict) context={'object':objects,'dict':dict} return render(request,'checkout.html',context) I tried multiple methods like json.loads() and json.dump() and both … -
QuillField not showing in django admin
Quill editor v0.1.40 works fine on my local computer, but when in production, QuillFileds are invisible on admin panel – only labels appear: When inspecting the admin page on Chrome, I see such errors on the console: GET https://my site.com/static/django_quill/django_quill.css net::ERR_ABORTED 404 (Not Found) GET https://my site.com/static/django_quill/django_quill.js net::ERR_ABORTED 404 (Not Found) Uncaught ReferenceError: QuillWrapper is not defined at (index):261:27 at (index):263:11 django_quill.css and django_quill.js fail to load. I can't figure out why it works on my local project which has the same setup, except that on local I use python 3.9/Django 4.0.1 while in production, it's v3.8/4.0.2. Another difference is that, in production, django_quill folder is under myenv/lib/python3.8/site-packages/ directory. On my computer, there is no django_quill folder under myenv/lib/python3.9/site-packages/. In fact, there is no such folder anywhere on my drive, nor the related django_quill.css or django_quill.js files. I have no problem while migrating from old TextField's, or viewing the content on the templates. Any suggestion or feedback will be welcomed and greatly appreciated. Thank you. -
How to get CST Timezone for Django DateTimefield column
I want to update existing DB data and it should update the "DateTimeStamp" field in database with current time (Central time). DB Table configuration : DateTimeStamp field is having default value as CURRENT_TIMESTAMP. Django setting.py configuration : TIME_ZONE = 'US/Central' Django models.py configuration : DateTimeStamp = models.DateTimeField() Django views.py : dt = datetime.now().astimezone(pytz.timezone('US/Central')) when I check "dt", it shows date in Central only, but when I update the table, it is not reflecting in Central time table.objects.filter(col1=col1).update(col2=col2,col3=col3,DateTimeStamp=dt) dt = 2022-03-14 07:53:19 database field got updated with 2022-03-14 23:23:19 Can someone please assist me what's going wrong here. -
Django tried these URL patterns, in this order
from django.contrib import admin from django.urls import path from App import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('qui_sommes_nous/', views.qui_sommes_nous, name='qui_sommes_nous'), path('equipe/', views.equipe, name='equipe'), path('galerie/', views.galerie, name='galerie'), path('avendre/', views.avendre, name='avendre'), path('alouer/', views.alouer, name='alouer'), path('realisation/', views.realisation, name='realisation'), path('contact/', views.contact, name='contact'), path('details_des_appartement/', views.details_des_appartement, name='details_des_appartement'), ] please help me solve this problem, when I click on a link it always comes out not found while on the home page it goes well -
Django server & Gunicorn - 502 Bad Gateway
I have running two Django servers in my raspberry pi and serve them with Gunicorn and Nginx. One of them is running fine, but the other one is giving me a 502 Bad Gateway issue. I would appreciate if someone could help me to debug this issue. Here are the logs when I run sudo journalctl -u portfolio: pi@raspberrypi:/etc/systemd/system $ sudo journalctl -u portfolio -- Logs begin at Mon 2022-03-14 11:41:15 GMT, end at Mon 2022-03-14 12:32:28 GMT. -- Mar 14 12:07:10 raspberrypi systemd[1]: Started gunicorn daemon. Mar 14 12:07:11 raspberrypi gunicorn[4623]: [2022-03-14 12:07:11 +0000] [4623] [INFO] Starting gunicorn 20.1.0 Mar 14 12:07:11 raspberrypi gunicorn[4623]: [2022-03-14 12:07:11 +0000] [4623] [INFO] Listening at: unix:/run/portfolio.sock (4623) Mar 14 12:07:11 raspberrypi gunicorn[4623]: [2022-03-14 12:07:11 +0000] [4623] [INFO] Using worker: sync Mar 14 12:07:11 raspberrypi gunicorn[4623]: [2022-03-14 12:07:11 +0000] [4626] [INFO] Booting worker with pid: 4626 Mar 14 12:07:11 raspberrypi gunicorn[4623]: [2022-03-14 12:07:11 +0000] [4630] [INFO] Booting worker with pid: 4630 Mar 14 12:07:11 raspberrypi gunicorn[4623]: [2022-03-14 12:07:11 +0000] [4631] [INFO] Booting worker with pid: 4631 Mar 14 12:07:11 raspberrypi gunicorn[4623]: [2022-03-14 12:07:11 +0000] [4626] [ERROR] Exception in worker process Mar 14 12:07:11 raspberrypi gunicorn[4623]: Traceback (most recent call last): Mar 14 12:07:11 raspberrypi … -
Error when deleting AbstractBaseUser user instance
The user model class is defined as follows: enter image description here The settings are configured as follows: enter image description here The views code is as follows: enter image description here I use the following command to generate sql: python3 manage.py makemigrations rbac python3 manage.py sqlmigrate rbac 0001 Then I generate the table in the database: enter image description here Then I am using Delete to call the API: http://127.0.0.1:8000/rbac/user/21 So django raise an exception: django.db.utils.ProgrammingError: (1146, "Table 'mds.django_admin_log' doesn't exist") I don't know why this is happening, I hope you can help me solve this problem -
Filter object where queried number is within a range
Lets say I have a model with a range_low and a range_high, and want to find that instance if a number falls within that range. ID Prefix Low High 3 GH 1 300 4 GH 450 700 If I were to search GH250 then I should get back the instance with ID of 3 in this example. I considered using range() to get a list of all the numbers within a range, but this would require me to query every instance with a prefix of GH first & then build a range for each & every one of them to find which one overlaps. To limit this, I do at least have the low & high available, so I could query all instance with a prefix of GH where high is under 250 and that somewhat scales the results down, but this is still a pretty big query. This is my current query which just looks for the prefix being exact & the low or high containing the number. prefix = search[:2] number = search[2:] queryset = queryset.filter( Q(Q(low__icontains=number) | Q(high__icontains=number)) & Q(prefix__icontains=prefix) ) What tools might be available to me to efficiently filter results to get the block that … -
Saving Form Data Based On The Input Label
I am building a form that utilizes dynamic question/answers with Question and Answer models so that new questions can be created by non-devs. Here are my current models (missing some unnecessary information for this question) models.py class Question(models.Model): question = TextField() is_active = BooleanField(default=False) def __str__(self): return self.question class Answer(models.Model): answer = TextField() question = ForeignKey(Question, on_delete=CASCADE, default=None) In the view I create the form like this. views.py def survey(request): custom_questions = Question.objects.filter(is_active=True) if request.method == "POST": formset = [] for q in custom_questions: formset.append(AnswerForm(request.POST)) ### Here is where I would like to process this data else: formset = [] for q in custom_questions: answer_form = AnswerForm() answer_form.fields['answer'].label = q.question formset.append(answer_form) return render(request, 'template.html', {'formset': formset}) How would I process this data based on the question that was asked? Here is what I tried just to see what information was being processed in the form: for q in custom_questions: answer_form = AnswerForm(request.POST) if answer_form.is_valid(): print(answer_form.cleaned_data['answer'] However, when it printed the data it only printed the same answer multiple times. I would like to: Use the label that was defined in the GET request to Question.objects.get(question=) in order to set the foreignkey field to the Answer model. Get the correct data … -
How to order queryset by foreign key field without duplicates?
I have Django models Ticket and Confirmations: class Ticket(Model): name = models.TextField() class Confirmation(Model): ticket = models.ForeignKey( "ticket.Ticket", related_name="confirmations", ) expire_date = models.DateTimeField() I want to order them by expire date of confirmations, and it works but if ticket has more than one confirmation then it will be returned in queryset multiple times: tickets = Ticket.objects.order_by('confirmations__expire_date') for ticket in tickets: print(f"id: {ticket.id}") > id: 1 id: 2 id: 1 id: 3 id: 4 id: 1 I don't want to return duplicates. I just need the first element and get rid of the rest. I need to take into account the latest confirmation in response. -
how to view/edit data after submitting form through template
How do I have the data visible/editable on the form after submitting the form and coming back to this URL "checkout/" again, so the user can edit the address again and submit it and the data gets updated in the database, I can't seem to find a way to do this I would really appreciate if you can help, Thx! views.py def checkout(request): if request.method == 'POST': form = ShippingForm(request.POST) if form.is_valid(): new_shipping = form.save(commit=False) new_shipping.customer = customer new_shipping.order = order new_shipping.save() return redirect('store:checkout_shipping') else: form = ShippingForm() else: form = ShippingForm() models.py class ShippingForm(forms.ModelForm): address_one = forms.CharField(max_length=200) address_two = forms.CharField(max_length=200) urls.py path('checkout', views.checkout, name="checkout"), -
Django admin Unknown field with underscore
class UserControlAdmin(ExportActionMixin, admin.ModelAdmin): resource_class = UserResource list_display = ('get_branch', 'get_segment', 'get_team', 'get_position', 'user', 'get_gender') list_filter = ('team_control__company_group__branch', 'team_control__company_group__segment', 'team_control__team') fields = ('team_control__company_group__branch', 'team_control__company_group__segment', 'team_control__team', 'user',) I'm trying to add fields with underscore separated field names and I got error: Unknown field(s). How can I fixed that? -
`Cannot query "<class 'models.declaration.gentmodel.Beast'> Must be "ContentType" instance.`
I am using Django3. I have model class Option and it has members like these. class Option(models.Model): item_type = m.ForeignKey( ContentType, related_name="item_%(class)s_set", on_delete=m.CASCADE,null=True) item_id = m.PositiveBigIntegerField(null=True) item = GenericForeignKey('item_type', 'item_id') This can accept any class instance in item However I have trouble when filtering this model. For example in this case, I have rows which have Beast class as item so I try to filter by Beast and id def get_queryset(self): queryset = super().get_queryset() queryset = queryset.filter(item_type=Beast,item_id=1) This error comes Cannot query "<class 'models.declaration.gentmodel.Beast'>": Must be "ContentType" instance. How can I solve this? Any help appreciated. thank you. -
Multi container application
I have to create a dockerized web application. In my idea, I would like to create 3 containers: A Python Django container that can query a container that contains an R-script. An R container A Postgres database container. My question is this: how can I query the R container from the Django container? Thank you for your support. -
Set Unique Constrait only under the direct parents (Django MPTT)
I created "Category" model with Django MPTT: from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): name = models.CharField(max_length=50) parent = TreeForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name="children") But, with this "Category" model, I could add the duplicated data "3F" and "4F" under "Building B"(Direct Parent) as shown below: USA New York Building A 3F 4F Building B 3F // Here 3F // Here 4F // Here 4F // Here So I added "unique=True" to "name" field in the model "Category": from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Category(MPTTModel): // Here name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name="children") But with this "Category" model, I couldn't add the data "3F" and "4F" under "Building B" anymore because "3F" and "4F" already exist under "Building A" in "Category". I found adding "unique=True" to "name" field in "Category" model sets Unique Constrait in whole "Category" model about "name" field. So if there are the same "name" values such as "F3" and "F4" anywhere in "Category", we cannot add the same "name" values such as "F3" and "F4" anywhere in "Category". In short, if "3F" and "4F" already exist anywhere in "Category", we cannot add "3F" and … -
SMTPConnectError (421, b'Server busy, too many connections')SMTPConnectError (421, b'Server busy, too many connections')
I have checked every single solution on other questions but they are of zero help,using bulk email services also require having a domain name already meanwhile my django website is still in development but i also want to send actual mails not mail on django console.I have allowed access to less secure apps,used app password and re capcha all to no avail,i even changed my email host to yahoo mail still the same thing,the fact that email verification is a core part of authentication and there's little to no support or help is very annoying,already looked through all youtube videos it worked for them but non worked for me my settings file: EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'mymail@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True EMAIL_USE_SSL = False the error mesage: SMTPConnectError (421, b'Server busy, too many connections')