Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
serializer showing name of model
I want to serialize data from nested queryset: I have working code but output from serializer showing too many data. I want hide this for security reason. example output: (...) "gallery": "[{"model": "mainapp.imagesforgallery", "pk": 1, "fields": {"user": 1, "image": "uploads/2022/8/6/drw/Adapta-KDE-theme_JOgL4kO.webp", "thumbnail": ""}}]" (...) this is models.py class ImagesForGallery(models.Model): user = models.ForeignKey(UserProfile, null=True, blank=True, on_delete=models.CASCADE) image = models.ImageField(upload_to=user_directory_path, blank=True, null=True) thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True) def __str__(self): return 'User: {} || Image: {}'.format(self.user, self.image) class Gallery(models.Model): project = models.ForeignKey(Projects, null=True, blank=True, on_delete=models.CASCADE) project_gallery = models.ManyToManyField(ImagesForGallery, blank=True, related_name='project_gallery') def __str__(self): return '{}'.format(self.project) This is my view class HomeView(viewsets.ModelViewSet): serializer_class = ProjSerializer queryset = Proj.objects.all() def list(self, request, *args, **kwargs): response = super(HomeView, self).list(request, args, kwargs) gal = Gallery.objects.all() for d in response.data: for g in gal: if d['uuid'] == str(g.project.uuid): qs = g.project_gallery.get_queryset() serialized_obj = serializers.serialize('json', qs) d['gallery'] = serialized_obj return response This code compares the project model to the photo gallery model. If uuid is correct, include this gallery in the project and send json. I'm not sure the code is efficient and safe. The question is how to modify the code so that it does not show the model name. -
Using Below Code i m able to find states present in a country, is There any method to find cities within the given states using python
Using this code i am able to find states of country i want to find all cities within given state, suppose i enter the state name i get all cities within that state from countryinfo import CountryInfo name = "India" country = CountryInfo(name) data = country.info() print(data["provinces"]) -
Why I am getting access denied when enabling the service of the systemctl?
I am configuring a Nginx server in Django. I am in the stage of enabling the /etc/systemd/system/emperor.uwsgi.service but I am getting Failed to enable unit: Access denied error when I am running the command systemctl enable emperor.uwsgi.service. Here emperor.uwsgi.service file's content: [Unit] Description=uwsgi emperor for projet agricole website After=network.target [Service] User=username Restart=always ExecStart=/project_path/my_venv/bin/uwsgi --emperor /project_path/my_venv/vassals --uid www-data --gid www-data [Install] WantedBy=multi-user.target what can I do in order to solve this issue? Please assist. -
TypeError: fromisoformat: argument must be str
[akbar@fedora src]$ ./manage.py migrate Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, core, product, sessions, users Running migrations: Applying blog.0007_blog_created_at...Traceback (most recent call last): File "/home/akbar/Desktop/Tech/E-commerce-Unistore-Wolves/src/./manage.py", line 22, in main() File "/home/akbar/Desktop/Tech/E-commerce-Unistore-Wolves/src/./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/akbar/.local/lib/python3.10/site-packages/django/core/management/init.py", line 446, in execute_from_command_line utility.execute() File "/home/akbar/.local/lib/python3.10/site-packages/django/core/management/init.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/akbar/.local/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/home/akbar/.local/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/home/akbar/.local/lib/python3.10/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "/home/akbar/.local/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 290, in handle post_migrate_state = executor.migrate( File "/home/akbar/.local/lib/python3.10/site-packages/django/db/migrations/executor.py", line 131, in migrate state = self._migrate_all_forwards( File "/home/akbar/.local/lib/python3.10/site-packages/django/db/migrations/executor.py", line 163, in _migrate_all_forwards state = self.apply_migration( File "/home/akbar/.local/lib/python3.10/site-packages/django/db/migrations/executor.py", line 248, in apply_migration state = migration.apply(state, schema_editor) File "/home/akbar/.local/lib/python3.10/site-packages/django/db/migrations/migration.py", line 131, in apply operation.database_forwards( File "/home/akbar/.local/lib/python3.10/site-packages/django/db/migrations/operations/fields.py", line 108, in database_forwards schema_editor.add_field( File "/home/akbar/.local/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 599, in add_field definition, params = self.column_sql(model, field, include_default=True) File "/home/akbar/.local/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 345, in column_sql " ".join( File "/home/akbar/.local/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 296, in _iter_column_sql default_value = self.effective_default(field) File "/home/akbar/.local/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 410, in effective_default return field.get_db_prep_save(self._effective_default(field), self.connection) File "/home/akbar/.local/lib/python3.10/site-packages/django/db/models/fields/init.py", line 910, in get_db_prep_save return self.get_db_prep_value(value, connection=connection, prepared=False) File "/home/akbar/.local/lib/python3.10/site-packages/django/db/models/fields/init.py", line 1408, in get_db_prep_value value = self.get_prep_value(value) File "/home/akbar/.local/lib/python3.10/site-packages/django/db/models/fields/init.py", line 1403, in get_prep_value return self.to_python(value) File "/home/akbar/.local/lib/python3.10/site-packages/django/db/models/fields/init.py", line … -
Display of parent categories does not work
Greetings! I can't solve this problem myself, I have the following code: urls.py re_path(r'^category/(?P<hierarchy>.*)$', show_category, name='category'), I tried different things, settled on two options after the comment "# No category, show top-level content somehow" views.py def show_category(request, hierarchy=None): hierarchy = (hierarchy or "").strip("/") # Remove stray slashes if hierarchy: category_slug = hierarchy.split('/') parent = None for slug in category_slug[:-1]: parent = Categories.objects.get(parent=parent, slug=slug) category = Categories.objects.get(parent=parent, slug=category_slug[-1]) else: category = None if category: return render(request, 'shop/categories.g.html', {'instance': category}) # No category, show top-level content somehow # categories = Categories.objects.all() category = Categories.objects.filter(parent=None) return render(request, 'shop/categories.g.html', {'instance': category}) The problem is that the path /category/window-and-door opens the required category. But with /category/ nothing is displayed, the template uses {{ instance.title }} -
Django: Problem deleting an Authenticated User profile
I'm having problems deleting a user, where the authenticated user can delete their own account. But what happens is that the page just refreshes, in the same template and returning '200 ok from POST' [06/Aug/2022 11:46:33] "POST /members/profile/ HTTP/1.1" 200 4998 members.views.profiles.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User @login_required(login_url="/accounts/login/") def profile(request): template_name = "members/profile.html" context = {} return render(request, template_name, context) def profile_delete(request, pk): user_profile = User.objects.filter(pk=pk) template_name = "members/profile_delete.html" context = { "user_profile": user_profile, }, if request.method == "POST": user_profile.delete() return render(request, template_name, context) return render(request, template_name, context) members.urls.py from django.urls import path from allauth.account import views as allauth_views from . import views app_name = "members" urlpatterns = [ path("login/", allauth_views.LoginView.as_view(), name="login"), path("logout/", allauth_views.LogoutView.as_view(), name="logout"), path("profile/", views.profile, name="profile"), path("profile/<int:pk>/delete/", views.profile_delete, name="profile_delete"), ] profile.html <div> <form method="POST"> {% csrf_token %} <p>Are you sure you want to delete <strong>{{ user | title }}</strong> ?</p> <button class="btn btn-danger" href="{% url 'members:profile_delete' user.pk %}" type="submit"> Delete </button> </form> </div> -
Django getting error exceptions must derive from BaseException
Info: I want to upload files using Uppy in frontend and django-tus as backend for file processing. I am getting error TypeError: exceptions must derive from BaseException. Traceback Internal Server Error: /tus/upload/6393bfe5-277e-4c68-b9af-c0394be796b9 Traceback (most recent call last): File "/home/c0d3/git/django-rus-multi-files/env/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/c0d3/git/django-rus-multi-files/env/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/c0d3/git/django-rus-multi-files/env/lib/python3.10/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/c0d3/git/django-rus-multi-files/env/lib/python3.10/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/c0d3/git/django-rus-multi-files/env/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/c0d3/git/django-rus-multi-files/django_tus/views.py", line 37, in dispatch return super(TusUpload, self).dispatch(*args, **kwargs) File "/home/c0d3/git/django-rus-multi-files/env/lib/python3.10/site-packages/django/contrib/auth/mixins.py", line 71, in dispatch return super().dispatch(request, *args, **kwargs) File "/home/c0d3/git/django-rus-multi-files/env/lib/python3.10/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/home/c0d3/git/django-rus-multi-files/django_tus/views.py", line 82, in head tus_file = TusFile.get_tusfile_or_404(str(resource_id)) File "/home/c0d3/git/django-rus-multi-files/django_tus/tusfile.py", line 75, in get_tusfile_or_404 raise TusResponse(status=404) TypeError: exceptions must derive from BaseException [06/Aug/2022 14:36:42] "HEAD /tus/upload/6393bfe5-277e-4c68-b9af-c0394be796b9 HTTP/1.1" 500 103054 [06/Aug/2022 14:36:42,624] - Broken pipe from ('127.0.0.1', 35814) [06/Aug/2022 14:36:42] "POST /tus/upload/ HTTP/1.1" 201 0 [06/Aug/2022 14:36:42] "PATCH /tus/upload/8295bef4-c94a-4ab7-9c75-2635c74428d8 HTTP/1.1" 204 0 https://github.com/alican/django-tus/blob/master/django_tus/tusfile.py class TusUpload(View): def head(self, request, resource_id): tus_file = TusFile.get_tusfile_or_404(str(resource_id)) return TusResponse( status=200, extra_headers={ 'Upload-Offset': tus_file.offset, 'Upload-Length': tus_file.file_size, }) def create_initial_file(metadata, file_size: int): resource_id = str(uuid.uuid4()) cache.add("tus-uploads/{}/filename".format(resource_id), "{}".format(metadata.get("filename")), settings.TUS_TIMEOUT) cache.add("tus-uploads/{}/file_size".format(resource_id), file_size, settings.TUS_TIMEOUT) cache.add("tus-uploads/{}/offset".format(resource_id), … -
In a registration form there are 5 different phone numbers for one user i need to store all 5 numbers in different table(In django). How to solve this
in models.py class UserForm(models.Model): name = models.CharField('Name',max_length=20) email = models.EmailField(max_length=20) city = models.CharField(max_length=20) class Meta: db_table = 'userform' def __str__(self): return self.name class PhoneNumber(models.Model): user = models.ForeignKey(UserForm, on_delete=models.CASCADE) # phone = models.CharField(user, max_length=10) phone1 = models.CharField(user, 'Phone',max_length=10, blank=True) phone2 = models.CharField(user, max_length=10, blank=True) phone3 = models.CharField(user, max_length=10, blank=True) phone4 = models.CharField(user, max_length=10, blank=True) phone5 = models.CharField(user, max_length=10, blank=True) class Meta: db_table = 'phonenumber' I tried applying this method, i have a confusion that how to manage view.py and html form file -
Django creating multiple groups with post_save
I need to auto-create several groups with a post_save signal. I almost have this working however, as a novice, I can't get the syntax right. When I use the code below, instead of two groups, I get one group with the name ('manager', 'employee'). How would I change this to add two groups - manager and employee? # autocreate basic employee groups when new company is created @receiver(post_save, sender=Tenant) def create_basic_group(sender, created, **kwargs): if created: # Get or create group new_group, created = Group.objects.get_or_create( name=('manager', 'employee')) -
Django, how to save a randomly generated variable for the next session after POST method
I have an integer in Views.py which is generated randomly. I send it to Index.html: return render(request, 'index.html', {'number':number}) Then I have a simple form in forms.py class AForm(forms.Form): information = forms.CharField(label='Your answer', max_length=100) And this form in Index.html with POST method: <form action="{% url 'index' %}" method = POST> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> which leads to the same page and function. And I want to return via this POST method that number which I previously sent, because now it is already another, taken randomly, because it is the same function. But I already need the previous one. In other words I generate a random number and I need to save it for the next loading, after POST Method. I would even not send that number anywhere if it is possible. Is there a simple, elegant way to do it? I've read about sessions in Django, probably it is the way, but is there an easier way? Thanks. -
The concatenation returns me the name of the variable
I want to create an alert to delete users with sweetAlert, but in the script tag when I create my url from a variable passed as a parameter in the function, the result is only the name of the variable to display and not its value function delInscPart(id){ var url = "{% url 'suppPartners' " +id+" %}" Swal.fire({ "title":"Etes vous sure de vouloir supprimé l invité ?", "text":"Si vous confirmer cette opération, Vous supprimerais cette invité !", "icon":"", "showCancelButton":true, "cancelButtonText":"Anuller", "confirmButtonText":"Je confirme", "reverseButtons":true, }).then(function(result){ if(result.isConfirmed){ window.location.href = url console.log(url) } }) } <td><a href= "#" onClick="delInscPart('{{list.user_inscrit.username}}');"><i data-feather="trash-2"></i>Supprimer</a></td> the result is {% url 'suppPartners' +id+ %} instead {% url 'suppPartners' admin %} -
PyCharm: Cannot connect to postgres-db in docker container
as the title says, I'm having trouble to connect a rather simple database-configuration with my IDE PyCharm. docker-compose.yml db: restart: always image: postgres container_name: db volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=postgres ports: - "5432:5432" networks: - db-net Using it with django, here are my database-settings from the backend, which are working perfectly fine: settings.py DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "postgres", "USER": "postgres", "PASSWORD": "postgres", "HOST": "db", "PORT": 5432, } } But when trying to connect the database inside PyCharm with the following settings, I'm getting this error: Note: The field for password was of course filled -> get's cleared everytime someone hits Apply or tries to test the connection. Does anyone might know what I'm doing wrong or maybe had the same problem? Thanks for your help and have a great weekend! -
How Can I Check if Date is Passed from Django Model
I am really new in Django and I want to check if Date Stored in Model is passed. In fact, I am currently working on a ticketing app where users would have to purchase and activate ticket and I want to check if the Event Ticket Date is passed upon activation. My Models: class Event(models.Model): event_name = models.CharField(max_length=100) date = models.DateField(auto_now_add=False, auto_now=False, null=False) event_venue = models.CharField(max_length=200) event_logo = models.ImageField(default='avatar.jpg', blank=False, null=False, upload_to ='profile_images') added_date = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.event_name}" #Prepare the url path for the Model def get_absolute_url(self): return reverse("event_detail", args=[str(self.id)]) class Ticket(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) price = models.PositiveIntegerField() category = models.CharField(max_length=100, choices=PASS, default=None, blank=False, null=False) added_date = models.DateField(auto_now_add=True) def __str__(self): return f"{self.event} " #Prepare the url path for the Model def get_absolute_url(self): return reverse("ticket-detail", args=[str(self.id)]) def generate_pin(): return ''.join(str(randint(0, 9)) for _ in range(6)) class Pin(models.Model): ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE) value = models.CharField(max_length=6, default=generate_pin, blank=True) added = models.DateTimeField(auto_now_add=True, blank=False) reference = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4) status = models.CharField(max_length=30, default='Not Activated') #Save Reference Number def save(self, *args, **kwargs): self.reference == str(uuid.uuid4()) super().save(*args, **kwargs) def __unicode__(self): return self.ticket class Meta: unique_together = ["ticket", "value"] def __str__(self): return f"{self.ticket}" def get_absolute_url(self): return reverse("pin-detail", args=[str(self.id)]) My Views for … -
How to loop websocket events in django in a roulette game
Hello fellow programmers, I'm currently using Django with WebSockets to create a replica close to https://bloxflip.com/roulette or any kind of online synchronized roulette you can have that involves multiple bets from all different players. I am at this stage attached image, and I'm trying to create a backend loop that will run between states (Waiting for bets, Calculating hashes, Rolling, Restarting), the only solution I got is using workers from Celery that will loop it on a Redis server. I wonder if there is any other solution that can help me make this loop in the backend so I can send it to the frontend with WebSockets. Let me know what other method i can use or if i can improve my actual code. consumers.py class RouletteConsumer(WebsocketConsumer): def connect(self): self.room_group_name = 'roulette' async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept()` current_state = states[0] self.send(text_data=json.dumps({ 'type':'current_state', 'current_state': current_state })) def receive(self, text_data): text_data_json = json.loads(text_data) bet_data = text_data_json['bet_data'] async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type':'send_bet', 'bet_data': bet_data, } ) def send_bet(self, event): bet_data = event['bet_data'] self.send(text_data=json.dumps({ 'type':'bet', 'bet_data': bet_data })) def current_state(self, event): state = event['current_state'] self.send(text_data=json.dumps({ 'type':'state', 'current_state': state })) -
How to store token from another api in Django?
In my DJango application I use another API external to my application. To authenticate on the external API, I must first make a POST with my credentials, and get a JWT token. Once this token is retrieved, I have to put it in the headers to be able to make requests on the api. Once the token is retrieved (thanks to requests), how to store it in a "global" way to be able to reuse it until it expires ? -
Store the primary key but display the name of an instance in Django Forms
I created a form through which the user can send an email to customers. I wanted to create a UI where the user can select a customer from the list of customers and automatically after clicking the customer, the email field is updated(i.e., the customer's email). I have done this before and the Foreign Key relation works the best but in this case, I think there is no need to create a different app for Email support and then give the foreign relations, etc. forms.py: class EmailForm(forms.Form): customer = forms.CharField(widget=forms.Select) email = forms.CharField(max_length=100) subject = forms.CharField(max_length=100) attach = forms.FileField() message = forms.CharField(widget = forms.Textarea) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['customer'].widget.choices = [(i.name, i.name) for i in Customer.objects.all()] email.html: {{ customer_data|json_script:"customerdata" }} <script type="text/javascript"> var customerdata = JSON.parse(document.getElementById('customerdata').textContent); document.getElementById('id_customer').onchange = function(event){ var cust = customerdata.find(({customer_id}) => customer_id == event.target.value); document.getElementById('id_email').value = cust && cust.email ? cust.email : ""; }; I am passing the Customer data to the email.html using JSON but I am not able to assign the email to the appropriate field because id_customer returns a String, i.e., The customer name and not the customer_id as I want. I understand that I am purposely displaying the customer_name instead of … -
Django.urls reversing urls through multiple url pattern lists within one app
I have a url.py inside my project which includes the following urls.py (belongs to my app). urls.py from django.urls import path,include from .views import Index, Foo bar_urlpatterns = [ path('foo/', Foo.as_view(), name='foo'), ] urlpatterns = [ path('', Index.as_view(), name='index'), path('bar/', include(bar_urlpatterns)),] I'm trying to outsource the subpaths of a path. The docs says the function include can include a pattern_list and when i call the url"http://myurl/foo/bar" directly, this seems to hold true. I can also load the view via ajax directly when i give it the string. But when i try to use the reverse {%url 'foo'} url template tag this throws: Uncaught SyntaxError: Invalid regular expression flags(at ...) Doing the same thing with non-outsourced url patterns works perfectly fine for me. The html elements where i use the function: <a onclick="load_tab_view({% url "foo" %})">Foo</a> <div id="tab_view_replaceable"></div> js (works fine with my other views) function load_tab_view(url){ replace_id = 'tab_view_replaceable'; $.ajax({ url: url, type: 'GET', dataType: 'html', success: function(data){ $('#'+replace_id).html(data); } }); } Is there a way in which im still able to outsource my subpaths and make use of the reverse url template tag? (I dont want to create a new app for bar) -
Celery scheduler not performing the task
I was trying to use Celery to query an external api at a regular frequency and update my database in my Django project with the new data. Celery schedules the task correctly and sends it to the celery worker but it never executes anything. Here is my celery.py file which is at the same level as my settings.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings from celery.schedules import crontab os.environ.setdefault("DJANGO_SETTINGS_MODULE", "data_analysis.settings") app = Celery("data_analysis") app.conf.enable_utc = False app.conf.update(timezone= 'Asia/Kolkata') app.config_from_object(settings, namespace="CELERY") app.autodiscover_tasks() app.conf.beat_schedule = { 'update_all_api':{ 'task':'operations.tasks.celery_update', 'schedule': 30.0, } } @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') This is my tasks.py which is inside an app named 'operations': from celery import shared_task import time from operations.models import Machine, MachineData from operations.analytics.processing import get_data @shared_task(bind=True) def celery_update(self): print('Running Update') print('The time is :' + str(time.asctime(time.localtime(time.time())))) print('Getting Data ...') all_machines = Machine.objects.all() for machine in all_machines: data_list = get_data(machine.api_url) for data in data_list: # print(data) if not MachineData.objects.filter(data=data): print('New Data received for :' + str(machine)) MachineData.objects.create(machine=machine, data=data) else: print('No new data for : ' + str(machine)) return 'done' The scheduler sends the task to the celery worker, but it never executes the function. Here is … -
HOW TO PULL ALL USERS FROM AD AND STORE THEM IN DATABASE BY USING DJANGO AUTH LDAP
I am Using Django 4.4, I have managed to authenticate users by using django-auth-ldap.But I can not get all users records to my database. I have tried to follow instructions from this link using the filter "sAMAccountType=805306368)", It gives all users and their groups but they cant be updated to django admin panel, Users are only displayed in the debug file only and users can not be binded to login here is how my configurations look like AUTH_LDAP_SERVER_URI = "mydomain.com" AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_REFERRALS: 0 } AUTH_LDAP_BIND_DN = "user@mydomain" AUTH_LDAP_BIND_PASSWORD = "password" LDAP_IGNORE_CERT_ERRORS = True AUTH_LDAP_USER_SEARCH = LDAPSearch( "DC=mydomain,Dc=com", ldap.SCOPE_SUBTREE, "(sAMAccountType=805306368)" ) AUTH_LDAP_GROUP_TYPE = PosixGroupType(name_attr='cn') -
Webpack is compiling successfully but changes are not reflected in React App
I am using Django to host the react app which is being compiled by babel and bundled using webpack. The webpack shows me a compiled successfully message like below but the changes aren't reflected. The funny thing is when I wait for a bit, it works but that too sometimes with no linear pattern. I am getting mad about this, please help! I saw that, since I am using OSX, it is getting corrupted as the github issue says: https://github.com/webpack/webpack-dev-server/issues/24 but it is not helping! npm run dev > frontend@1.0.0 dev > webpack --mode development --watch asset main.js 1.32 MiB [compared for emit] [minimized] (name: main) 1 related asset runtime modules 1.04 KiB 5 modules modules by path ./node_modules/ 1.2 MiB modules by path ./node_modules/axios/ 56.8 KiB 32 modules modules by path ./node_modules/react-dom/ 1000 KiB 3 modules modules by path ./node_modules/react/ 85.7 KiB 2 modules modules by path ./node_modules/scheduler/ 17.3 KiB 2 modules + 5 modules modules by path ./src/ 36.6 KiB modules by path ./src/components/*.js 30.3 KiB ./src/components/App.js 1.58 KiB [built] [code generated] + 9 modules modules by path ./src/*.js 6.33 KiB ./src/index.js 35 bytes [built] [code generated] + 2 modules webpack 5.74.0 compiled successfully in 2567 ms assets … -
Django cannot save to to second database
i've tried using multiple database in my django projects, then i create a models with foreign key to User, it can't save to second database this is the UserData models class UserData(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user', related_query_name='user') is_controller = models.BooleanField(default=False) phone_number = models.CharField(max_length=255, blank=True, null=True) then in views instance = UserData( user=request.user, nim=nim, phone_number=phone ) after that, i save the instance >>> instance.save() #it works on default database (sqlite) >>> instance.save(using='db_alias') # return an error the error said it was cannot add or update child row because of the foreign key (1452, 'Cannot add or update a child row: a foreign key constraint fails (labs.presence_userdata, CONSTRAINT presence_userdata_user_id_4b3dfc56_fk_auth_user_id FOREIGN KEY (user_id) REFERENCES auth_user (id))') can anyone help me solve this problem -
Django, create table or page just to join all other tables into one and show it. is it possible?
I want to show info from different tables together in another page or table. But I don't want create another table with duplicate info. Is it possible to Join many tables and show in some admin page? -
How to get value of a nested serializer field from its parent serializer class?
Consider the followings two serializers: class SerializerA(BaseSerializer): field_1 = serializers.IntegerField() field_2 = SerializerB() class SerializerB(BaseSerializer): field_3 = serializers.IntegerField() The input JSON for SerializerB will not contain field_3 and it has to obtained from field_1 of SerializerA. I have tried this class SerializerB(BaseSerializer): field_3 = serializers.IntegerField() def __init__(self, instance=None, data=empty, **kwargs): if data is not empty and isinstance(data, dict): _data = data.copy() _data['field_3'] = self.parent.initial_data.get('field_1') super(SerializerB, self).__init__(instance, _data, **kwargs) super(SerializerB, self).__init__(instance, data, **kwargs) But it is not working as data is always empty and it never passes the if statement. -
The admin isn't submitting data in django
I have written this code using django: in models.py(in the app): class Feature2(models.Model): name = models.CharField(max_length=100) detail = models.CharField(max_length=500) in URLs.py(in the app) urlpatterns = [ path('2', views.index, name='index2'), ] in admin.py(in the app): 'admin.site.register(Feature2)' in app's templates (index2.html): <div class="row icon-boxes"> {% for feature in xfeatures %} <div class="col-md-6 col-lg-3 d-flex align-items-stretch mb-5 mb-lg-0" data-aos="zoom-in" data-aos-delay="200"> <div class="icon-box"> <div class="icon"><i class="ri-stack-line"></i></div> <h4 class="title"><a href="">{{feature.name}}</a></h4> <p class="description">{{feature.details}}</p> </div> </div> {%endfor%} </div> </div> in views.py (in app): def index2 (request): xfeatures = Feature2.objects.all() return render(request,'myapp/index2.html', {'xfeatures': xfeatures}) in urls.py in project: urlpatterns = [ path('admin/', admin.site.urls), path('myapp/', include("myapp.urls")) ] when I run admin in the browser and enter data in features2 this appears to me: in this photo so what is wrong in my code? -
Django template filter remove image
My Problem I was making posts and postdetail page using summernotes. I using summetnote made 2 pictures and sentences I use truncatechars_html:100|safe I want to image remove in the post page I want to show photos uploaded to summernote only when I go to postdetail. post.html content code without using safe I just want the image to be invisible <div style="text-align: center;">Make post and two image</div> <div style="text-align: center;"><br></div><div style="text-align: center;">wdljawlkdjkawd</div> <div style="text-align: center;"><img src="/media/django-summernote/2022-08-06/31910af9-4366-48ad-aae1-8fc523d87181.jpg" style="width: 698.011px;"><br></div> <div style="text-align: center;"><img src="/media/django-summernote/2022-08-06/3c7f7804-a5d7-4cd3-b69b-bea66fd6b121.png" style="width: 698.011px;"><br></div> post.html <div class="container mt-5"> <div class="row"> <div class="col-lg-12"> <!-- Post content--> <article> <!-- Post header--> {% for post in Post_list %} <header class="mb-4"> <!-- Post title--> <h1 class="fw-bolder mb-1"><a href="{% url 'post_detail' post.id %}"> {{ post.title }}</a></h1> <!-- Post meta content--> <div class="text-muted fst-italic mb-2">{{ post.create_time }}</div> </header> <section class="mb-5"> <p class="fs-5 mb-4">{{ post.content|truncatechars_html:100|safe }}</p> </section> {% endfor %} </article> </div> </div> </div> post_detail.html <div class="container mt-5"> <div class="row"> <div class="col-lg-12"> <!-- Post content--> <article> <!-- Post header--> <header class="mb-4"> <!-- Post title--> <h1 class="fw-bolder mb-1"><a href=""> {{ post.title }}</a></h1> <!-- Post meta content--> <div class="text-muted fst-italic mb-2">{{ post.create_time }}</div> </header> <section class="mb-5"> <p class="fs-5 mb-4">{{ post.content|safe }}</p> </section> </article> </div> </div> </div>