Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to sort queryset by another table's record count in Django
I have a Product table and order table the Product table record product info,and the Order table record customer's purchases records Now I want to get the products queryset and sort by the store with the most purchases in a customer's order history Product Model id product_name store_id store_name price ..... 1 iPhone 14 1 Amazon 100 ..... 2 iPhone 14 2 Shopee 1 ..... 3 iPhone 12 3 Taobao 100 ..... 4 iPhone 13 1 Amazon 80 ..... 5 iPhone 14 3 Taobao 100 ..... Order Model id product_id customer_id customer_name 1 1 1 Mike 2 2 1 Mike 3 4 1 Mike 4 1 2 Jhon 5 3 3 Simon in my case,I want to get the product's queryset and sort by the store with the most purchases in a customer's order history For example: when customer_id is 1(Mike),the product queryset should be like below because Mike have spent the most times on Amazon, so the ordering of products should put Amazon's products first id product_name store_id store_name price ..... 1 iPhone 14 1 Amazon 100 ..... 4 iPhone 13 1 Amazon 80 ..... 2 iPhone 14 2 Shopee 1 ..... 3 iPhone 12 3 Taobao 100 ..... … -
How to get logged in user ID and pass to backend or set via backend. Djano, DRF, Vue.js, Djoser
So when a user submits a form via frontend (Vue.js), I want to be able to set the created_by attribute in the backend. What is the best way of achieving this? Views class ProjectView(generics.RetrieveAPIView): queryset = Project.objects.order_by('-created_at') def get(self, request): queryset = self.get_queryset() serializer = ProjectsSerializer(queryset, many=True) return Response(serializer.data) def post(self, request): if request.method == 'POST': serializer = ProjectsSerializer if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) Serializer class ProjectsSerializer(serializers.ModelSerializer): interest_category = serializers.StringRelatedField() class Meta: model = Project fields = ( 'project_title', 'project_description', 'interest_category', 'created_by', 'created_at', 'updated_at', ) The data I am passing from Frontend project_title: this.project_title, project_description: this.project_description, interest_category: this.interest_category, I do have a token saved in localStorage, but I do not know how to get the ID of the currently logged in user id and pass to backend or set in backend. Any and all help is greatly appreciated! What is the best way of setting created_by the submitting/requesting user in the backend? -
Building a custom canonical url in python
I want to build a canonical url for my website: my.com here are the requirements: always include www subdomain always use https protocol remove default 80 and 443 ports remove trailing slash Example: http://my.com => https://www.my.com http://my.com/ => https://www.my.com https://my.com:80/ => https://www.my.com https://sub.my.com/ => https://sub.my.com https://sub.my.com?term=t1 => https://sub.my.com?term=t1 This is what I have tried: from urllib.parse import urlparse, urljoin def build_canonical_url(request): absolute = request.build_absolute_uri(request.path) parsed = urlparse(absolute) parsed.scheme == 'https' if parsed.hostname.startswith('my.com'): parsed.hostname == 'www.my.com' if parsed.port == 80 or parsed.port == 443: parsed.port == None # how to join this url components? # canonical = join parsed.scheme, parsed.hostname, parsed.port and parsed.query But I don't know how to join these url components? -
How to set user that submits on frontend to DRF API
So when a user submits a form via frontend (Vue.js), I want to be able to set the created_by attribute in the backend. What is the best way of achieving this? Views class ProjectView(generics.RetrieveAPIView): queryset = Project.objects.order_by('-created_at') def get(self, request): queryset = self.get_queryset() serializer = ProjectsSerializer(queryset, many=True) return Response(serializer.data) def post(self, request): if request.method == 'POST': serializer = ProjectsSerializer if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) Serializer class ProjectsSerializer(serializers.ModelSerializer): interest_category = serializers.StringRelatedField() class Meta: model = Project fields = ( 'project_title', 'project_description', 'interest_category', 'created_by', 'created_at', 'updated_at', ) The data I am passing from Frontend project_title: this.project_title, project_description: this.project_description, interest_category: this.interest_category, What is the best way of setting created_by the submitting/requesting user in the backend? -
Password reset confirm page not loading
I am building the reset password page, the first page where the users enter his email work fine, he receive the reset password email with success. The problem it with the page where the user actually write his new password. When I click on the link / go to the page it give me this error: assert uidb64 is not None and token is not None # checked by URLconf I am following this docs here: https://docs.djangoproject.com/en/1.8/_modules/django/contrib/auth/views/ here is my views.py @sensitive_post_parameters() @never_cache def password_reset_confirm(request, uidb64=None, token=None, template_name='users/password_reset_confirm.html', token_generator=default_token_generator, set_password_form=SetPasswordForm, post_reset_redirect=None, current_app=None, extra_context=None): """ View that checks the hash in a password reset link and presents a form for entering a new password. """ UserModel = get_user_model() assert uidb64 is not None and token is not None # checked by URLconf if post_reset_redirect is None: post_reset_redirect = reverse('password_reset_complete') else: post_reset_redirect = resolve_url(post_reset_redirect) try: # urlsafe_base64_decode() decodes to bytestring on Python 3 uid = force_text(urlsafe_base64_decode(uidb64)) user = UserModel._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None if user is not None and token_generator.check_token(user, token): validlink = True title = ('Enter new password') if request.method == 'POST': form = set_password_form(user, request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(post_reset_redirect) else: form = set_password_form(user) else: validlink … -
Select2 on explicit through model in Django admin
Using autocomplete_fields/search_fields in Django's admin works well to cause a Select2 widget to be used for a ForeignKey field, but I'm getting an error when I set things up to have Select2 widgets rendered on a declared through model in a ManyToManyField relationship. My models are different than the following, but using the example from the Django docs where through models in the admin are discussed as a starting point, I have things set up something like this (the example in the docs has an implicit through model, but I have an explicitly declared through model): class Person(models.Model): first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership', related_name='groups') class Membership(models.Model): person = models.ForeignKey('Person', ...) group = models.ForeignKey('Group', ...) and in admin.py: class PersonAdmin(admin.ModelAdmin): inlines = [MembershipInline,] search_fields = ('first_name','last_name,) class MembershipInline(admin.TabularInline): model = Membership autocomplete_fields = ('person',) class GroupAdmin(admin.ModelAdmin): inlines = [MembershipInline,] When I go to the GroupAdmin and try to create a membership, the Select2 widget is rendered, but when I try to look up a person, I get this error: Forbidden (Permission denied): /admin/autocomplete/ Traceback (most recent call last): File "/virtualenvs/my_virtualenv/lib/python3.8/site-packages/django/utils/datastructures.py", line 84, in __getitem__ list_ = super().__getitem__(key) KeyError: 'app_label' During handling … -
Django set/list/array + indexed?
I want to add a SET type column to my Django model. Seems like I can add it with SetTextField(). When I run my Django migrations, I get a longtext column instead of the MySQL set type. db_index=True is ignored. If I try to add an index through the Meta class then it complains with MySQL 1107. Basically, I need something where I can quickly look up if a set contains a string. I.e. check if abc,def contains def, obviously accounting for the commas. Also need to be able to add/remove, although I might get away with just setting a new list. The docs say SetTextField is deprecated and to use JsonField, which I can do and store as [ 'abc', 'def' ], but would I be able to have an index on whether or not "def" is in the list? -
Why isn't my return statement working in react?
I have a piece of code that looks like this: export async function getMyProfile() { try { const response = await Axios.get("http://127.0.0.1:8000/lover/lovers/?jwt=" + token) console.log(myUserId); response.data.forEach(response => { console.log(response.id); if (response.id == myUserId) { console.log("Got response"); return "i hate my life"; } //end if }); } catch (e) { concatBackendSignupErrors(e); return false; } return "fucking die"; } And my console has a record of "Got response" as it should on like 8, but then it prints "fucking die" instead of "i hate my life". AND if I take the return statement that says "fucking die" off, it returns undefined. Why isn't this returning "i hate my life" and how can I fix it? -
Understanding docker compose port wiring for django, react app and haproxy
I came across a docker-compose.yml which has following port configuration: wsgi: ports: - 9090 // ?? Is it by default mapped to host port 80 ?? nodejs image: nodejs:myapp ports: - 9999:9999 environment: BACKEND_API_URL: http://aa.bb.cc.dd:9854/api/ haproxy ports: - 9854:80 I am trying to understand how the port wiring is happening here. nodejs UI app settings needs to specify backend port which is 9854 here. This port is exposed by haproxy setting and is mapped to port 80. I know that wsgi is a django backend app. From its entrypoint.sh (in PS below) and port specification in above docker-compose.yml, I get that django listens to port 9090. But I am unable to get how this port 9090 maps to port 80 (which is then exposed by haproxy at 9854, which in turn is specified in BACKEND_API_URL by nodejs settings). PS: Django wsgi app has following in \wsgi\entrypoint.sh: nohup gunicorn myapp.wsgi --bind "0.0.0.0:9090" And nodejs react app has following in its server.js file: const port = process.env.PORT || 9999; -
MultiValueDictKeyError when trying to send an image from react-native to django
I am building my first react-native app with a Django backend. In order for my app to work properly, I need to upload an image from react-native to Django and then save it to a model. But when I try to send the image, I get "raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'profileImage'." here's my code: frontend const [ sentI, setSentI ] = useState(null) const sendI = (image) => { const formData = new FormData() image_data = { uri : image.uri, name : "profileImage", type : 'image/jpg' } if (image != null){ formData.append( 'profileImage', image_data,) setSentI(formData) console.log('recieved') } console.log(formData) } const showImagePicker = async () => { // Ask the user for the permission to access the media library const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync(); if (permissionResult.granted === false) { alert("You've refused to allow this appp to access your photos!"); return; } let result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.All, allowsEditing: true, aspect: [4, 3], quality: 1, }); // Explore the result console.log(result); if (!result.cancelled) { await setProfileImage(result); console.log(result.uri); sendI(result); } } const image = () => { fetch(`http://192.168.5.234:8000/home/imagetest/`, { method: 'POST', body: { sentI }, }) .then( res => res.json()) .then( res => { console.log(res) }) .catch( error => console.log(error)) } return ( <View … -
Django website deploy error: Failed building wheel for Pillow, Reportlab in cPanel
I am trying to use xhtml to pdf libray my code is on goddady cpanel. i have tried pip install reportlab pip install xhtml2pdf pip install --pre xhtml2pdf and no one works non of these commands works on the cpanel i am very sad for the errors they are not disappering i tried soo many things only pip install pillow==8.0.0 works copying src/reportlab/fonts/zy______.pfb -> build/lib.linux-x86_64-3.7/reportlab/fonts running build_ext creating build/temp.linux-x86_64-3.7 creating build/temp.linux-x86_64-3.7/src creating build/temp.linux-x86_64-3.7/src/rl_addons creating build/temp.linux-x86_64-3.7/src/rl_addons/rl_accel /usr/bin/gcc -pthread -Wno-unused-result -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/home/udowyxdf/virtualenv/downloader/3.7/include -I/opt/alt/python37/include/python3.7m -c src/rl_addons/rl_accel/_rl_accel.c -o build/temp.linux-x86_64-3.7/src/rl_addons/rl_accel/_rl_accel.o error: command '/usr/bin/gcc' failed: Permission denied [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for reportlab Running setup.py clean for reportlab Failed to build Pillow reportlab Installing collected packages: Pillow, oscrypto, lxml, importlib-metadata, html5lib, future, tzlocal, reportlab, cssselect2, click, arabic-reshaper, svglib, pyhanko-certvalidator, pyHanko, xhtml2pdf Attempting uninstall: Pillow Found existing installation: Pillow 8.0.0 Uninstalling Pillow-8.0.0: Successfully uninstalled Pillow-8.0.0 Running setup.py install for Pillow ... error error: subprocess-exited-with-error × Running setup.py install for Pillow did not run successfully. │ exit code: 1 ╰─> [130 lines of output] … -
Suggestions on using SQLAlchemy with a large vendor oracle database?
We are upgrading a custom application from PHP to Python / Django / SQLAlchemy. The vendor database it is built on is huge... several thousand tables with 100's of columns, multiple keys, and many layers of dependencies. The PHP application uses OCI and SQL to interact with the database. Database queries can involve as many as 10 tables with complex join conditions, and there are 100s of queries in the application. Trying to create models for all these tables doesn't seem practical. Is it possible to use SQLAlchemy without creating models for all these tables?--just execute the sql directly? -
why pagination is not showing ? django
def allProductCat(request, c_slug=None): c_page = None products_list = None if c_slug is not None: c_page = get_object_or_404(Category, slug=c_slug) products_list = Product.objects.all().filter(category=c_page, available=True) else: products_list = Product.objects.all().filter(available=True) paginator = Paginator(products_list, 6) try: page = int(request.GET.get('page', '1')) except: page = 1 try: products = paginator.page(page) except(EmptyPage, InvalidPage): products = paginator.page(paginator.num_pages) return render(request, "category.html", {'category': c_page, 'product': products}) // Code for Html // <div class="mx-auto"> {% if product.paginator.num_page %} <hr> <div class="text-center"> {% for pg in product.paginator.page_range %} <a href="?page={{pg}}" class="btn btn-light btn-sm {% if product.number == pg %} active {% endif %}">{{pg}}</a> {% endfor %} </div> {% endif %} </div> when i add all these codes pagination doesnt shows up anything when i type the links to next page manually its working perfectly i dont understand whats wrong in this code, also these div doesnt shows anything inside it when i type anything... -
Django-parler fetching translations from the wrong database
I'm a big fan of Django-parler, but I've run into a problem when storing a translated model in two different databases. My model is: class InstrumentFamily(TranslatableModel): primary_key = True translations = TranslatedFields( label=CharNullField(_('Label'), max_length=100, unique=False, null=True,) I have 2 database aliases 'default' and 'test' and my database router directs my model to 'test'. I insert models in both databases by doing this: fam = InstrumentFamily(code=TEST_CODE) with switch_language(fam, 'en'): fam.label = "test_family_test EN" with switch_language(fam, 'fr'): fam.label = "test_family_test FR" fam.save() which stores the object and its translations in database 'test', or by doing this: fam = InstrumentFamily(code="TEST_FAM") with switch_language(fam, 'en'): fam.label = "test_family_default_EN" with switch_language(fam, 'fr'): fam.label = "test_family_default_FR" fam.save(using='default') which saves the object and its translations to database 'default'. So far, so good. But when accessing the object previously saved in 'default' by doing this (after properly clearing all caches to force a database read): fam = InstrumentFamily.objects.using('default').get(code=TEST_CODE) print(f" label: {fam.label}") django-parler properly retrieves the object from database 'default', but looks for the translation from database 'test' ! (SQL trace below, see the very end of each line): SELECT "orchestra_instrumentfamily"."id", "orchestra_instrumentfamily"."code" FROM "orchestra_instrumentfamily" WHERE "orchestra_instrumentfamily"."code" = 'TEST_FAM' LIMIT 21; args=('TEST_FAM',); alias=default SELECT "orchestra_instrumentfamily_translation"."id", "orchestra_instrumentfamily_translation"."language_code", "orchestra_instrumentfamily_translation"."label", "orchestra_instrumentfamily_translation"."master_id" FROM "orchestra_instrumentfamily_translation" WHERE … -
Exclude used items in a one to many relationship
I'm trying to realize this relationship: -A user can have multiple social networks, but each social ONLY ONCE -A social network can have multiple users. I need to avoid a user choose more than one time the same social. Is somethig that has to be done in the model, or later filtering a user choice class Social(models.Model): name = models.CharField(max_length=200) link = models.CharField(max_length=200) def __str__(self): return self.name class Social2User(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) social = models.ForeignKey(Social, null=True, on_delete=models.CASCADE) class Meta: constraints = [ models.UniqueConstraint( fields=['user', 'social'], name='unique_migration_host_combination' ) ] def __str__(self): return self.user.username + '-' + self.social.name class UserInfos(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) bio = models.TextField(null=False) def __str__(self): return self.user.username Thank you -
Django Page Not Found (404) but the current path matched the last one
So.. this is the error: No Category matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/category/food/ Raised by: blog.views.CategoryArticlesListView This is my view: class CategoryArticlesListView(ListView): model = Article paginate_by = 12 context_object_name = 'articles' template_name = 'category/category_articles.html' def get_queryset(self): category = get_object_or_404(Category, slug=self.kwargs.get('sklug')) return Article.objects.filter(category=category, status=Article.PUBLISHED, deleted=False) def get_context_data(self, **kwargs): context = super(CategoryArticlesListView, self).get_context_data(**kwargs) category = get_object_or_404(Category, slug=self.kwargs.get('slug')) context['category'] = category return context And this is the routing: path('category/<str:slug>/', CategoryArticlesListView.as_view(), name='category_articles') I can't find where I've wronged the code. And the contradictory "Page Not Found" and "the current path matched the last one" is very confusing. -
Using variables across django templates
I have a link in a layout template that another template extends. i want the link to pass in a variable thats in the template that extends the other. I want to pass the name variable in the documentPage template through the editDoc link in the layout template. can anyone think of a way to do this? thanks -
Use Escaped url in Django url regex mismatch
I'm trying to use an escaped url as a re_path variable for an object identifier in my API. The logic to connect the escaped url to an object is there, but I can't figure out why the regex is not matching. In my head, a GET request with the following url /objects/http%3A%2F%2F0.0.0.0%3A3030%2Fu%2F%3Fid%3Dc789793d-9538-4a27-9dd0-7bb487253da1/foo should be parsed into obj = 'http%3A%2F%2F0.0.0.0%3A3030%2Fu%2F%3Fid%3Dc789793d-9538-4a27-9dd0-7bb487253da1' and field = 'foo' for further processing. Ultimately, returning the object and 200. However I am getting a 404 with a very specific Django error that only proliferates when Django unfruitfully iterates through all the paths available. <HttpResponseNotFound status_code=404, "text/html"> (Pdb) response.content b'\n<!doctype html>\n<html lang="en">\n<head>\n <title>Not Found</title>\n</head>\n<body>\n <h1>Not Found</h1><p>The requested resource was not found on this server.</p>\n</body>\n</html>\n' I know the path exists as when I examine the urlpatterns, the path is present: (Pdb) pp object_router.get_urls() [ ... <URLPattern '^(?P<obj>https?[-a-zA-Z0-9%._\+~#=]+)/(?P<field>foo|bar)\/?$' [name='test-detail-foobar']> ] The url is escaped with urllib.parse.quote(obj.url, safe="") Regexs tried: r"https?[-a-zA-Z0-9%._+~#=]+" r"https?[%23A](www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}(\.[a-z]{2,6})?\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)(?=\/foo)" https://regexr.com/6ue7b r"(https?://(www.)?)?[-a-zA-Z0-9@:%.+~#=]{2,256}(.[a-z]{2,6})?\b([-a-zA-Z0-9@:%+.~#?&//=]*) -
Expand folium map size on mobile devices
I make a web app using Django, Folium. I have a navbar and a Folium map on the web page. It works fine om computers and landscape screen devices, but on portrait screen devices the map has a free space. My code for map: .... current_map = folium.Map(location=start_location, zoom_start=6) m = current_map._repr_html_() .... context = {"current_map": m} return render(request, template_name="index.html", context=context) How do I fill it? -
Issue with Blueimp Jquery FileUpload For Individual Uploads
I am having issues with individual upload cancels for blueimp jquery fileupload library, have gone through the library and the functionality isn't well documented. I don't know if anyone also has an experience with blueimp fileupload, please help me out: The code for the Upload is: 'use strict'; $(function (){ function previewDataDetail(img,imgSize,imgName){ return ` <div class="col-sm-12" id="progress_img"> <img src="${img}"> <span>${imgSize}</span> <div class="value_hold" style="display:none"> <p id="preview_name">${imgName}</p> </div> <button class="btn btn-dark">Cancel</button> <div class="progress"> <div class="progress-bar progress-bar-striped progress-bar-animated" id="progress_bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style= "width:100%"></div> </div> </div> ` } function abortUpload(e){ e.preventDefault(); var template = $(e.currentTarget).closest( '#progress_img' ), data = template.data('data') || {}; data.context = data.context || template; if (data.abort) { data.abort(); } else { data.errorThrown = 'abort'; this._trigger('fail', e, data); } } $("#uploadTrigger").click(function(){ // const url = "{% url 'property_pic' %}"; // const csrf_token = $('input[name="csrfmiddlewaretoken"]').val(); // $("#fileupload").attr('data-url', url); // $("#fileupload").attr('data-form-data', csrf_token); $("#fileupload").click() }); $("#fileupload").fileupload({ dataType: 'json', sequentialUploads: true, add: function(e,data){ var previewImg = data.files[0]; var previewUrl = URL.createObjectURL(previewImg); $("#formInput").append(previewDataDetail(previewUrl,previewImg.size,previewImg.name)) data.context = $("#progress_img #progress_bar") data.submit(); var jqXHR = data.submit().error(function (jqXHR, textStatus, errorThrown){ if (errorThrown === 'abort'){ alert('This upload has been cancelled') } }) $("#progress_img button").click((e) => { e.preventDefault(); jqXHR.abort() const snip = e.currentTarget.closest("#progress_img preview_name") console.log(snip); // data.originalFiles.forEach(i => { // if(i.name == … -
having trouble getting user authentication to work in Python
I am building a django/react app and having trouble with the backend user authentication, have not been able to debug the issue. After successfully creating an account I am now trying to login. This is the the login route I have built. @csrf_exempt @api_view(['POST']) def loginUser(request): data = request.data if request.method == 'POST': email = data['email'] password = data['password'] try: user = User.objects.get(email=email) except: message = {'detail': 'email does not match a user'} return Response(message, status=status.HTTP_400_BAD_REQUEST) username = user.username user = authenticate(request, username=username, password=password) # Returning correct username and password print('This is the username:', username) print('This is the password:', password) # returning None, even though username and password are matching the info used for signup. (confirmed on admin page) print('This is the user:', user) if user is not None: login(request, user) serializer = UserSerializer(user, many=False) message = {'detail': 'user has been logged in'} return Response(serializer.data) else: message = {'detail': 'Username or password is incorrect'} return Response(message, status=status.HTTP_400_BAD_REQUEST) Any help would be greatly appreciate it since I have been stuck on this for 2 days. -
Django many-to-one relation with 3 tables
I dont want any foreign keys directly in my users table, and by default, when I add a foreing key field in my custom User model, Django generate 2 tabels like this: When I add a many-to-many field in my Company model I get the 3 desired tables but it's made possible for the same user be in two different companys. class Company(models.Model): class Meta: verbose_name = 'Company' verbose_name_plural = 'Companys' ordering = ['name'] db_table = 'companys' id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, unique=True, verbose_name='ID Empresa') name = models.CharField(max_length=100, verbose_name='Nome') users = models.ManyToManyField(User, related_name='company', verbose_name='Users') def __str__(self): return self.name I want Django to generate an additional table with only the Foreing Keys of the two models but keep the behevior of a many-to-one relationship between the two. like this: -
Django: cannot import CSS file from static
Django returns 404 error code while trying to import style.css file Hi, I have problem with loading static files. Error occurred in my main HTML file (frame.html - base for other files). I made everything for correct work of static files, here's all of the applications (code, images) to my problem: File system: ├── jdn ├── __init__.py ├── asgi.py ├── settings.py ├── urls.py └── wsgi.py ├── main ├── __init__.py ├── admin.py ├── apps.py ├── forms.py ├── models.py ├── pdf.py ├── templates └── main ├── create.html ├── frame.html ├── main.html ├── minauth.html ├── report.html ├── searchinit.html ├── searchres.html ├── univerauth.html └── viewuser.html ├── tests.py ├── urls.py └── views.py ├── manage.py ├── media └── main ... └── static ├── admin ├── css ... └── main └── css └── style.css urls.py(core): from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('main.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urls.py(app): from django.urls import path from . import views urlpatterns = [ path('', views.main, name='main'), path('token/', views.get_token, name='get_token'), path('create/', views.create_user, name='create_user'), path('search/', views.search_user, name='search_user'), path('token_report/', views.get_min_tok, name='get_min_tok'), path('report/', views.view_report, name='view_report'), path('view/<int:id>', views.view_user, name='view_user') ] settings.py: import os from pathlib import Path … -
MongoDB error in Django Admin interface: "Select a valid choice. That choice is not one of the available choices."
I am using Django with MongoDB with Djongo as the driver. I have the following two models: from djongo import models from djongo.models.fields import ObjectIdField, Field # Create your models here. class Propietario(models.Model): _id = ObjectIdField() Nombre = models.CharField(max_length=50) def __str__(self): return f"{self.Nombre}" class Vehiculo(models.Model): _id = ObjectIdField() Propietario_Vehiculo = models.ForeignKey(Propietario, db_column='Propietario_Vehiculo', on_delete=models.CASCADE) Modelo = models.CharField(max_length=25) Capacidad = models.IntegerField() Cilindraje = models.IntegerField() Placa = models.CharField(max_length=6) SOAT_Fecha = models.DateField() Operacion_Fecha = models.DateField() def __str__(self): return f"{self.Modelo} de {self.Propietario_Vehiculo}" Using the Django shell I am able to create and save Propietario objects and to link Vehiculo objects to their respecting owners using ForeignKey. However, any time I use the Django admin interface and input a Propietario to a new Vehicle, or try to save and existing one created with the Django shell, I get the error Select a valid choice. That choice is not one of the available choices. Any help would be greatly appreciated -
"Import "django.http" could not be resolved from source"
Just started learning Django by following the official documentation and came across this error. Naturally, I googled it to try and find a fix, but nothing helped. Everybody is saying to choose the right interpreter, but for me the right interpreter was chosen from the start, the one in the virtual environment folder (idk if that's how you say it, like I said I'm new so the terminology is still confusing) and it is still not working.