Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Loading module from “https://app.herokuapp.com/assets/index.1ab7e925.js” was blocked because of a disallowed MIME type (“text/html”)
index.html <!DOCTYPE html> <html lang="en"> <head> <meta content="text/html;charset=utf-8" http-equiv="Content-Type"> <meta content="utf-8" http-equiv="encoding"> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <base href="./"> <title>PzCompare</title> <script type="module" crossorigin src="/assets/index.1ab7e925.js"></script> <link rel="modulepreload" type="text/javascript" href="/assets/vendor.d0b4acaa.js"> <link rel="stylesheet" href="/assets/index.e7475acf.css"> </head> <body> <div id="root"></div> </body> </html> All of the css and js files are not being loaded because of this error 'blocked because of a disallowed MIME type (“text/html”)', no idea how to fix this, any help is appreciated! -
IntegrityError at /authentication/addProfilePic/ UNIQUE constraint failed: authentication_userprofile.user_id
I am working with a blog project where I am trying to add profile picture of the user. whenever I submit the picture It gives me UNIQUE constraint failed:authentication_userprofile.user_id. views.py from .forms import ProfilePic def add_pro_pic(request): form= ProfilePic() if request.method=='POST': form=ProfilePic(request.POST,request.FILES) if form.is_valid: user_obj=form.save(commit=False) user_obj.user=request.user user_obj.save() return redirect('profile') return render(request,'profilePic.html',{'form':form}) models.py from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user=models.OneToOneField(User,related_name='user_profile',on_delete=models.CASCADE) profile_pic=models.ImageField(upload_to='profile_pics') forms.py from. models import UserProfile from django import forms class ProfilePic(forms.ModelForm): class Meta: model=UserProfile fields=['profile_pic'] here comes profilePic.html {% extends 'base.html' %} {% block content %} <h2>Add Profile Pic</h2> <form method="POST" enctype="multipart/form-data"> {{form.as_p}} {% csrf_token %} <button type="submit" name='button' class="btn btn-success btn-sm">Add</button> {% endblock %} But the server shows me this UNIQUE constraint failed: authentication_userprofile.user_id IntegrityError at /authentication/addProfilePic/ UNIQUE constraint failed: authentication_userprofile.user_id Request Method: POST Request URL: http://localhost:8000/authentication/addProfilePic/ Django Version: 3.2.8 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: authentication_userprofile.user_id Exception Location: C:\Users\ITS\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: C:\Users\ITS\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.0 Python Path: ['C:\\Users\\ITS\\Desktop\\blog_project\\blogproject', 'C:\\Users\\ITS\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\ITS\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\ITS\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\ITS\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\ITS\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'] Server time: Tue, 14 Dec 2021 19:40:04 +0000 where is the problem? thanks in advance. -
Add model methods to Django model on a per-app basis? Model shared among apps
I am curious as to how best to handle this situation: I've got an app that has a User model (AbstractUser); it includes all the usual attributes (username, is_superuser, is_staff, etc.) This app is shared among multiple projects (which all have their own apps) The structure looks like something like this: Project X App A App B Project Y App A App C App D Project Z App A App E App F I'm at a point where I need to add a model method on that User model in Project Z to make life easier. It would do some business logic involving other models from the other related apps. Filtering stuff from App E and App F and what not. I can't add that method directly to the User model, because then the other projects would fail since they don't have access to those other projects. What is the best way to accomplish this in Django? -
Django - resource was not found on this server on production
I am trying to access these files used from the django-import-export-celery module: I am able to see my view on local: But its not showing on my production server: This is my urlpattern: urlpatterns = static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) + [ # favicon path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url('img/Dalmore-Group-16-16.png'))), # debug path('__debug__/', include(debug_toolbar.urls)), url(r'^', admin.site.urls), ] And my settings.py has: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') -
How to deal with circular relationship in Django models?
I'm trying to write a basic DB to offer my photographs. It seemed so simple, but I just can't wrap my head around this, despite thinking for a couple of weeks. I'm trying to combine multiple models that link to each other. Photo: Files with some stored dataPerson: Data about a person that appears in a photo / has mad a Quote Quote: Something a Person has said and needs to be attached to Photos (the quote does not belong to all photos of that person, but rather a specific set) Offer: An overview that has all the quotes with one Photo as a thumbnail and all the Photos (some photos might have the same quote, but it should only appear once) As a mockup and because people here really love to see some code first I made this: class Quote: person = models.ForeignKey("Person") photos = models.ManyToManyField("Photo") class Person: photo = models.ForeignKey("Photo") class Photo: pass class Offer: quotes = models.ManyToManyField("Quote") photos = models.ManyToManyField("Photo") Please take the code above as an illustration, because I already don't know how to tackle this. I tried multiple different versions, but there is always some case that doesn't get covered. In the above example the … -
How to Ignore Required Fields when updating user account details Django-Rest, ReactJS
I have made a field for profile image in database: serializers.py class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model=User fields=('id','username','email','password','first_name','last_name','profile_image') models.py I have made the following function for upload def upload_path(instance, pos, filname): return '/'.join(['profiles', filname]) User Class class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) username = models.CharField(max_length=255, unique=True) first_name = models.CharField(max_length=255, unique=False, default='') last_name = models.CharField(max_length=255, unique=False, default='') is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) objects = UserAccountManager() profile_image = models.ImageField( blank=True, null=True, upload_to=objects.upload_path) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] views.py My post method is: def post(self, request): serializer = PostCreateSerializer(data=request.data) if serializer.is_valid(): serializer.save() items = Post.objects.all() serializer = PostCreateSerializer(items, many=True) return Response(serializer.data, status=status.HTTP_200_OK) serializer_class = UserCreateSerializer if serializer_class.is_valid(): serializer_class.save() queryset = User.objects.all() profile_image = request.data['profile_image'] User.objects.create(queryset, profile_image=profile_image) return HttpResponse({'message':'profile image uploaded'}, status = 200) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) On my ReactJS frontend, I am doing the following: I have made the following axios post method: export const uploadProfile = (profile_image, id) => async (dispatch) => { const config = { headers: { "Content-Type": "application/json", }, }; const body = JSON.stringify({ profile_image }); alert("1234"); console.log(body) try { await axios.post( `${process.env.REACT_APP_API_URL}auth/users/`, body, config ); console.log(Response); dispatch({ type: UPLOAD_SUCCESS, }); } catch (err) { dispatch({ type: UPLOAD_FAIL, }); } }; This is the form … -
Count how many times value appears in table
Within my app, I have some forms that allow the user to select from a dropdown and I'm trying to count how many times RED, GREEN and AMBER have been selected across 20 different fields. I was looking at from django.db.models import Count queryset = MyModel.objects.all().annotate(count = Count('my_charfield')) But I'm not sure how to count the values rather than the field type? Thanks -
Django not showing images in editor (404 error)
I'm try create post and add to this post images. And i'm use for this Django-summernote in Django 3.0. Picture upload to folder on hard disk, but not showing in editor. Console show 404 Error. Please, give me advice how to fix it? Thank you! settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' ADMIN_MEDIA_PREFIX = STATIC_URL + "grappelli/" X_FRAME_OPTIONS = 'SAMEORIGIN' SUMMERNOTE_THEME = 'bs4' # Show summernote with Bootstrap4 MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py urlpatterns = [ path('admin/filebrowser/', site.urls), path('summernote/', include('django_summernote.urls')), path('admin/', admin.site.urls), path('', include('blog.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) image = models.ImageField(upload_to="", blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def get_absolute_url(self): return "/api/article/%i/" % self.id def __str__(self): return self.title screenshot from console -
UUID fails unit pytest due to formatting?
I am returning a user's UUID in my serializier and this works fine. However, when writing a unit test to test this return the test fails despite them being called the same way. Below is a simplified version of my code. My serializers.py: class UserSerializer(serializers.ModelSerializer): user_sso = serializers.SerializerMethodField("get_user_sso") class Meta: model = get_user_model() fields = ( "user_sso", ) def get_user_sso(self, user): return user.profile.sso_id My unit test in test_views.py class TestUserAPIView(BaseAPIViewTest): factory = factories.UserFactory def expected_response(self, user): return { "user_sso": user.profile.sso_id, } The failed test message (the user generated from a factory is the top one): E - 'user_sso': UUID('f696d740-bdd5-43a3-8f58-406b7a1e117d')}, E ? ----- - E + 'user_sso': 'f696d740-bdd5-43a3-8f58-406b7a1e117d'}, How do I make this test pass? I do not have the word 'UUID(' at the begining of my current output which looks to be the problem but I'm not sure how to remove this without everything a string? Many thanks. -
Why is Elastic beanstalk app creation failing at [InstallDependency] python3.8
I've rebuilt the requirements.txt multiple times, and removed and re-created pipenv, but still every time I build the deployment package for elastic beanstalk, the deployment fails giving this error: 2021/12/14 18:31:40.411896 [ERROR] An error occurred during execution of command [app-deploy] - [InstallDependency]. Stop running the command. Error: fail to install dependencies with Pipfile file with error Command /bin/sh -c /usr/bin/python3.8 -m pipenv install --skip-lock failed with error exit status 1. Stderr:Warning: Your Pipfile requires python_version 3.8, but you are using unknown (/var/app/s/.venv/bin/python). $ pipenv --rm and rebuilding the virtual environment may resolve the issue. $ pipenv check will surely fail. Error while executing command /var/app/staging/.venv/bin/python -c import sysconfig, distutils.sysconfig, io, json, sys; paths = {u'purelib': u'{0}'.format(distutils.sysconfig.get_python_lib(plat_specific=0)),u'stdlib': u'{0}'.format(sysconfig.get_path('stdlib')),u'platlib': u'{0}'.format(distutils.sysconfig.get_python_lib(plat_specific=1)),u'platstdlib': u'{0}'.format(sysconfig.get_path('platstdlib')),u'include': u'{0}'.format(distutils.sysconfig.get_python_inc(plat_specific=0)),u'platinclude': u'{0}'.format(distutils.sysconfig.get_python_inc(plat_specific=1)),u'scripts': u'{0}'.format(sysconfig.get_path('scripts')),u'py_version_short': u'{0}'.format(distutils.sysconfig.get_python_version()), }; value = u'{0}'.format(json.dumps(paths));fh = io.open('/tmp/tmpn2omzq7a.json', 'w'); fh.write(value); fh.close():Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/pipenv/vendor/vistir/misc.py", line 513, in _create_subprocess c = _spawn_subprocess( File "/usr/local/lib/python3.8/site-packages/pipenv/vendor/vistir/misc.py", line 190, in _spawn_subprocess return subprocess.Popen(cmd, **options) File "/usr/lib64/python3.8/subprocess.py", line 854, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "/usr/lib64/python3.8/subprocess.py", line 1702, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) OSError: [Errno 8] Exec format error: '/var/app/staging/.venv/bin/python' Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/pipenv/vendor/vistir/contextmanagers.py", line 205, in spinner yield _spinner File "/usr/local/lib/python3.8/site-packages/pipenv/vendor/vistir/misc.py", line 618, in run … -
Django Serializer only serializing objects with many=True
I am trying to make a serializer class StoreSerializer(serializers.ModelSerializer): class Meta: model = Store fields = '__all__' and in the viewset, def list(self, request, *args, **kwargs): obj = Store.objects.first() ser = StoreSerializer(data=obj) if ser.is_valid(): pass print(ser.data) return Response(ser.data) this method is returning just an empty dict {} as the response. When defining the serializer as ser = StoreSerializer(data=[obj], many=True) the object is getting serialized. What am I doing wrong here? -
Django-import-export-celery Import error [Errno 13] Permission denied
I have a minor issue where I always see an error 13: Import error [Errno 13] Permission denied: '/_/_/_/media/django-import-export-celery-import-change-summaries' I can still import but I cannot see the end HTML template. It's supposed to look like this (on my windows localhost): I believe this is an Ubuntu file permission issue but I do not want to do anything because as I understand it, granting permissions on a production server is dangerous. Any help is appreciated. Thanks! -
OperationalError: no such table: users_profile in Django
I am trying to create an extend User model but when I start the server I get an OperationalError: no such table: users_profile. Here is a structure of the project: │ db.sqlite3 │ manage.py │ ├───ithogwarts │ │ asgi.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └───__pycache__ │ ├───main │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ │ ├───static │ │ └───main │ │ ├───css │ │ │ footer.css │ │ │ header.css │ │ │ index.css │ │ │ │ │ ├───img │ │ │ │ │ └───js │ │ script.js │ │ │ ├───templates │ │ └───main │ │ index.html │ │ layout.html │ │ level_magic.html │ │ │ └───__pycache__ │ ├───templates │ └───registration └───users │ admin.py │ apps.py │ forms.py │ models.py │ tests.py │ urls.py │ utils.py │ views.py │ __init__.py │ ├───migrations │ │ 0001_initial.py │ │ __init__.py │ │ │ └───__pycache__ │ ├───static │ └───users │ └───css │ login.css │ register.css │ ├───templates │ └───users │ login.html … -
Add some data to extra_context in response_change
I have some model: from django.db import models class Deviation(models.Model): name = models.CharField(max_length=100) def calc(self): # some calculation return 1 Then I added a button that runs calc method (overrided change form): {% extends 'admin/change_form.html' %} {% block submit_buttons_bottom %} {{ block.super }} <div class="submit-row"> <input type="submit" value="Calculate" name="calc"> </div> Calculation result: {{ result }} {% endblock %} This model is registered in admin with handling calc button submit (pass result in extra_context): @admin.register(Deviation) class DeviationAdmin(admin.ModelAdmin): change_form_template = 'admin/deviations_change_form.html' list_display = '__str__', def response_change(self, request, obj): if "calc" in request.POST: obj.save() result = obj.calc() return self.change_view(request, str(obj.id), form_url='', extra_context={'result': result}) return super().response_change(request, obj) Here problem happening. I cannot render change view with result through extra_context. How can I pass extra_context to change view? -
ModuleNotFoundError: No module named 'api' (heroku)
tree ├───pzApi │ │ asgi.py │ │ db.sqlite3 │ │ manage.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └───api │ │ apps.py │ │ funcs.py │ │ urls.py │ │ views.py │ │ __init__.py Procfile release: python pzApi/manage.py migrate web: gunicorn --bind 127.0.0.1:8000 pzApi.wsgi:application I'm still trying to deploy this web app and after fixing the wsgi.py not found error by putting it in the same dir as manage.py, now I have another problem where the 'api' folder is not being found, any help is appreciated! -
How to clear a ManyToMany Field in a patch request?
My ManyToMany Relationship doesn't reset. I'm doing a patch requests that translates into djrf's partial_update. But afterwards RecordUsersEntry still has the same users saved it got from setup_entry. I've tried a put request with field and record, and then the many to many relationship is resetted, but I want to reset it with a patch request. Might be related to: https://github.com/encode/django-rest-framework/issues/2883, however I'm going to use JSON Requests and at the moment I'm only concerned about how to get this test green. I've written the follwing test: def test_entry_update(self): self.setup_entry() view = RecordUsersEntryViewSet.as_view(actions={'patch': 'partial_update'}) data = { 'users': [] } request = self.factory.patch('', data=data) force_authenticate(request, self.user) response = view(request, pk=1) self.assertEqual(response.status_code, 200) entry = RecordUsersEntry.objects.first() self.assertEqual(entry.users.all().count(), UserProfile.objects.none().count()) # <-- The test fails here with def setup_entry(self): self.entry = RecordUsersEntry.objects.create(record=self.record, field=self.field) self.entry.users.set(UserProfile.objects.all()) and the model looks like this: class RecordUsersEntry(RecordEntry): record = models.ForeignKey(Record, on_delete=models.CASCADE, related_name='users_entries') field = models.ForeignKey(RecordUsersField, related_name='entries', on_delete=models.PROTECT) users = models.ManyToManyField(UserProfile, blank=True) class Meta: unique_together = ['record', 'field'] verbose_name = 'RecordUsersEntry' verbose_name_plural = 'RecordUsersEntries' def __str__(self): return 'recordUsersEntry: {};'.format(self.pk) Viewsets and Serializer just being the basic ones: class RecordUsersEntryViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, GenericViewSet): queryset = RecordUsersEntry.objects.none() serializer_class = RecordUsersEntrySerializer def get_queryset(self): # every field returned because they are supposed to … -
Unable to see messages using django register
I have an app with views.py as follows from django.shortcuts import render,redirect from django.contrib.auth.models import User, auth from django.contrib import messages # Create your views here. def register(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] password1 = request.POST['password1'] password2 = request.POST['password2'] email = request.POST['email'] if password1==password2: if User.objects.filter(username=username).exists(): messages.info(request,'username taken') return redirect('register') elif User.objects.filter(email=email).exists(): messages.info(request,'email taken') return redirect('register') else: user= User.objects.create_user(username=username, password=password1, email=email, first_name=first_name,last_name=last_name) user.save(); print('user created') else: print('password missmatch') return redirect('register') return redirect('/') else: return render(request,'register.html') I have added a for loop for showing the messages in register.html {% for message in messages %} <h3> {{message}} </h3> {% endfor %} I can't able to see messages when the for loop is available but i can see message address when for loop is removed. Can some explain and help me how to proceed? -
Django: Help converting Flask app: How/where to refer to main.py?
I've set up all the foundational pages/folders for a Django app, including a bunch of html templates, admin.py, apps.py, models.py, settings.py, urls.py, views.py, etc. They work fine to pull up the menu.html template without errors. But my main py file, which I call index.py, which has most of my functionality: How and where do I refer to it? Thanks! -
How can i submit two forms in django
I have a template where i should have 2 forms and update them, I succeded to get the 2 foms in the same template, but when i make changes nothing happens ! forms.py class OrderManageForm(forms.ModelForm): class Meta: model = Order fields = ['customer', 'product', 'quantity', 'status'] class CustomerForm(forms.ModelForm): address = forms.CharField(widget=forms.Textarea(attrs={'rows': 5})) class Meta: model = Customer fields = ['full_name', 'address', 'phone', 'city', 'email' models.py class Customer(models.Model): full_name = models.CharField(max_length=150) address = models.CharField(max_length=1500, null=True) phone = models.CharField(max_length=20) city = models.CharField(max_length=100) email = models.EmailField(null=True) def __str__(self): return self.full_name class Order (models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE,) quantity = models.IntegerField(default=1) status = models.TextField(choices=ORDER_STATUS, default='Pending') def __str__(self): return 'Order n°: ' + str(self.id) views.py def update_order(request, order_id): order = get_object_or_404(Order, id=order_id) cust = get_object_or_404(Customer, order__id=order_id) if request.method == 'POST': customer = CustomerForm(request.POST) form = OrderManageForm(request.POST) print(request.POST) if form.is_valid() and customer.is_valid(): order = form.save(commit=False) customer = customer.save() order.customer = customer order.save() return redirect('orders') else: form = OrderManageForm(instance=order) customer = CustomerForm(instance=cust) return render(request, 'dashboard/order_details.html', {'form': form, 'customer': customer}) I put the 2 forms in only one form tag inside my HTML template -
Write an Effective query for django for a FOR Loop?
I need to get number of policies bought in each month from these model class Insurance(models.Model): #other fields.. date_purchased_on = models.DateField(auto_now_add=True) customer_region = models.CharField( max_length=10, choices=RegionType.choices) so i have written a views to get a response @api_view(['GET']) def chart_data(request): # structure of the op should be all the months from 1 to 12 # [{"month": 1,"count": 100,}, { "month:2", "count":20}] filtered_data = [] for i in range(1, 13): query = Insurance.objects.filter(date_purchased_on__month=i).count() data = { "month": i, "count": query } filtered_data.append(data) return Response(filtered_data) now the problem is this query hits the database every time its like 12 times. is there a way to handle this to get in a single query or to reduce it and my logger results (0.000) SELECT COUNT(*) AS "__count" FROM "insurance_insurance" WHERE EXTRACT('month' FROM "insurance_insurance"."date_purchased_on") = 1; args=(1,); alias=default (0.000) SELECT COUNT(*) AS "__count" FROM "insurance_insurance" WHERE EXTRACT('month' FROM "insurance_insurance"."date_purchased_on") = 2; args=(2,); alias=default (0.000) SELECT COUNT(*) AS "__count" FROM "insurance_insurance" WHERE EXTRACT('month' FROM "insurance_insurance"."date_purchased_on") = 3; args=(3,); alias=default (0.000) SELECT COUNT(*) AS "__count" FROM "insurance_insurance" WHERE EXTRACT('month' FROM "insurance_insurance"."date_purchased_on") = 4; args=(4,); alias=default (0.000) SELECT COUNT(*) AS "__count" FROM "insurance_insurance" WHERE EXTRACT('month' FROM "insurance_insurance"."date_purchased_on") = 5; args=(5,); alias=default (0.000) SELECT COUNT(*) AS "__count" FROM "insurance_insurance" … -
ProcFile declares types -> (none) ProcFile
I want to host Django server over heroku and my procfile looks like this web: gunicorn DjangoHerokuApp.Portfoliowebapp.wsgi and this my file structure both procfile and requirements.txt are in root folder enter image description here and it is giving me this error continously Procfile declares types -> (none) and this my requirements.txt asgiref==3.4.1 Django==4.0 gunicorn==20.1.0 sqlparse==0.4.2 tzdata==2021.5 Please Help ! I am stuck at this for 2 days -
How to post an image in django server using tiny mce editor? Note: I have integrated the tiny mce editor in a simple html page
I have designed a simple html webpage. Where I've integrated tinymce editor. Someone gave me a uri, Where I need to post an image from tinymce editor to django server by using a uri.In response the server will return a url. That url I need to show in success message. How to do that? -
How does payment work while shopping on a webpage with Django?
I am creating a shopping web app and I'm wondering how does it work? How do I connect my page to the credit card and how does it take money from it? How to implement it in Django? Where to send the money that was taken from the credit card itself? You can probably understand now what I need. Thanks in advance. -
Django-summernote not showing images in editor (404 error)
I'm try create post and add to this post images. And i'm use for this Django-summernote in Django 3.0. Picture upload to folder on hard disk, but not showing in editor. Console show 404 Error. Please, give me advice how to fix it? Thank you! settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' ADMIN_MEDIA_PREFIX = STATIC_URL + "grappelli/" X_FRAME_OPTIONS = 'SAMEORIGIN' SUMMERNOTE_THEME = 'bs4' # Show summernote with Bootstrap4 #MEDIA_ROOT = os.path.join(BASE_DIR, 'blog/media/') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py urlpatterns = [ path('admin/filebrowser/', site.urls), path('summernote/', include('django_summernote.urls')), path('admin/', admin.site.urls), path('', include('blog.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) image = models.ImageField(upload_to="", blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def get_absolute_url(self): return "/api/article/%i/" % self.id def __str__(self): return self.title screenshot from console -
Combining DetailView and CreateView in Django 3.2/4.0, as explained in the docs
I'm building a generic blog and trying to enable users to make comments directly on the article page. I am trying to implement this by combining DetailView with CreateView. The docs present 3 different solutions to this issue: FormMixin + DetailView: this is the answer that Django docs advise against, but that is advised by most answers on SO that I could find DetailView only + write the post method: "a better solution" according to Django docs DetailView + FormView: "an alternative better solution", and the one I'm trying to implement. The "alternative better" solution consists in making a DetailView for articles and a FormView for comments, but the docs state that "This approach can also be used with any other generic class-based views", which means that DetailView + CreateView should be possible. I've gone through a number of SO items that reference this solution, but I am unable to implement any of them. This SO question suggests mixing DetailView and CreateView. However, the explanation in that answer is incomplete. Another SO question, among advice to use FormMixins, has this answer that is close, but different. Other questions (1, 2, etc.) only address the FormMixin and DetailView + post methods. …