Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Implementing reset password for different user app in django
PLease I have two two apps that handle two kinds of users in my project. The two kinds of user have different privileges on the site (I also have groups based on these two user account apps). The problem am having is that the default. from django.contrib.auth import views as auth_views has only one file structure in contrib/admin/templates/registration. I have this in urls.py for the diferent apps: path('reset_password/', auth_views.PasswordResetView.as_view(template_name="users/reset_password.html"), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="users/password_reset_sent.html"), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="users/password_reset_form.html"), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="users/password_reset_done.html"), name="password_reset_complete"), For the second app, I have this in the urls.py path('reset_password/', auth_views.PasswordResetView.as_view(template_name="companyusers/reset_password.html"), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="companyusers/password_reset_sent.html"), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="companyusers/password_reset_form.html"), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="companyusers/password_reset_done.html"), name="password_reset_complete"), but django does not seem to find the template paths unless I put the html files in the general templates folder for the project thus: path('reset_password/', auth_views.PasswordResetView.as_view(template_name="reset_password.html"), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="password_reset_sent.html"), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="password_reset_form.html"), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="password_reset_done.html"), name="password_reset_complete"), So when a user resets to password, the final login page points to just the login page for one user. Meanwhile the two apps in the project has two different login pages. when I try to use url name-spacing for the reset password url paths, django is not able to find them since they are not in the root directly. Please how … -
fix JavaScript LoadMore button to load 5 items per page - Django
fix JavaScript #LoadMore button to load 5 items per page - Django i want show 5 item per once then user click on LoadMore button then it will load more 5 items how to do that with js ? html code : {% for mobile in mobileforhome %} <div class="card-deck"> <div class="card mb-3" style="max-width: 800px;"> <div class="row no-gutters"> <div class="col-md-4"> <a href="Mobile/{{ mobile.slug }}"><img style="height:100%;width:100%;border-radius:6.5px;" src="{{ mobile.get_image }}" class="rounded float-right" alt="..."></a> </div> <div class="col-md-8"> <div class="card-body"> <a href="Mobile/{{ mobile.slug }}"> <h5 class="card-title" id="primary_site_pages_app_name_control"> <b>{{ mobile.name }}</b></h5></a> <p class="card-text" id="font_control_for_all_pages">{{ mobile.app_contect|truncatechars_html:153|safe}}</p> </div> <div class="card-footer"> <small class="text-muted" id="date_post_control">{{ mobile.post_date}}</small> <small class="firstsmall"><a class="bg-orange" href="{% url 'mobile' %}" id="tag_name_control">هواتف</a></small> </div> </div> </div> </div> </div> <hr> {% endfor %} <!-- show more button --> <div class="text-center mt-4"> <a role="presentation" type="button" class="btn btn-secondary btn-lg loadMore" style="width:40%;color:white">Show More</a> </div> <!-- script controll the games ( show 6 game per page ) --> <script src="https://code.jquery.com/jquery-3.1.0.js"></script> <script> const thumbnails = $(".card-deck .card mb-3"); let visibleThumbnails = 0; function showThumbnailsUntil(index) { for (var i = visibleThumbnails; i <= index; i++) { if (i < thumbnails.length) { $(thumbnails[i]).addClass('visible'); visibleThumbnails++; } else { break; } } } showThumbnailsUntil(2); $(".loadMore").on("click",function(){ showThumbnailsUntil(visibleThumbnails + 2) if(visibleThumbnails === thumbnails.length) { $(".loadMore").fadeOut(); //this will hide //button when … -
Like Button Django Ajax
I'm trying to create my like button with Ajax but this stopped me at the beggining. The function wont preventDefault. <script> var a = "{{ post.id }}" $(document).ready(function(){ $("#demo"+a).modal({show:true}); $('.like-form').submit(function(e){ e.preventDefault() console.log('works')}); }); </script> <input type="hidden" name="post_id" value="{{post.id}}"> <button type="submit" class="ui bwhite-sm button like-btn{{post.id}}"> {% if user.profile not in post.liked.all %} LIKE {% else %} UNLIKE {% endif %} </button> <div>{{post.liked.all.count}}</div> </form> -
KeyError in graphql when reusing DRF serializer
So I am trying to implement graphql and reuse my serializer.py file but am getting "name 'request' is not defined". I can see what it's referencing on the serializer but no clue how to fix it. It seems to be hanging on the self.context["request"] I used to pop the password field from my put methods when using drf. any ideas as to how best to get around this. I am still learning and seem to be hitting a wall. Any help would be greatly appreciated. Thank you in advance. serializer.py class UserSerializer(serializers.ModelSerializer): """Serializes the user model""" # name = serializers.CharField(max_length=10) specialties = serializers.PrimaryKeyRelatedField( many=True, queryset=models.Specialty.objects.all() ) class Meta: model = models.User fields = "__all__" extra_kwargs = { "password": {"write_only": True, "style": {"input_type": "password"}} } def __init__(self, *args, **kwargs): super(UserSerializer, self).__init__(*args, **kwargs) if self.context["request"].method == "PUT": self.fields.pop("password") def create(self, validated_data): """Create and return a new user""" user = models.User.objects.create_user( email=validated_data["email"], first_name=validated_data["first_name"], last_name=validated_data["first_name"], password=validated_data["password"], ) return user mutations.py class CreateUser(SerializerMutation): class Meta: serializer_class = UserSerializer error NameError at /graphql/ name 'request' is not defined Request Method: GET Request URL: http://localhost:8000/graphql/ Django Version: 3.0.10 Exception Type: NameError Exception Value: name 'request' is not defined Exception Location: /dsinfinitum/backend/ds_admin/schema.py in Meta, line 106 Python Executable: … -
cant import the file itself in pyinstaller
i am trying to use pyinstaller to pack my single file web application as follow, which can be run normally by tested, hoping to use it in another computer without python import os this = os.path.splitext(os.path.basename(__file__))[0] if __name__ == '__main__': import sys from daphne.cli import CommandLineInterface sys.exit(CommandLineInterface().run(["-p", "30003", this + ":application"])) else: import django from django.conf import settings from django.core.asgi import get_asgi_application from django.urls import re_path from django.http import JsonResponse DEBUG = True urlpatterns = [ re_path(r'^', lambda x: JsonResponse({'msg': 'success'})) ] SETTINGS = dict( DEBUG=DEBUG, ROOT_URLCONF=this ) settings.configure(**SETTINGS) django.setup() application = get_asgi_application() but when i run the packed file, it returns Error daphne/server.py:11: UserWarning: Something has already installed a non-asyncio Twisted reactor. Attempting to uninstall it; you can fix this warning by importing daphne.server early in your codebase or finding the package that imports Twisted and importing it later on. Traceback (most recent call last): File "single.py", line 9, in <module> File "daphne/cli.py", line 252, in run File "daphne/utils.py", line 12, in import_by_path File "importlib/__init__.py", line 127, in import_module File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'single' [596096] Failed to execute … -
How to change Django static files
I know this might be a really obvious question, but I'm doing a Django project where I have Javascript in my static files. However, I have noticed that whenever I make a change to those files, my web server doesn't reflect the changes. Is there some migration or something else I need to do to make my web server reflect changes to my static Javascript files? Thanks. -
How to access djagno built in login system fields
So when I look on tutorials online on how to use the django built in login system I found that they use {{ form.as_p }} in templates, how can I access each field individualy in tmeplates so I can put them in my own styled template ? -
How can i set permission on url
I am new on Django, I have implemented a valid form and now i want to set permission on url. When a form is submit then it redirects me to this url http://127.0.0.1:8000/success/. Without submitting a form i can manually type the name of the url "http://127.0.0.1:8000/success/" and it will take me to the same page. How can i set permission on "success" url, so that user can not manually view the page unless the form is valid and submitted. Do i need a decorator for this? Model: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) profile_pic = models.ImageField(upload_to='ProfilePicture/', default="ProfilePicture/avatar.png", blank=True) phone = models.IntegerField(default='0', blank=True) email = models.EmailField(blank=True) date_of_birth = models.CharField(max_length=50, blank=True) address = models.TextField(blank=True) date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'Profile' verbose_name_plural = 'Profiles' ordering = ['-date'] '''Method to filter database results''' def __str__(self): return self.user.username class CotCode(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) cot_code = models.IntegerField(default='0', blank=True) date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'CotCode' verbose_name_plural = 'CotCode' ordering = ['-date'] def __str__(self): return self.user.username Url: path('cot/', TransferCOTView, name='transfer_cot'), path('success/', SuccessfulView, name='successful_trans'), Views: @login_required def TransferCOTView(request): form = CotCodeForm(request.POST) if request.method == "POST": if form.is_valid(): cot_code = form.cleaned_data.get('cot_code') try: match = CotCode.objects.get(cot_code=cot_code) return redirect('site:successful_trans') except CotCode.DoesNotExist: messages.info(request, "Wrong code") else: form = … -
Django: can I make db queries async?
In my app I have a template that I wish to make it like a control center that would display a ton of information, so I have to make a ton of queries to grab that info. So of course, the page is slow as heck and now I'm thinking how to fix this. I thought about making indexes but I don't have the space for this. I already optimized my queries to the minimun waste possible but it still takes like 1:30 minutes to load the page. I'm looking into assynchronous support on Django, but the version of Django I'm using doesn't seem to support (2.1). Does anybody got any tip that could help me in this? I didn't showed my code because I figured it's not nescessary, for this question is more abstract. It's not about my problem especifics but more about optimization in general. -
Django: make an addition inside of a model.objects.filter.update()
I have this view that has a form and I want to update a field of a model based on the user input. I cannot find a way to do that. The pytonic way =+ does not seem to work in this situation. Here is my view: def orders_on_the_way_edit2(request, Id): OnOrder2 = get_object_or_404(table_on_order, Id=Id) if request.method == 'POST': form = OnOrderUpdateForm(request.POST, instance = OnOrder2) if form.is_valid(): form.save() quantity = form.cleaned_data.get('Quantity_received') id = form.cleaned_data.get('Id') update2 = table_on_order.objects.filter(Id = Id).update(Quantity_received =+ quantity) update = table_on_order.objects.filter(Id = Id).update(StockOnOrder = (StockOnOrder - quantity)) messages.success(request, "Changed in order status successfully recorded") return redirect('OnOrder2') else: form = OnOrderUpdateForm(initial = { 'Id' : OnOrder2.Id, 'StockOnOrder' : OnOrder2.StockOnOrder, 'Quantity_received' : OnOrder2.Quantity_received, 'OrderCompleted' : OnOrder2.OrderCompleted}, instance =OnOrder2) return render(request, 'OnOrder2edit.html', {'form' : form}) the lines: update2 = table_on_order.objects.filter(Id = Id).update(Quantity_received =+ quantity) update = table_on_order.objects.filter(Id = Id).update(StockOnOrder = (StockOnOrder - quantity)) are causing the issue, update1 replaces the existing value by quantity and update2 gives me an error. Any clue on this would be appreciated! -
Django atomic transactions not actually atomic?
I was recently in an interview for a fairly upper-level django job and they stated that atomic transactions aren't truly atomic. In all my years using django ive never heard this. can anyone explain? -
Django: Can't add field to custom user model
So, I've got a well running Django 3 app with a custom user model running on a MySQl db. I've been doing makemigrations and migrate successfully for months. Today I tried to add a field to my custom User Model called Account. The second I add a field to that model, the dev server attempts to process the change and crashes with this error: django.db.utils.OperationalError: (1054, "Unknown column 'account_account.lifetimeuser' in 'field list'") Doesn't matter the type of the field or the name. The base exception is: MySQLdb._exceptions.OperationalError: (1054, "Unknown column 'account_account.lifetimeuser' in 'field list'") Understand that this is NOT at runtime. It's right after I change the model and stop typing. Or in this case uncomment the lifetimeuser field (BTW, this is for testing only. I know I have an is_lifetime_user. That's the real field that was added sometime ago. Also note that this is ONLY with the Account model. Every other model in the file works as expected. Add, remove, edit: no problem as long as the syntax is correct. Since the error happens immediately, I can't makemigrations or migrate. I know my DB is in sync everywhere else. Can anyone give me a hint as to what is … -
Different One-To-Many relationships with same entities in Django
How would one go about implementing two different One-To-Many Relationships between the same entities in Django? For example: Suppose we have two relationships between a physical movement and muscles involved. For each movement I want to be able to distinguish between its main acting muscles and its supporting muscles. In practice I would introduce two tables (movement2primarymuscle, movement2supportingmucsle) and create a row with foreign keys for each relationship in each table. What's the Django way of implementing this with Django models? -
How to upload file from google drive to my django website?
I want the user to first upload the file from local system to google drive. Then my django website has a button to upload file from google drive to my website. -
How to dynamically create div class="row" using Django and Booststarp
I am trying to render some cards dynamically in my webpage. I want to render four cards in the first row and wants to render four more cards in the next row. How can I render div dynamically using django? Here is the view.py def User_View_Packages(request): package = Package.objects.all() return render(request, 'user_view_packages.html',{'package':package}) And index.html <div class="row"> {% for p in package %} <div class="col-md"> <div class="card" style="width: 18rem;margin-left:5%"> <img class="card-img-top" src="dp.39069 (1).jpeg" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ p.package_name }}</h5> <p class="card-text">STARTS FROM BDT. {{ p.package_cost }} PER PERSON</p> <p class="card-text">Location: INDIA</p> <a href="#" class="btn btn-primary">View More</a> </div> </div> </div> {% endfor %} </div> -
Django - sub-select returns 5 columns - expected 1
I have a django model Post with a M2M field views. When a visitor of the website views a post, he should be added to views. Here is the view: class ViewPostView(APIView): def get(self, request, format=None, *args, **kwargs): post_id = self.kwargs['post_id'] print(post_id) #17 this_post = get_object_or_404(Post, id=post_id) print(this_post) #Post abc post_count = this_post.views.all().count() print(post_count)#0 thisvisitor = get_visitor(request) print(thisvisitor)#<QuerySet [<Visitor: 127.0.0.1>]> if thisvisitor in this_post.views.all(): post_count = post_count else: post_count = post_count + 1 this_post.views.add(thisvisitor) data = {post_count} return Response(data) Traceback (most recent call last): File "/.../site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/.../site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) The above exception (sub-select returns 5 columns - expected 1) was the direct cause of the following exception: ... File "/.../views.py", line 388, in get this_post.views.add(thisvisitor) File "/.../site-packages/django/db/models/fields/related_descriptors.py", line 946, in add through_defaults=through_defaults, File "/.../site-packages/django/db/models/fields/related_descriptors.py", line 1129, in _add_items ], ignore_conflicts=True) File "/.../site-packages/django/db/models/query.py", line 493, in bulk_create objs_without_pk, fields, batch_size, ignore_conflicts=ignore_conflicts, File "/.../site-packages/django/db/models/query.py", line 1230, in _batched_insert self._insert(item, fields=fields, using=self.db, ignore_conflicts=ignore_conflicts) File "/.../site-packages/django/db/models/query.py", line 1204, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/.../site-packages/django/db/models/sql/compiler.py", line 1392, in execute_sql cursor.execute(sql, params) File "/.../site-packages/django/db/backends/utils.py", line 100, in execute return super().execute(sql, params) File "/.../site-packages/django/db/backends/utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) … -
(Django) Can you access model methods in Create & List View?
I have a StaffProfile Model and an Establishment Model. I'm using Class Based Views, and in each of the CRUD views for the StaffProfile Model I need to check that the User logged in is an admin at the Establishment the StaffProfile is a member of. To do this I have a get_establishment() method in the views and a UserIsAdmin mixin that checks the User is an admin of the Establishment. My question is: instead of having to copy and paste the exact same method in each view, can I put it in the model itself and then reference it? I know I can for DetailView, UpdateView, DeleteView... but for CreateView and ListView it doesn't work as there is no object to reference, so I'm wondering if there is another way to access the method? Or a different approach I should be taking? My Code (shortened & simplified): views.py # URL for view is: <slug:establishment_slug>/staff/create/ class StaffProfileCreate(LoginRequiredMixin, UserIsAdminMixin, generic.CreateView): form_class = CustomStaffProfileCreationForm template_name = 'profiles/create_staffprofile.html' login_url = "login" def get_establishment(self): establishment_slug = escape(self.kwargs.get('slug')) establishment = Establishment.objects.get(slug=establishment_slug) return establishment # URL for view is: <slug:establishment_slug>/staff/<int:staff_pk>/ class StaffProfileDetail(LoginRequiredMixin, UserIsAdminMixin, generic.DetailView): model = StaffProfile template_name="profiles/detail_staffprofile.html" login_url = "login" def get_establishment(self): establishment_slug = escape(self.kwargs.get('slug')) … -
update a model in the view of a django restframework view
I can't find examples of using patch to update a partial view in rest framework and it isn't computing for me. Here is my code: class ArworkIsSold(generics.RetrieveUpdateAPIView): permission_classes = [permissions.IsAuthenticatedOrReadOnly] serializer_class = ArtworkSerializer queryset = Artwork.objects.all() def partial_update(self, request, pk=None): data = {sold:True,forSale:False} serializer = ArtworkSerializer(context={'request': request},data=data, partial=True) serializer.is_valid() serializer.save() serializer.is_valid(raise_exception=True) return Response(serializer.data) However, it doesn't update and I get this error: NameError: name 'sold' is not defined My model does have sold and I am trying to just set the data in the view instead of sending it in from the ajax request. I just want to hit a view and have it update two fields. -
Django Paginator showing as disabled
I'm implementing a paginator in a blog section of a website, so that it only displays 6 items per page. Right now I have 7 items in the database, but it isn't displaying the paginator links as enabled, as if a second page didn't exist. The view: class PostListView(ListView): queryset = Post.published.all() context_object_name = 'posts' paginate_by = 6 template_name = 'blog/list.html' The template: <ul class="pagination"> {% if page.has_previous %} <li class="waves-effect"><a href="?page={{ page.previous_page_number }}"><i class="material-icons">chevron_left</i></a></li> {% else %} <li class="disabled"><a href="#!"><i class="material-icons">chevron_left</i></a></li> {% endif %} Page {{ page.number }} of {{ page.paginator.num_pages }} {% if page.has_next %} <li class="waves-effect"><a href="?page={{ page.next_page_number }}"><i class="material-icons">chevron_right</i></a></li> {% else %} <li class="disabled"><a href="#!"><i class="material-icons">chevron_right</i></a></li> {% endif %} </ul> And this is where I inserted the paginator object in the list template: <div class="col s12 m10 offset-m1 center"> <h1>blog</h1> <div class="row masonry-grid"> {% for post in posts %} <div class="col s12 m6 l4"> <div class="card fade-in-out up-in-out" data-duration="0"> <div class="card-image"> <a href="{{ post.get_absolute_url }}"><img src="http://placehold.it/600x400"></a> <span class="card-title">{{ post.title }}</span> </div> </div> </div> {% endfor %} </div> {% include 'pagination.html' with page=page_obj %} </div> So, the first page is displaying correctly, but the paginator isn't working and the second page (which should display, as I have … -
Django calls wrong function on given url
django calls the "listing" function even though I told it to use the "watchlist" function when handling the request which arises when going to the .../watchlist url. I can't find the problem. Here is the error: File "/home/simon/Dokumente/cs50WebProgramming/commerce/auctions/views.py", line 103, in listing listing_obj = AuctionListing.objects.get(id=int(listing_id)) ValueError: invalid literal for int() with base 10: 'watchlist' urls.py urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("create", views.create_listing, name="create"), path("after_create", views.after_create, name="after_create"), path("<str:listing_id>", views.listing, name="listing"), path("<str:listing_id>/bid", views.after_bid, name="after_bid"), path("watchlist", views.watchlist, name="watchlist") ] views.py def listing(request, listing_id): listing_obj = AuctionListing.objects.get(id=int(listing_id)) return render(request, "auctions/listing.html", { "listing": listing_obj }) def watchlist(request): return render(request, "auctions/watchlist.html") -
Trouble with django templating looping over a dict created from an xml response
I am trying to display data in the html page from an xml request. I have converted the xml content to a dict using xmltodict. The xml data is like this: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <countriesRS xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.hotelbeds.com/schemas/messages"> <from>1</from> <to>207</to> <total>207</total> <auditData processTime="30" timestamp="2020-10-01 18:10:02.666" requestHost="10.185.89.196" serverId="ip-10-185-88-253.eu-west-1.compute.internal.node.int-hbg-aws-eu-west-1.discovery" environment="[awseuwest1, awseuwest1a, ip_10_185_88_253]" release="cbd9f69ac1e7076b6ae86a8358f1e1bf26e00f44" internal="94d38b94f628408a9a0e41d7673d93a8"/> <countries> <country code="AD" isoCode="AD"> <description>Andorra</description> <states> <state code="CA"> <name>CANILLO</name> </state> <state code="EN"> <name>ENCAMP</name> </state> <state code="ES"> <name>ESCALDES - ENGORDANY</name> </state> <state code="AN"> <name>ANDORRA</name> </state> <state code="AD"> <name>ANDORRA LA VELLA</name> </state> <state code="07"> <name>ANDORRA</name> </state> <state code="XX"> <name>NOT ASSIGNED</name> </state> <state code="OR"> <name>ORDINO</name> </state> <state code="SJ"> <name>SANT JULIA DE LORIA</name> </state> <state code="MS"> <name>LA MASSANA</name> </state> </states> </country> <country code="AE" isoCode="AE"> <description>United Arab Emirates</description> <states> <state code="DU"> <name>UNITED ARAB EMIRATES</name> </state> <state code="FU"> <name>Fujairah</name> </state> <state code="AZ"> <name>Abu Dhabi</name> </state> <state code="AJ"> <name>Ajman</name> </state> <state code="07"> <name>UNITED ARAB EMIRATES</name> </state> <state code="XX"> <name>NOT ASSIGNED</name> </state> <state code="UQ"> <name>Umm Al Quwain</name> </state> <state code="RK"> <name>Ras Al Khaimah</name> </state> <state code="SH"> <name>Sharjah</name> </state> </states> </country> however, when i use a for loop to display the countries with {% for country in response.CountriesRS.countries %}, I can only see 'country' being displayed. How can I properly loop through this dict? This is how … -
Display song with preview_url and track name and image in spotipy search method
How to display all the track with their preview_urls and image and track name matching with the search query made in spotipy in django application. I am trying to do this below : sp = client_credentials_manager=SpotifyClientCredentials() track = sp.search("My Heart Will Go On", limit=10, offset=0, type='track', market=None) Now how to retrive above mentioned information from this track variable. -
How to adjust django qs-based table
I'm trying to render my Django queryset as table and adjust column sizes but simple changing class like: class="col-sm-2" dont give any results. Im using bootstrap4 and my code looks like so: <main role="main" class="container"> <table class="table"> <thead> <tr> <th class="col-sm-2">Name</th> <th class="col-md-1">Price</th> <th class="col-md-1">Weight</th> </tr> </thead> <tbody> {% for x in queryset %} <tr> <td>{{x.NAME}}</td> <td>{{x.WEIGHT}}</td> <td>{{x.PRICE}}</td> </tr> {% endfor %} </tbody> </table> </main> How to adjust these column sizes using bootstrap? And how to implement this together with following css: table { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } Because currently it only spans my rows all over the screen to avoid wrapping. Thanks. -
Why sometimes my python path from venv doesn't work?
When I try to run sudo python setup.py install having my venv activated, I get some Django and python version mismatch error, but when I use python path which is there in venv by copying its actual path and running the same command above just by replacing python path, it do works, so I am unable to understand which it worked when I kept actual path int it? Thanks in advance -
django.db.utils.OperationalError: duplicate column name: Email
I want to create a Django app that supports two different kinds of users. For that I have first extended my User by inheriting AbstractUser. Some fields are common to both the types of Users that I want my Django app to support and hence I add those fields in the extended User model. My User model is as follows. class User(AbstractUser): is_a = models.BooleanField(default=False) # a boolean flag to determine if this user is of type a is_b = models.BooleanField(default=False) # a boolean flag to determine if this user is of type b Name = models.CharField(max_length=128) Email = models.EmailField() MobileNumber = PhoneNumberField(null=False, blank=False, unique=True) Age = models.PositiveIntegerField() Gender = models.CharField(max_length=1, choices=GenderChoices) Organisation = models.CharField(max_length=128) Designation = models.CharField(max_length=128) def __str__(self): return self.Name I then make migrations. This is my first ever migration in this project. My migrations file is as follows: # 0001_initial.py # Generated by Django 2.0.1 on 2020-10-01 17:30 from django.conf import settings import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import phonenumber_field.modelfields class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0009_alter_user_last_name_max_length'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), …