Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I create in Django Framework a serializers for a model self referenced ManyToMany with intermediate table
I am try to create a simple model that is referred to itself through an intermediate table. Below the code. class Entity(models.Model): ..... childs = models.ManyToManyField( to='Entity', symmetrical=False, related_name='from_entities', verbose_name='Child Entities', through='EntityChild', through_fields=('from_entity', 'to_entity')) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'entity' verbose_name_plural = 'Entities' The intermediate table below class EntityChild(models.Model): from_entity = models.ForeignKey( Entity, on_delete=models.RESTRICT, related_name='from_entity') to_entity = models.ForeignKey( Entity, on_delete=models.RESTRICT, related_name='to_entity') ....., type = models.CharField( max_length=255, verbose_name='Type') class Meta: db_table = 'entity_childs' And the serializeres class EntityChildSerializer(serializers.ModelSerializer): to_entity = serializers.RelatedField(many=False, read_only=True) def to_representation(self, value): serializer = self.parent.parent.__class__(value, context=self.context) class Meta: model = EntityChild fields = ('to_entity', 'type',....) class EntitySerializer(serializers.ModelSerializer): fields = FieldSerializer(many=True) tags = TagSerializer(many=True) childs = EntityChildSerializer(source='from_entity', many=True) class Meta: model = Entity fields = ('id', 'childs', 'created_at', 'updated_at') So at the end my entity child will have a relation ManyToMany with the EntityChild that hold a reference to another entity. With the code below the serializer will return { "id": 1, "childs": [ null ],... } I tried follow this Nested serializer "Through model" in Django Rest Framework with no luck. Any help will be appreciated... Thank you all. -
Django TestCase crashes
I've created quite a few TestCases for my apps and everything was working as expected so far, recently I get this error Message when trying to run any TestCase (SimpleTestCase works fine, since it doesnt create any DB Objects, at least thats my theory). Example: # # pages/tests.py from django.test import SimpleTestCase, TestCase from non_voice.models import Product class HomePageTests(SimpleTestCase): def test_home_page_status_code(self): response = self.client.get('/') self.assertEquals(response.status_code, 200) class ProductTests(TestCase): def setUp(self): Product.objects.create(product='test', product_name='test', header_text='test', language_code='DE') def test_text_content(self): product = Product.objects.get(id=1) expected_object_name = f'{product.product}' self.assertEquals(expected_object_name, 'test') Output: 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 "/EDR_ICT/.virtualenvs/WSx_Dev/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/EDR_ICT/.virtualenvs/WSx_Dev/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/EDR_ICT/.virtualenvs/WSx_Dev/lib/python3.6/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/EDR_ICT/.virtualenvs/WSx_Dev/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/EDR_ICT/.virtualenvs/WSx_Dev/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/EDR_ICT/.virtualenvs/WSx_Dev/lib/python3.6/site-packages/django/core/management/commands/test.py", line 53, in handle failures = test_runner.run_tests(test_labels) File "/EDR_ICT/.virtualenvs/WSx_Dev/lib/python3.6/site-packages/django/test/runner.py", line 684, in run_tests old_config = self.setup_databases(aliases=databases) File "/EDR_ICT/.virtualenvs/WSx_Dev/lib/python3.6/site-packages/django/test/runner.py", line 606, in setup_databases self.parallel, **kwargs File "/EDR_ICT/.virtualenvs/WSx_Dev/lib/python3.6/site-packages/django/test/utils.py", line 156, in setup_databases test_databases, mirrored_aliases = get_unique_databases_and_mirrors(aliases) File "/EDR_ICT/.virtualenvs/WSx_Dev/lib/python3.6/site-packages/django/test/utils.py", line 272, in get_unique_databases_and_mirrors (connection.settings_dict['NAME'], set()) TypeError: unhashable type: 'set' I haven't changed anything I can think of, DB … -
How to insert a HTML Page inside HTML File without conflicting styles of each other
I have an HTML stored in database. I want to add that HTML page inside a HTML. the page has inline styling cdn of bootstrap etc. If I just add it inside a div element it affects the styling of the page that's it added to. How can I insert the html page in the html without conflicting styles of each other? -
Problems with creating obejcts with CreateView Django
I have a website with a blog section and when I am on a specific post page I want to add the comment section, where a specific user can leave a specific comment for a specific post. I tried a lots of methods but nothing is seems to work as expected. First I tried to handle this with a View class with get and post method and now I tried this and I'm not sure what is wrong with my code. my view: lass PostDetailView(CreateView): template_name = 'blog/post.html' form_class = CommentCreateForm slug = None def get(self, request, slug, *args, **kwargs): context = self.get_context_data(**kwargs) self.slug = slug post = Post.objects.get(slug=slug) context['banner_page_title'] = post.title context['page_location'] = 'home / post' context['post'] = post context['author_description'] = Profile.objects.get( user=post.author).description return render(request, self.template_name, context) def get_context_data(self, **kwargs): context = {} return context def form_valid(self, form): form.instance.user = request.user forms.instance.post = Post.objects.get(slug=slug) return super().form_valid(form) my model: class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='comments') content = models.TextField(_('Content')) posted_date = models.DateTimeField( _('Posted Date/Time'), auto_now_add=True) updated_date = models.DateTimeField(_('Updated Date/Time'), auto_now=True) def __str__(self): return f'{self.author.username} - {self.post.title}' my html: {% if user.is_authenticated %} <div class="comment-form"> <h4>Leave a Comment</h4> <form class="form-contact comment_form" action="#" id="commentForm"> <div class="row"> <div … -
Reverse for 'chat_friend' with arguments '('',)' not found
I am building chat app and I am using Django Version 3.8.1. I am stuck on Error. 1 pattern(s) tried: ['chat_friend/(?P<pk>[0-9]+)/$'] This view is for Chat with friend private. views. def chat_friend(request, pk): # Chat info friend = get_object_or_404(User, pk=pk) chat_box = ChatBox.objects.filter( user_1=request.user, user_2=friend).first() if not chat_box: chat_box = ChatBox.objects.filter( user_1=friend, user_2=request.user).first() for message in Message.objects.filter(Q(is_read=False), ~Q(message_sender=request.user)): message.is_read = True message.save() chat_messages_list = Message.objects.filter( chat_box=chat_box).order_by('date') paginator = Paginator(chat_messages_list, 7) if request.GET.get('page'): page = int(request.GET.get('page')) else: page = 0 page = paginator.num_pages - page try: chat_messages = paginator.page(page) except EmptyPage: chat_messages = [] except PageNotAnInteger: chat_messages = paginator.page(paginator.num_pages) if request.method == 'GET' and not request.GET.get('action') and not request.GET.get('page'): return render(request, 'chat_friend.html', {'friend': friend, 'chat_messages': chat_messages, }) elif request.GET.get('page'): return JsonResponse({'chat_messages': serialize('json', chat_messages)}) elif request.GET.get('action') == 'load_new_messages': last_message_id = int(request.GET.get('last_message_id')) chat_messages = Message.objects.filter( chat_box=chat_box, id__gt=last_message_id).order_by('date') return JsonResponse({'chat_messages': serialize('json', chat_messages)}) urls.py path('chat_friend/<int:pk>/', views.chat_friend, name='chat_friend'), profile.html Chat The Problem When i open profile.html in browser after put <a href="{% url 'chat_friend' friend.id %}">Chat</a> link, I got an error named :- ` Reverse for 'chat_friend' with arguments '('',)' not found. 1 pattern(s) tried: ['chat_friend/(?P[0-9]+)/$']`. Please, tell me where is the Problem. When I start a chat through Admin. Chat is working fine with Two … -
Show loading gif until the django view performs the data processing and renders the template with this data
I have a django project where the page has multiple nav links. On clicking any nav link, the urls.py redirects to nav specific view and the view needs to perform some processing to get the data needed to render the template. def nav_view(request): rows = Model.objects.all() data = get_data(rows) # takes about 15-20s return render(request, 'app/nav1.html', {'data': data}) The processing of data required to render the template takes some time in the order of 15-20s and until this time I would like to show a loading gif to the user. As the page is not rendered yet I am not sure how to do this. Could someone please help how to make the view the point to a loading gif on a page until the actual template is rendered. -
Django Form save error due to input field
I created a system with Django. I have several users. This users has comp_name. When a user open signup or signup update page, he/she cannot see this field. It is a hidden field. Only admin can see it. In signup page and admin page there is no error. But in the signup update (profile edit page) the label of comp_name is shown and input is hidden and there is a form error: Select a valid choice. That choice is not one of the available choices. 2-3 days ago it works but now it is not working. What is wrong in my code? models.py class UserProfile(AbstractUser): ranks = ( ('Analyst', 'Analyst'), .... ) comp_name = models.CharField(max_length=200, default='', blank=True, null=True) ... rank = models.CharField(max_length=200, choices=ranks) image = models.ImageField(upload_to='profile_image', blank=True, null= True, default='profile.png') forms.py class SignUpForm(UserCreationForm): email = forms.CharField(max_length=254) rank = forms.ChoiceField(label='What is your role?', choices=UserProfile.ranks) first_name = forms.CharField(max_length=250) last_name = forms.CharField(max_length=250) comp_name = forms.ModelChoiceField(queryset=CompanyProfile.objects.all(), required=False, widget=forms.HiddenInput()) class Meta: model = UserProfile fields = ( 'username', 'first_name', 'last_name', 'email', 'password1', 'password2', 'rank', 'comp_name', 'image') labels = { "comp_name": "" } class SignUpChangeForm(UserChangeForm): email = forms.CharField(max_length=254) rank = forms.ChoiceField(label='What is your role?', choices=UserProfile.ranks) first_name = forms.CharField(max_length=250) last_name = forms.CharField(max_length=250) comp_name = forms.ModelChoiceField(queryset=CompanyProfile.objects.all(), required=False) class … -
Which database and backend is best for an Ecommerce website?
I am currently developing an ecommerce website. I am wondering which database should I use for my site. Relational Database vs Non-Relational Database like SQL vs NoSQL which one is the best? also the stack, I know Django and Node.js (Express) but Django is my primary if I have to say. But I've seen people using MERN stack for eCommerce. So I just want to know which one is the best one. -
how to push new file to a repository in Github using python[Django]
I created a new repository on github.com and I need to push the file that I generated via Django python application, I need to automate the push sequences to GitHub repo once the file is generated using python. I already refer to this How do I push new files to GitHub? But I don't want to provide credential default into the code, I prefer to use login authentication via GitHub authenticator in a web browser and once login it starts to push the generated HTML file. Thank you in Advance!!! -
AttributeError: 'dict' object has no attribute 'parseArrivalDate'
I'm trying to save field from API in his match field in my database, but I'm getting an error: AttributeError: 'dict' object has no attribute 'parseArrivalDate' First I convert the type of it from string to datetime, I printed to see the type and the output is: <class 'datetime.datetime'> But when I tried to save the value of parseArrivalDate also same for departureDate (I'm trying to save first one of them and will make the other) into the database I got the error. Can someone say why it's happened? I also tried different way to convert it everything what I found and researched like make_aware and etc but without success with the saving. from datetime import datetime arrivalDate = response.json()['bookings'][0]['arrival']['date'] print(arrivalDate) parseArrivalDate = datetime.strptime(arrivalDate, '%Y-%m-%d') print(type(parseArrivalDate)) departureDate = response.json()['bookings'][0]['departure']['date'] patientIdWebFlow = response.json()['patient']['patient_id'] patientsIdDB = Patient.objects.values('coreapi_id') for patientIdDB in patientsIdDB: if patientIdWebFlow == int(patientIdDB['coreapi_id']): print('they matched') datesPatients, created = Patient.objects.get_or_create( coreapi_id=int(patientIdDB['coreapi_id']), defaults=dict( date_arrival=patientIdDB.parseArrivalDate, date_departure=patientIdDB.departureDate, ), ) else: print('they not matched') my models.py: class Patient(models.Model): coreapi_id = models.CharField(max_length=100) date_arrival = models.DateField(null=True) date_departure = models.DateField(null=True) -
Getting top N tags attached to each object in Django
With following models: class Tag(models.Model): name = models.CharField(max_length=10) class Restaurant(models.Model): name = models.CharField(max_length=20) class Review(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, related_name='review') tags = models.ManyToManyField(Tag, related_name='review') I want to prefetch top three tags for each Restaurant object like below. Restaurant.objects.prefetch_related(Prefetch('review__tags'), queryset=tag_qs) But I'm having difficulty specifying tag_qs, which may be something like tag_qs = Tag.objects.(...) . How can I get tag_qs so that it contains top three tags for each Restaurant object? -
How to load static files with DEBUG=False in production.py in cPanel
Everything is fine, permission code, path of files, already run collectstatic, just found this error, when DEBUG is True in production.py file CSS and JS is loading and with DEBUG is False, it's not loading. How to resolve this. -
Bootstrap CSS Plotly Height Overlap
I have tried for hours to get this to work right. I just want my graph to fit to the page. Everything inside 100vh. No scrollbars. base.html <body> <nav class="navbar navbar-expand-md navbar-light bg-light"> <div class="container-fluid"> <div class="collapse navbar-collapse"> <ul class='navbar-nav mr-auto'> <li class="nav-item"><a class="nav-link" href="#">item1</a></li> <li class="nav-item"><a class="nav-link" href="{% url 'data' %}">item2</a></li> <li class="nav-item"><a class="nav-link" href="#">item3</a></li> <li class="nav-item"><a class="nav-link" href="#">item4</a></li> </ul> </div> </div> </nav> {% block content %} {% endblock %} </body> base.css html, body { max-height: 100vh; } chart.html {% extends "base.html" %} {% load static %} {% block content %} {% load plotly_dash %} <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> <div class="{% plotly_class name='scatter' %}" style="height: 100%"> {% plotly_app name='scatter' ratio=1 %} </div> {% endblock %} chart.py app.layout = html.Div( [ dcc.Input( id = "input_{}".format(_), type = _, placeholder="input type {}".format(_), ) for _ in ALLOWED_TYPES ] + [ dcc.Graph( id='graph', figure=fig, style={'width': '100%', 'height': '100%'} ) ] ) The chart height doesn't take up the full page like this, only half. But the iframe takes up the whole viewport and more? If I change the app.layout to 'height':'90vh' or something the chart expands but fills in the iframe way down. I've tried wrapping the plotly div in a container-fluid but it … -
How to fix unresolved import error in Django
I'm learning to use Django but I ran into an error. manage.py can no longer import excecute_from_command_line from django.core.management That is, in manage.py file the following line of code isn't working, it's underlined with yellow line in vscode. from django.core.management import excecute_from_command_line I have tried to fix it myself but ain't able to do that. I want someone to help me with the possible cause of this issue. -
How to make a page content editable for a client in django-admin?
I want to make page's content editable so that client can edit the content of a page using Django-admin. -
How to use Class Media in django ModelForm?
How to use this Class Media in ModelForm? where to keep product_form.js? Please help. class ProductForm(forms.ModelForm): class Meta: model = Product fields = ('company', 'manufacturing_unit', 'manufacturing_plant', 'production_block', 'product_name', 'product_code', 'dosage_form', 'contract_giver') widgets = { 'company': autocomplete.ModelSelect2(url='company-autocomplete'), 'manufacturing_unit': autocomplete.ModelSelect2(url='manufacturing_unit-autocomplete-by-company', forward=['company']), 'manufacturing_plant': autocomplete.ModelSelect2(url='manufacturing_plant-autocomplete-by-manufacturing-unit', forward=['manufacturing_unit']), 'production_block': autocomplete.ModelSelect2(url='manufacturing_block-autocomplete-by-manufacturing-plant', forward=['manufacturing_plant']), } class Media: js = ('media/app_js/material_management/product_form.js') -
VSCode Emmet: How to disable certain snippets
For example, in my html file, emmet thinks that the "var" keyword should be a tag on the first suggestion. var -> <var></var> I NEVER use that var, so I'd like to remove it so that the django var comes first. var -> {{ }} How can I do this? -
AttributeError: __name__ running test in djangorestframework 3.8.2
I was currently running on DRF 3.7.7 but working on upgrading to DRF 3.8.2, running against python 3.8. I have a test that was previously passing prior to the upgrade but after the upgrade, I get an error in the test AttributeError: __name__ Note: I've changed up some of the variable names so there may be some inconsistency with the naming if I missed anything class ProductViewSetTestCase(): def setUp(self): super().setUp() self.product = self.create_product() self.client = Client(HTTP_HOST='{}.localtest.me:8000'.format(self.account.domain)) self.client.login(username=self.user, password=self.user_password) def send_refund_request(self, amount=5000): url = reverse('product-refund', kwargs={'pk': self.product.id}) data = json.dumps({'amount': amount, 'reason': 'dont want it!'}) return self.client.post(url, data=data, secure=True, content_type='application/json') @mock.patch('apps.product.api.ProductViewSet.get_object') def test_refund_request_will_succeed(self, mock_get_object): mock_get_object.return_value = self.product with mock.patch.object(self.product, 'process_refund') as process_refund: process_refund.return_value.transaction.product = self.product response = self.send_refund_request() assert response.status_code == HTTP_200_OK The following is the stack trace. It seems to be throwing an error in the reverse method but it's related to the mocking I'm doing in the test case. @mock.patch('apps.product.api.ProductViewSet.get_object') def test_refund_request_will_succeed(self, mock_get_object): mock_get_object.return_value = self.product with mock.patch.object(self.product, 'process_refund') as process_refund: process_refund.return_value.transaction.product = self.product > response = self.send_refund_request() bentobox/apps/product/tests/test_product.py:148: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ … -
Rest Api In Django Rest Framework for personal chat
here is my models.py I am building a one to one chat application in django using django-channels and restframework but cant find a way to build rest api for the project from chat.managers import ThreadManager from django.db import models class TrackingModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: abstract = True class Thread(TrackingModel): THREAD_TYPE = ( ('personal', 'Personal'), ('group', 'Group') ) name = models.CharField(max_length=50, null=True, blank=True) thread_type = models.CharField(max_length=15, choices=THREAD_TYPE, default='group') users = models.ManyToManyField('authentication.User') objects = ThreadManager() def __str__(self) -> str: if self.thread_type == 'personal' and self.users.count() == 2: return f'{self.users.first()} and {self.users.last()}' return f'{self.name}' class Message(TrackingModel): thread = models.ForeignKey(Thread, on_delete=models.CASCADE) sender = models.ForeignKey('authentication.User', on_delete=models.CASCADE) text = models.TextField(blank=False, null=False) timestamp = models.DateTimeField(auto_now=True) def __str__(self) -> str: return f'From <Thread - {self.thread}>' def get_sender_user(self): sender = self.sender if sender: return sender.username return '' and here is manager.py from django.db import models from django.db.models import Count class ThreadManager(models.Manager): def get_or_create_personal_thread(self, user1, user2): threads = self.get_queryset().filter(thread_type='personal') threads = threads.filter(users__in=[user1, user2]).distinct() threads = threads.annotate(u_count=Count('users')).filter(u_count=2) if threads.exists(): return threads.first() else: thread = self.create(thread_type='personal') thread.users.add(user1) thread.users.add(user2) return thread def by_user(self, user): return self.get_queryset().filter(users__in=[user]) and serielizer.py from rest_framework import serializers from chat.models import * from shared.serializers import DateTimeSerializerField class User_Serializer(serializers.ModelSerializer): sender = serializers.CharField(source='get_sender_user') thread = serializers.CharField(source='thread.__str__') … -
django.db.utils.OperationalError 1101. JSON column can't have a default value
I was fiddling around with Django forms and CKEditor when I realised that my forms weren't valid after changing from django's default longtext widget to CK's RichText widget. To try to work around this, idky but I tried changing the model so that the field is nullable: field=models.TextField(blank=True, null=True), This caused me some problems so I tried reverting back: field=models.TextField(blank=True), There was a prompt to fill in a null or something: "Ignore for now, and let me handle existing rows with NULL myself". I carelessly used that option and this has caused a whole host of problems and I can't even rollback to a previous migration anymore. I tried altering the tables manually to set them back to null=False but it didn't solve the problem. I saw something online and tried to alter the table to set default to ("{}") but the command couldn't run due to the same-titled error. I was unsure too, so I filled up all the empty fields of the column in the actual data with "-" so that it isn't empty or null. These methods have not worked so far. Thank you! -
How to create response json from pandas csv in django?
get error when use this df = pd.read_csv('filename.csv', usecols=[1,5,7]) return Response(df.to_json(),status=status.HTTP_200_OK) -
Plotly Dash Graph Inputs to the Right of Graph
I have a plotly graph with input boxes on top. Is there a way to send these input boxes to the right of the graph. I have checked the documentation but it doesn't seem to mention this in the dcc.Input section. https://dash.plotly.com/dash-core-components/input app.layout = html.Div( [ dcc.Input( id = "input_{}".format(_), type = _, placeholder="input type {}".format(_), ) for _ in ALLOWED_TYPES ] + [dcc.Graph(id='graph', figure=fig, style={'width': '90vh', 'height': '90vh'})] ) dcc.Input doesn't seem to have an option for this. Thanks for any help. -
using widgets to change the CSS of label in Django forms
I am trying to apply CSS styling to the admin login form in Django (version 3.1.3). I am able to customise the inputs easily enough using Widgets via the 'forms.TextInput(attrs={'class':'textinputclass'}) method however there seems to be no way to add CSS class to the labels? I can set the label to "false" so that it doesnt show up at all, but ideally I would like to be able to associate a CSS class to it. My code below shows the widgets being used for the text input for username and password. How do I do something similar for the label? ''' class MyAuthForm(AuthenticationForm): class Meta: model = Lesson fields = ['username', 'password'] def __init__(self, *args, **kwargs): super(MyAuthForm, self).__init__(*args, **kwargs) self.fields['username'].widget = forms.TextInput(attrs={'class': 'input', 'placeholder': 'Username'}) self.fields['username'].label = False self.fields['password'].widget = forms.PasswordInput(attrs={'class': 'input', 'placeholder': 'Password'}) self.fields['password'].label = False ''' -
How to populate model's new fields from OneToOneField in Django?
In Django 3.1.2, I would like to copy data in a OneToOneField to multiple fields. I want to change class A(models.Model): name = models.TextField() description = models.TextField() class B(models.Model): a = models.OneToOneField(A, on_delete=models.CASCADE, related_name='b_a') to class A(models.Model): name = models.TextField() description = models.TextField() class B(models.Model): name = models.TextField() description = models.TextField() while keeping existing data. Thank you for your time in advance! -
NameError: name 'TypeError' is not defined in Apache logs
My apache error logs are full of this repeating error message. While my app works fine and apache continues to serve it I am unable to find the cause of other errors because for some reason this is the only thing being logged. My app is a Django app running apache2 and mod-wsgi NameError: name 'TypeError' is not defined Exception ignored in: <function BaseEventLoop.__del__ at 0x7fefd6b13040> Traceback (most recent call last): File "/usr/lib/python3.8/asyncio/base_events.py", line 654, in __del__ NameError: name 'ResourceWarning' is not defined Exception ignored in: <function Local.__del__ at 0x7fefd6b0b430> Traceback (most recent call last): File "/srv/example/env/lib/python3.8/site-packages/asgiref/local.py", line 96, in __del__