Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
creating superuser returns "no such table: accounts_user"
I am creating a rest API using Django-rest-auth, and I have a custom user model in an app named accounts. the problem is after making migrations when I try creating a superuser in the console after I input the email in the email field, I get a bunch of errors telling me "no such table: accounts_user" my settings.py INSTALLED_APPS = [ ... 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.facebook', 'accounts', ] # to use old_password when setting a new password OLD_PASSWORD_FIELD_ENABLED = True LOGOUT_ON_PASSWORD_CHANGE = False ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USER_EMAIL_FIELD = 'email' ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_LOGOUT_ON_GET = True # UNSURE ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1 ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 86400 # 1 day in seconds ACCOUNT_LOGOUT_REDIRECT_URL ='api/accounts/rest-auth/login/' LOGIN_REDIRECT_URL = 'api/accounts/rest-auth/user/' SOCIALACCOUNT_EMAIL_VERIFICATION = 'none' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'opeyemiodedeyi@gmail.com' EMAIL_HOST_PASSWORD = '9j@4lifE' DEFAULT_FROM_EMAIL = 'opeyemiodedeyi@gmail.com' DEFAULT_TO_EMAIL = EMAIL_HOST_USER EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '/' REST_AUTH_SERIALIZERS = { "USER_DETAILS_SERIALIZER": "accounts.api.serializers.CustomUserDetailsSerializer", } REST_AUTH_REGISTER_SERIALIZERS = { "REGISTER_SERIALIZER": "accounts.api.serializers.CustomRegisterSerializer", } models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models from django.utils import timezone class UserManager(BaseUserManager): def _create_user(self, email, fullname, password, is_staff, is_superuser, **extra_fields): if not … -
How to properly filter or exclude based on a parameter in Django?
I can do this in Django: query = {field_name: value} if include: return queryset.filter(**query) else: return queryset.exclude(**query) That's bad because there's a fair bit of duplication, and it's rather verbose. I can also do this, which is much simpler: return queryset._filter_or_exclude(not include, field_name=value) But that's also bad, because I'm calling a protected method. Is there a way to combine the best of both? return queryset.filter(exclude=not include, field_name=value) is not a thing. -
How do I get a specific value from an object through foreign key connection in django?
guys! I got the following table and want to get all scad files from objects of Model3D where part of is not null and has the same id as Model3D. Model3D is an 3D printer object that may consists of more than just one part and has therefore the "part of" attribute that holds the id of the original model. class Model3D(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=300) description = models.CharField(max_length=500) original_Model = models.ForeignKey('Model3D', on_delete=models.CASCADE, null=True) creation_Date = models.DateTimeField(auto_now=True) stl_File = models.FileField(null=True, upload_to='models/stlFiles') scad_File = models.FileField(null=True, upload_to='models/scadFiles') parameter_id = models.ForeignKey('Parameter', on_delete=models.CASCADE, null=True) part_of = models.ForeignKey('Model3D', related_name="part_of_model3d", on_delete=models.CASCADE, null=True) I tried the following: part_models_scad_files = Model3D.objects.filter(part_of__isnull=False).select_related(id=self.id) but how do i get the scad files and not only the objects? Thanks for your help, I really want to learn more! -
Django NoReverseMatch when i try add href to the navbar
Hey i learning django from Youtube channel https://www.youtube.com/watch?v=6PX_eVxg5jM But i have a problem. When I add another link in the navigation in base.html I get this error. NoReverseMatch at / Reverse for 'post-new' with no arguments not found. 1 pattern(s) tried: ['post/new/(?P<pk>[0-9]+)/$'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.7 Exception Type: NoReverseMatch Exception Value: Reverse for 'post-new' with no arguments not found. 1 pattern(s) tried: ['post/new/(?P<pk>[0-9]+)/$'] Exception Location: C:\Users\kacpe\dev\blog\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 673 Python Executable: C:\Users\kacpe\dev\blog\Scripts\python.exe Python Version: 3.7.5 Python Path: ['C:\\Users\\kacpe\\dev\\blog\\blog', 'C:\\Users\\kacpe\\dev\\blog\\Scripts\\python37.zip', 'C:\\Users\\kacpe\\dev\\blog\\DLLs', 'C:\\Users\\kacpe\\dev\\blog\\lib', 'C:\\Users\\kacpe\\dev\\blog\\Scripts', 'c:\\python37\\Lib', 'c:\\python37\\DLLs', 'C:\\Users\\kacpe\\dev\\blog', 'C:\\Users\\kacpe\\dev\\blog\\lib\\site-packages'] Server time: Pon, 18 Lis 2019 00:37:52 +0100 This is what the rest of my files look like. base.html <!DOCTYPE html> {% load static %} <html lang="pl"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'myblog/main.css' %}"> {% if title %} <title>Django Blog - {{ title }}</title> {% else %} <title>Django Blog</title> {% endif %} </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div class="container"> <a class="navbar-brand mr-4" href="{% url 'myblog-home' %}">Django Blog</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse … -
Problem with upload image from android(retrofit) to django
I would like to send a photo from android app to django. I use django rest framework as backend. When i post through postman everything works and I get 201. But when i try through android, I get 400. Where is the problem? Thanks for help in advance My model: class Photo(models.Model): file = models.FileField(blank=False, null=False) My django view: def post(self, request, *args, **kwargs): parser_classes = (FileUploadParser,) file_serializer = PhotoSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) Retrofit request: @Headers("content-type: multipart/form-data;") @POST("upload") fun checkItem(@Body image: MultipartBody.Part): Observable<CheckDto> That's how i send my photo from android app: val requestFile: RequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file) val body: MultipartBody.Part = MultipartBody.Part.createFormData("file", file.toString(), requestFile) val requestInterface = ApiClient.getClient().create(ApiInterface::class.java) myCompositeDisposable?.add(requestInterface.checkItem(body) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe({ result -> Log.d("Request", result.toString()) }, { error -> error.printStackTrace() }) ) -
VS Code: Python Interpreter can't find my venv
I've been stuck on this for a few days, kindly help me if you can. I have my venv folder on my root project folder. When I try to set the Python Interpreter, it shows me only the Python installed in my machine and not the one in my root folder. It was working fine until I formatted my PC and installed windows 10 64 bits. (was running on windows 7 64 bits prior) Things I have tried: Set the path manually via pythonPath and/or venvPath, in both workspace and user settings: "python.pythonPath": "F:/Web Dev/Python/Django/project_x_v2/backend/venv/Scripts/python.exe", "python.venvPath": "F:/Web Dev/Python/Django/project_x_v2/backend/venv/Scripts/python.exe", It shows me the correct location in the placeholder but I don't have the option to choose it from the dropdown list: Any ideas how I can solve this? Thank you very much. -
Confused with multiple dimension dictionaries
I got this method which returns a multi-dimensional dictionary. def get_apps(): menu_one = { 'name': 'Apps group one', 'menu_one_app_one': { 'name': 'app one!', 'icon': 'fa-rocket', 'url': '/Url' }, 'menu_one_app_two': { 'name': 'app two!', 'icon': 'fa-user', 'url': '/Url2' } }, menu_two = { 'name': 'Apps group two', 'menu_two_app_one': { 'name': 'app three!', 'icon': 'fa-clipboard', 'url': '/Url3' }, 'menu_two_app_two': { 'name': 'app four!', 'icon': 'fa-users', 'url': '/Url4' } } return menu_one, menu_two So in my Django view I'm calling the method get_apps() in order to get the apps with their attributes and show them on different groups like this: def my_django_view(request): apps = get_apps() return render(request, "apps.html", {'apps': apps}) And the idea is to display them by group in my template like this: {% for menu in apps %} <!-- this is ok! --> <div class="breadcrumb"> <h1>{{ menu.name }}</h1> {% for app in menu %} <!-- here is the part where I am wrong --> <a href="{{ app.url }}" data-toggle="tooltip" title="{{ app.name }}"> <i class="fa {{ app.icon }}></i> </a> {% endfor %} </div> {% endfor %} I know what is wrong thanks to django since it's saying 'str' has no attr 'name', of course, since it is a dictionary. But then, how … -
<a> tag is not clickable and not linked
Okay , I am not sure if that is a problem with my Django project logic or with my html tags , so here it goes I am trying to make a link that lists all the groups created by a specific user the template code <h1> <a href"{% url 'infrastructure:user-orgs-view' slug=request.user.slug%}"> Your Organizations </a> </h1> url.py part path('accounts/<slug>/orgs', views.UserOrgsView, name='user-orgs-view' ) my view def UserOrgsView(request, slug): orgs = Profile.objects.get(slug=slug).organization_set return render(request, 'user_orgs.html', { 'orgs' : orgs}) the only css I am using on this page body { text-align: center; vertical-align: middle; } p *{ vertical-align: middle; } what happens is the tag appears as normal text , not clickable .. not linked .. nothing .. any idea why is that happening ? -
How do I auto increment field that is part of unique_together in Django admin
Basketball Game has 4 Quarters. I would like Django to auto increment Quarter.number for each Game in Admin, so I don't have to always correct them manually. Example models.py class Game(models.Model): name = models.CharField() class Quarter(models.Model): number = models.IntegerField(help_text='quarter number from 1 to 4') game = models.ForeignKey(Game) class Meta: unique_together = ['game', 'number'] So number in Quarter can be 1, 2, 3 or 4 (or more for other sports) and should be set to 1 by default. After saving first quarter for one Game it should suggest number=2 for the next entry of the same Game. The incremented numbers should also get shown correctly in admin.TabularInline if I set Quarter as inline of Game in admin.py (in below code Django would by default show 3 entries for a new Game, but all would have default number=1): class QuarterInline(admin.TabularInline): model = Quarter class Game(admin.ModelAdmin): inlines = [QuarterInline] How can I achieve that number gets incremented by default for each game? -
Is there a way for Django to accept naive datetimes with USE_TZ=True, or to suppress warnings?
Our company has been a long-time user of Django -- for more than 10 years. We are currently running Django 1.11.26. We've dealt with a lot of datetime-related issues over the years, but our current issue is proving challenging. Our goal is to do the following: use Django's timezone support (setting USE_TZ=True) with UTC as default time zone for a couple of denormalized fields (daily rollups of energy data) store naive datetimes As is documented in many Stack Overflow questions, Django will issue a warning with datetime field values set to a naive datetime: RuntimeWarning: DateTimeField received a naive datetime...while time zone support is active. We think our use case for storing naive datetime is a reasonable one. While for almost all our datetime fields it make sense to use UTC, for certain kinds of daily rollups we want to store a naive/agnostic datetime indicating the start datetime of the day in the local time zone (multiple time zones for different objects). By using a naive datetime, we are able to use datetime-related filters. Therefore if we are summarizing certain kinds of energy rollups for a given datetime, we can find the rollup for the same local datetime for buildings … -
Use DeleteView to delete an object, got "'mysite' is not a registered namespace"
I followed this example to upload document to AWS (https://github.com/sibtc/simple-s3-setup/tree/master/s3-example-static-and-media). I am now adding a functionality which allows user to delete an uploaded document. I got the error "django.urls.exceptions.NoReverseMatch: 'mysite' is not a registered namespace". Followed is the parameter values in /home/ubuntu/.local/lib/python3.6/site-packages/django/urls/base.py: args [1]; current_app ''; current_ns None; current_path None; kwargs {}; ns 'mysite'; ns_converters {}; ns_pattern ''; parts ['delete', 'mysite']; path []; prefix '/'; resolved_path []; resolver ; urlconf 'mysite.urls'; view 'delete'; viewname 'mysite:delete' Here are the files I made changes: (1) mysite/core/views.py class DocumentCreateView(CreateView): model = Document fields = ['upload', ] success_url = reverse_lazy('home') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) documents = Document.objects.all() context['documents'] = documents return context (below was added by me.I may need to add some code here to make the deletion work) class DocumentDeleteView(DeleteView): model = Document fields = ['upload', ] success_url = reverse_lazy('home') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) documents = Document.objects.all() context['documents'] = documents return context (2) mysite/urls.py app_name = 'mysite' urlpatterns = [ url(r'^$', views.DocumentCreateView.as_view(), name='home'), *(below was added by me)* path('<int:pk>/delete/', views.DocumentDeleteView.as_view(), name='delete'), ] (3) mysite/core/templates/core/document_form.html: I also added the following code to line 27 of https://github.com/sibtc/simple-s3-setup/blob/master/s3-example-static-and-media/mysite/core/templates/core/document_form.html <td><a href="{% url 'mysite:delete' document.id %}">Delete</a></td> (If I change 'mysite:delete' to 'delete', I got … -
Django - How to do a prefetch_related? Am I doing it wrong?
I have these four models/tables: class Category(models.Model): image = models.ImageField(upload_to="images/") position = models.IntegerField() class CategoryTranslation(models.Model): name = models.CharField(max_length=32) language = models.CharField(max_length=2) category = models.ForeignKey(Category, related_name="translated_category", on_delete=models.CASCADE) class Quote(models.Model): num_views = models.IntegerField() category = models.ForeignKey(Category, related_name="quote_category", on_delete=models.CASCADE) class QuoteTranslation(models.Model): quote_text = models.TextField(max_length=512) language = models.CharField(max_length=2) quote = models.ForeignKey(Quote, related_name="translated_quote", on_delete=models.CASCADE) I want to prefetch all of the related data, I came up with this: t_quote = QuoteTranslation.objects.filter( language='en' ).prefetch_related( 'quote__category__translated_category' ).first() With this I can get: >>> t_quote.quote_text >>> t_quote.quote.num_views >>> t_quote.quote.category.image without any additional query, but I get None when I try to get the category name: >>> t_quote.quote.category.translated_category.name and to get what I want (the category name) I still need to do this: >>> t_quote.quote.category.translated_category.get( category=t_quote.quote.category.id, language='en').name Am I doing prefetch_related wrong? I couldn't figure out how to do it with Prefetch either. Please help. -
Django Rest Framework get_field is not being called
I've got an existing Django code base which uses Django Rest Framework to expose the data. I had one field which was defined as a SerializerMethodField() in the Serializer: categories = serializers.SerializerMethodField() And in the same serializer this get_method is defined: def get_categories(self, obj): return [obj.categories.choices[key.upper()] for key in obj.categories] That worked, but I had to add a way to also let users post new data to the api. Since the SerializerMethodField is read-only by definition I changed the field to a CharField (because it's a varchar in the DB): categories = serializers.CharField(required=True, allow_blank=False, max_length=100) That works for posting new content, but unfortunately, the get_categories() is not being called anymore. Does anybody know how I can make it call the get_categories() method while keeping the CharField? -
Django Show Unique List Of Subjects (Many To Many) In Dropdown Menu
I want to be able to produce a dropdown menu in my template with a unique list of subjects. Subjects are populated inside of admin rather than hard coding them in SUBJECT_CHOICES. A course can have many subjects or only 1 subject. For example: Course Title = Django Subject = Technology Course Title = Python Subject = Technology Course Title = Accounting Subject = Business Course Title = E-commerce Subject(s) = Technology, Business CourseListView corresponds to the course_list.html template. Models and views: https://dpaste.de/s8jq Desired Output: https://imgur.com/a/l0FWJoN I tried writing a for loop in my template that does return the subjects successfully but they are not unique or showing only once. https://dpaste.de/NHdF I would prefer to do it with a for loop that produces unique results, but maybe it can be done with django-select2 or use a form with model select or multiple model select? Can someone provide some code for either the loop or one of these methods? I would appreciate any help with this. -
NameError: name doohickey is not defined
This doesn't make sense... The error message: something = doohickey() NameError: name 'doohickey' is not defined get_random_tweet.py import twitter api = twitter.Api(consumer_key='i43eOLgYs6u6CCNQ93TxqqUR4', consumer_secret='18l0emYejR9rTWVd8ri1b0WtqC2qSj74yHqN0iyc$ access_token_key='1126243617482231808-q997kDrZf7gmGLhfKwB$ access_token_secret='oHdW4EaAg7ZS0hloJnvRpaz1CZmnimlJrKYd$ timeline = api.GetUserTimeline(screen_name='realDonaldTrump', include_rts=False, trim_user=True, exclude_replies=True, count=6) def doohickey(): pprint(timeline) return {'index': "<i> something </i>"} My views.py from django.shortcuts import render from django.http import HttpResponse from hello.sampled_stream import okdood import hello.get_random_tweet from .models import Greeting # Create your views here. def index(request): # return HttpResponse('Hello from Python!') # okdood() something = doohickey() return render(request, "index.html") Now I need to fill up space with something.... -
Best stack for uploading and processing several pdf files on a website?
I'm making a website where users can upload several pdf files (normally 10 MB in total, but can it can go up to 80-100 MB) and extract certain parts of those files in an Excel sheet. It involves heavy use of functions on each page, as there are a lot data to retrieve. I've already coded it in python as a script, but I want to make it as a website. Noob question: What stack should I use? Is it better using server-side or client-side? I know pdf.js can retrieve some information, but I'm not sure it would be the most appropriate for this. I was thinking about flask or django as it's already in python. What would be the best option for speed? User would use the browser, not the smartphone for this app. -
Django documenation page
I'm busy making a documentation page in my Django project and would like to make a dynamic page where theres a sidenav with links but if you click on a nav item it loads the page within the "master page aka the documentation page" without leaving that page like so https://www.nbinteract.com/tutorial/tutorial_github_setup.html I have created the side nav etc and it's working fine and linked my first URL to a nav item but if you click on the nav item, it opens that .html file instead of loading it within the main documentation page. I would like to find a way to do it with Django only and not JavaScript if possible, any guidance would be appreciated. Yes, this could be a silly question but please don't flame me about learning how to do stuff :) -
Django Rest Framework - GenericViewSet with Authentication/Permission decorator
Currently i have a simple rest setup for a single entity, you can create an object and you can retrieve it by the id. "POST" requires authentication/permission, "RETRIEVE" requires no authentication/permission. settings.py (requires global authentication/permission from every resource): REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'api.authentication.token_authentication.TokenAuthentication' ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated' ] } In my resource the global authentication/permission settings are applied correctly but i want to generate an exception for the retrieve method: my-resource.py: from django.utils.translation import gettext_lazy as _ from rest_framework import mixins, serializers, viewsets from rest_framework.decorators import authentication_classes, permission_classes from api.models import Entity class EntitySerializer(serializers.ModelSerializer): class Meta: model = Entity fields = [...] read_only_fields = [...] class EntityViewSet( mixins.CreateModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet ): queryset = Entity.objects.all() serializer_class = EntitySerializer @permission_classes([]) # this is ignored ? @authentication_classes([]) # this is ignored too ? def retrieve(self, request, *args, **kwargs): return super().retrieve(request, *args, **kwargs) Result: "POST" works as expected "RETRIEVE" return 403 ??? Why does the retrieve method still require authentication and returns 403? Is there any easier way to accomplish this? Greetings and thanks! -
Django-ckeditor upload permission for all users and scroll bar
1) I am using Django-CKEditor and when I am trying to upload any file or image in it then it is showing Alert error: "Incorrect Server Response", And when I checked in the terminal, there it is showing "GET /admin/login/?next=/ckeditor/upload/ HTTP/1.1" I don't know what to do to make this work! Please help me here... 2) when I am copy-pasting 100 lines of text in the editor it increases its height rather providing any scroll bar in it, here is the config code I am using: CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_CONFIGS = { 'default': { 'height': '200', 'width': 1250, 'toolbar_Basic': [ ['Source', '-', 'Bold', 'Italic'] ], 'toolbar_YourCustomToolbarConfig': [ {'name': 'document', 'items': ['Source']}, {'name': 'clipboard', 'items': ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo']}, '/', {'name': 'basicstyles', 'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']}, {'name': 'paragraph', 'items': ['NumberedList', 'BulletedList', '-', 'Blockquote', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl']}, {'name': 'links', 'items': ['Link', 'Unlink', 'Anchor']}, {'name': 'insert', 'items': ['Image', 'Table', 'SpecialChar']}, '/', {'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize']}, {'name': 'colors', 'items': ['TextColor', 'BGColor']}, {'name': 'tools', 'items': ['Maximize']}, ], 'toolbar': 'YourCustomToolbarConfig', # put selected toolbar config here # 'toolbarGroups': [{ 'name': 'document', 'groups': [ 'mode', 'document', 'doctools' … -
Django form : Setting the user to logged in user
I am trying to create an address book website where logged in user is able to fill in a form and store contact information. I was able to implement the login and logout functionality. But the problem is that I am not able to set the username to current logged in user. Here is what I have implemented so far: Models.py class UserProfileInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) #additional def __str__(self): return self.user.usernname class UserContacts(models.Model): current_user = models.ForeignKey(User,on_delete=models.CASCADE) first_name = models.CharField(max_length = 150) last_name = models.CharField(max_length = 150) phone_number = models.CharField(max_length = 150) email_address = models.CharField(max_length = 150) street_address = models.CharField(max_length = 350) def __str__(self): return '{}'.format(self.first_name) Forms.py class UserForm(forms.ModelForm): password = forms.CharField(widget = forms.PasswordInput()) class Meta(): model = User fields = ('username','email','password') class UserContactForm(forms.ModelForm): class Meta(): model = UserContacts fields = "__all__" views.py: @login_required def new_contact(request): form = UserContactForm() current_user = request.user.get_username() user = User.objects.filter(username=current_user).first() output = UserContacts.objects.filter(current_user_id=user.id).first() if request.method == "POST": form = UserContactForm(request.POST) if form.is_valid(): form.save(commit=True) return index(request) else: print('Error Form Invalid') return render(request,'basic_app/contact.html',{'form':form}) Here is how the output looks like when the logged in user tries to enter contact information details: Updating contact screenshot. As you can see the current user has to select his username to fill … -
df.to_html() method is displaying the actual html on the webpage and not the representation it should (Django website)
I'm currently making a django website for a Software Engineering class. I'm having a problem with displaying a pandas dataframe using the .to_html() method. The webpage template is rendering the actual html code on the UI instead of the representation of the html code. I don't understand why and have looked for similar problems on the internet. I think I can't find a similar problem because I don't know the right words to use in the search engine to get the answer I want. The webapp template (called graphs.html) is displaying the actual code itself. Here is a code fragment: <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>itemId</th> <th>title</th> <th>endPrice</th> <th>location</th> <th>endTime</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>283584749546</td> <td>1979 80 TOPPS #18 WAYNE GRETZKY ROOKIE CARD PSA 6 EX-MINT</td> <td>500.0</td> <td>Canada</td> <td>2019-11-17T08:08:30.000Z</td> </tr> <tr> <th>1</th> <td>163940352354</td> <td>1979 Topps Hockey Unopened Wax Pack Gretzky PSA ?</td> <td>103.5</td> <td>Rice Lake,WI,USA</td> <td>2019-11-16T16:27:42.000Z</td> </tr> <tr> <th>2</th> <td>293329130191</td> <td>1979/80 Topps Wayne Gretzky Rookie #18 High End PSA 6 RC Priced to Sell</td> <td>345.0</td> <td>Liberty Lake,WA,USA</td> <td>2019-11-15T22:04:27.000Z</td> </tr> <tr> As you can see, the UI is displaying html tags when it shouldn't. Below, the html is displaying without the tags showing, and would look like … -
django Arabic Hijri calendar
I use Django 2.2 When I have a field that has DateTimeField type, Django automatically uses Django calendar. But in Saudi Arabia we use Islamic Hijri Calendar. How can I define a field with Hijri calendar? -
Can't Login into Django Admin
What I know about AbstractUser and AbstractBaseUser is that AbstractBaseUser allow you to start from scratch but AbstractUser is to work with existng fields in USER. Similarly I created model using AbstractBaseUser and changed name of some fields like is_admin and is_staff but when I tried to login in Django Admin it doesn't allows. I figure out the problem and change name back to default and it worked. So if I wan't to login in to django admin what should I do. -
Adding a Custom DateTimePicker in a Django form
I'm quite new to Django, so I decided to build a simple app to test my skills. On one of the model forms, I have a DateTimeField, but that only defaults to a TextField. I would like to create a custom datetime picker with bootstrap, but I didn't know how to implement it. I followed a tutorial for Tempus Dominus Bootstrap 4 here. I have everything they say, but when I navigate to my form, it displays an error: 'BootstrapDateTimePickerInput' object has no attribute 'is_hidden'. Models.py from django.db import models class ToDoItem(models.Model): title = models.CharField(max_length=100) description = models.TextField() start_time = models.DateTimeField() end_time = models.DateTimeField() remind_time = models.DateTimeField() Widgets.py from django.forms import DateTimeField class BootstrapDateTimePickerInput(DateTimeField): template_name = 'main/bootstrap_datetimepicker.html' def get_context(self, name, value, attrs): datetimepicker_id = 'datetimepicker_{name}'.format(name=name) if attrs is None: attrs = dict() attrs['data-target'] = '#{id}'.format(id=datetimepicker_id) attrs['class'] = 'form-control datetimepicker-input' context = super().get_context(name, value, attrs) context['widget']['datetimepicker_id'] = datetimepicker_id return context forms.py from django import forms from .widgets import BootstrapDateTimePickerInput from .models import ToDoItem class NewEventForm(forms.ModelForm): start_time = forms.DateTimeField( input_formats=['%d/%m/%Y %H:%M'], widget=BootstrapDateTimePickerInput() ) end_time = forms.DateTimeField( input_formats=['%d/%m/%Y %H:%M'], widget=BootstrapDateTimePickerInput() ) remind_time = forms.DateTimeField( input_formats=['%d/%m/%Y %H:%M'], widget=BootstrapDateTimePickerInput() ) class Meta: model = ToDoItem fields = ['title', 'description', 'start_time', 'end_time', 'remind_time'] views.py from django.shortcuts … -
Query through intermediate models that returns multiple results, using Django Q object
How to follow an intermediate 'through' model, in a Q object? I'm trying to get a list of the ids of all Property objects that a User is a member of, in one query. A User is a member of a BusinessUnit through BusinessUnitMember. How do I make a filter with a Q object that finds all (multiple) BusinessUnitMembers for a particular User, and then finds all (multiple) BusinessUnits for those BusinessUnitMembers? class Property(BaseModel): """Physical Things belonging to various Business Units""" category = models.CharField(max_length=255, choices=CATEGORY_CHOICES) objects = PropertyQuerySet.as_manager() @property def asset(self): asset_maps = { 'typea': 'type_a_asset', 'typeb': 'type_b_asset', } if self.category not in asset_maps: return None return getattr(self, asset_maps.get(self.category), None) class AssetBase(models.Model): """Abstract Base Asset model.""" business_unit = models.ForeignKey('BusinessUnit', null=True, on_delete=models.SET_NULL) class TypeAAsset(AssetBase): """Type A Assets""" property = models.OneToOneField('Property', null=True, on_delete=models.CASCADE, related_name='type_a_asset') class TypeBAsset(AssetBase): """Type B Assets""" property = models.OneToOneField('Property', null=True, on_delete=models.CASCADE, related_name='type_b_asset') class BusinessUnit(models.Model): name = models.CharField(max_length=255) owner = models.ForeignKey('core.User', null=True, on_delete=models.SET_NULL, related_name='owned_business_units') class BusinessUnitMember(models.Model): """ ``through`` model for BU and members. """ business_unit = models.ForeignKey('BusinessUnit', on_delete=models.CASCADE) member = models.ForeignKey('core.User', on_delete=models.CASCADE) I need to find the ids of all Property objects that the current User is a member of. I'm thinking of a filter like: available_ids = Property.objects.filter(Q(type_a_asset__business_unit__in=user.businessunitmember.all().businessunit_set.all())).values_list('id', flat=True) …