Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to combine generic `detailsView` and `CreateView` in a single view in django
I'm trying to combine detail and create in a single view in Django generic views, here is my code : models.py class Supplier(models.Model): person_name = models.CharField(max_length=850) company_name = models.CharField(max_length=1200) phone = models.CharField(max_length=15) email = models.EmailField(max_length=250, null=True) address = models.CharField(max_length=2200) def __str__(self): return self.company_name def get_absolute_url(self): return reverse('supplier_details', args=[str(self.id)]) class SupplierItem(models.Model): supplier = models.ForeignKey(Supplier, on_delete=CASCADE) item = models.ForeignKey(Item, on_delete=CASCADE) unit_price = models.DecimalField(max_digits=19, decimal_places=10, default=00.00) def __str__(self): return self.item.name urls.py path('<int:pk>/details', views.SupplierItemsView.as_view(), name="supplier_details"), views.py class SupplierItemsView(View): def get(self, request, *args, **kwargs): view = SupplierDetailsView.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = SupplierItemCreate.as_view() return view(request, *args, **kwargs) class SupplierDetailsView(DetailView): model = Supplier class SupplierItemCreate(CreateView): model = SupplierItem fields = ['item', 'unit_price'] Now I want the detail view to be viewed including the create view inside of it, I've tried to render the HTML like this : templates/appName/supplieritem_forms.html <form method="post"> {{ form }} </form> templates/appName/supplier_detail.html .... {% include 'profiture_supplier/supplieritem_form.html' %} .... The result that it shows the details HTML view rendered perfect, but the form is never shown -
Django and Firebase Auth
I'm trying to use Firebase Auth with Django, but I have a few questions. So far, I've successfully created a demo app with a login form. Upon load the page checks if firebase.auth().currentUser is set, and disables the Login button if so. If not set, then login form is editable. When user logs in, I'm calling firebase.auth().signInWithEmailAndPassword. If that succeeds, I'm calling a backend view through Ajax to verify the ID token. Now I'm trying to tie all this in with a more realistic Django app. There's some index resource at, say www.example.com, and there's the login page at www.example.com/login. When user first goes to www.example.com, the view will check if the ID token exists in the request (and verify it if yes), and then return the index resource. If not, it will redirect to login resource. Once on the login page, how would I send the user to the index page after login with the ID token in the request header? I can make ajax requests from the login page, but how do you actually send the user to another page with this authorization header in "Django style"? -
AJAX sending empty FormData
I;m trying to send a file via ajx FormData but it is sending None instead. JS: $('#hide').click(function(e){ e.preventDefault(); var fd = new FormData(); fd.append('file', $('#lecturefile').prop('files')[0]) $.ajax({ type: 'POST', url: "{% url 'create_course' instructor.id %}", headers: { 'X-CSRFToken': $('input[name=csrfmiddlewaretoken]').val() }, data: fd, processData: false, contentType: false, success:function(){ console.log('done!!') } }); }); Views.py: file = request.FILES.get('data') print(file) con = CourseContent.objects.filter(user = request.user).latest('id') lec = CourseLecture.objects.filter(content = con).latest('id') lec.file = file lec.save() Printing var file gives None. Appreciate the help. -
How could I modify django-tracking2 so users can opt out of tracking
I'm making a website right now and need to use django-tracking2 for analytics. Everything works but I would like to allow users to opt out and I haven't seen any options for that. I was thinking modifying the middleware portion may work but honestly, I don't know how to go about that yet since I haven't written middleware before. I tried writing a script to check a cookie called no_track and if it wasn't set, I would set it to false for default tracking and if they reject, it sets no_track to True but I had no idea where to implement it (other than the middle ware, when I tried that the server told me to contact the administrator). I was thinking maybe I could use signals to prevent the user being tracked but then that would slow down the webpage since it would have to deal with preventing a new Visitor instance on each page (because it would likely keep making new instances since it would seem like a new user). Could I subclass the Visitor class and modify __init__ to do a check for the cookie and either let it save or don't. Thanks for any answers, if … -
Django form CharField not setting initial value
I am trying to set initial values in a Django form that is shown more than once in a view. Unfortunately even with 3 hours of searching and debugging, it ends up like everything I have tried does not work. My form is used to create a message object linked to a conversation (I'm building a chatbot app) and in my conversation template I show every message in a form to make it editable afterwards. The problem is that every field of the form does set the default value I passed to the form inside the message_values var in my view.py except one : the "tag_list" CharField (see below). I cannot use ModelForm because a message is composed of several models (q_reply_* fields will create QuickReplies() objects in my view, tags will create several Tags() etc.) I have tried passing the data specifying initial = message_values in the view when creating the form, setting the value through __init__ by getting the value in kwargs (like i did for the messages var) but it just does not want to work... I don't get any error anywhere, zero warnings and when debugging I got the confirmation that my ManyToMany where I get … -
How do I customize the display of username field of default User Model in Django ModelForm without extending User Model?
I have a default User Model, with which I have connected a ModelForm. In the ModelForm, I am accessing the username field of the default User Model. It works fine as usual, it shows the username(s) of the users. But I don't want it to just show username, instead I want to show the custom content of each user. I want to show first_name, last_name and username of the user in the following format: {first_name last_name - (username)} Current display of the username filed: user1 user2 user3 user4 # # # Desired display of the `username field: John Doe - (user1) Doni Marquart - (user2) Geoff Roberts - (user3) Alice Woods - (user4) # # # Does anyone know how can I accomplish it without extending the default User Model? Thanks -
Receiving Integrity Error from CustomUserModel form
I would like to create a form with my CustomUserModel as shown below, which has a extending model called customer. class UserManager(BaseUserManager): def create_user(self, email, password=None,is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError("Users must have email address") user_obj = self.model(email = self.normalize_email(email)) if not password: raise ValueError("Users must have a password") user_obj.set_password(password) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_staffuser(self,email,password=None): user = self.create_user(email, password=password,is_staff=True) return user def create_superuser(self, email, password=None): user = self.create_user(email, password=password, is_staff=True, is_admin=True) return user class User(AbstractBaseUser): email = models.EmailField(max_length=255,unique=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) USERNAME_FIELD = 'email' # email and password are required by default REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active class Customer(models.Model): GENDER = ( ('Male', 'Male'), ('Female', 'Female'), ) TITLE = ( ('Mr', 'Mr'), ('Mrs', 'Mrs'), ('Miss', 'Miss'), ('Ms', 'Ms'), ('Dr', 'Dr'), ('Sir', 'Sir'), ('Madam', 'Madam'), ) user = models.OneToOneField(User,on_delete=models.CASCADE) title = models.CharField(max_length=200, null=True, choices=TITLE) first_name = models.CharField(max_length=200, null=True) middle_name = models.CharField(max_length=200, blank=True,default='') last_name = models.CharField(max_length=200, … -
Django | Error when insert imageName with for into static url
Error when we want to insert image file name into static url. No all has imageName. Error: Invalid block tag Code: <img width="40%" src="{% static 'files/img/ {% for i in questions %} {% i.imageName %} {% endfor %} ' %}"> -
How to Create a Model for to complex Json Strucuture in django Rest Framework
I am using Latest Django 3.0 and Database: Postgress and frontend Angular using for this This is my example Json can we able to create for this Complex Json { 'id' : '1', 'name' : 'A Walk Amongst Friends - Canvas Print', 'handle' : 'a-walk-amongst-friends-canvas-print', 'description' : 'Officia amet eiusmod eu sunt tempor voluptate laboris velit nisi amet enim proident et. Consequat ', 'categories' : [ 'Canvas Print', 'Nature' ], 'tags' : [ 'canvas-print', 'nature' ], 'featuredImageId' : 1, 'images' : [ { 'id' : 0, 'url' : 'assets/images/ecommerce/a-walk-amongst-friends.jpg', 'type': 'image' }, { 'id' : 1, 'url' : 'assets/images/ecommerce/braies-lake.jpg', 'type': 'image' }, { 'id' : 2, 'url' : 'assets/images/ecommerce/fall-glow.jpg', 'type': 'image' }, ], 'priceTaxExcl' : 9.309, 'priceTaxIncl' : 10.24, 'taxRate' : 10, 'comparedPrice' : 19.90, 'quantity' : 3, 'sku' : 'A445BV', 'width' : '22', 'height' : '24', 'depth' : '15', 'weight' : '3', 'extraShippingFee': 3.00, 'active' : true }, Please Help On this to create a list of string and json objects in the django Thanks in Advance -
Why FormView not saving data within a DetailView?
I have a DetailView Based on a model ( A ) and on the same template I have a ModelFormView from a model B which has FK to model (A) The data from form doesn't get saved to the database. This is the DetailView: class LocationView(DetailView): template_name = "base/stocks/location.html" model = LocationStock def get_context_data(self, **kwargs): context = super(LocationView, self).get_context_data(**kwargs) context['form'] = OutsModelForm return context def get_object(self): id_ = self.kwargs.get("id") return get_object_or_404(LocationStock, id=id_) This is the FormView: class OutsAdd(FormView): form_class = OutsModelForm success_url = reverse_lazy('base:dashboard') def form_valid(self, form): return super().form_valid(form) This is the url.py: path('locations/<int:id>', LocationView.as_view(), name='location-detail'), path('locations/outs', require_POST(OutsAdd.as_view()), name='outs-add'), This is the template: <form method="POST" action="{% url 'outs-add' %}" > <div class="modal-content"> {% csrf_token %} {% render_field form.quantity placeholder="Quantity"%} {% render_field form.id_year placeholder="Year"%} {% render_field form.id_location placeholder="ID Location"%} </div> <div class="modal-footer"> <input class="modal-close waves-effect waves-green btn-flat" type="submit" value="Save"> </div> </form> The data gets POSTED in the /locations/outs but is not saving to the actual database.How can I save it ? -
Python / Dajngo App deployed using WSGI is getting stuck to generate the HTTP response
I'm using Heroku to deploy my application, I'm using gunicorn. For some requests, we're facing a really long time to generate the HTTP response, generated by the WSGI handler. The logs don't provide any insights and checking new relic I found this information: [Transaction chart][1] [1]: https://i.stack.imgur.com/9vt0p.png [Transaction breakdown][2] [2]: https://i.stack.imgur.com/P1f98.png [Transaction trace][3] [3]: https://i.stack.imgur.com/AJkKQ.png Do you know what could be happening? or do you have any advice about how to approach these kinds of problems? thanks! -
Django: render included template automatically
So I include 'navbar.html' in my 'base.html' Django template. I know that you can render it in each view function separately, but is there a way to create its own view function that will render it at its own without a call in urls.py? -
How to configure UPLOADS behind SSL
I am having an issue with retrieving uploaded images from my server. I have the following configurations: project/urls.py urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += [ path('adminx/', admin.site.urls), path('admin_app/', include('admin_app.urls')), path('app/', include('app.urls')), re_path(r'^(?:.*)/?$', include('app.urls')), # THIS ROUTE IS TO LOAD MY REACT APP ] settings.py MEDIA_ROOT = '/home/ubuntu/uploads' MEDIA_URL = '/uploads/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") Nginx config: upstream gunicorn{ server unix:/home/ubuntu/mysite/project.sock fail_timeout=0; } server { listen 443 ssl http2; server_name *.mysite.com; ssl_certificate /etc/ssl/private/ssl-bundle.crt; ssl_certificate_key /etc/ssl/private/briefing_key.pem; # path for static files root /home/ubuntu/mysite/project/project; location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://gunicorn; } } server { # if a request is made on port 80 to your domain, it will be redirected if ($host = mysite.com) { return 301 https://$host$request_uri; } if ($host = www.mysite.com) { return 301 https://$host$request_uri; } listen 80; server_name *.mysite.com; return 404; } On my DEV rig, it all works perfectly. On my PROD rig, I can upload images, no problem. However, when I try to link to them, Django wants to spit out the HTML for my React app instead of the image. How can I adjust this so it pulls the image … -
Django dependant form fields from 2 forms
I've searched a bit but I can not find any problem/solution similar to what I have. I hope you can help me out. I know I will need to use Django's clean function, but I'm lost in what way I can get this to work. The answer will be pretty straight forward, but I'm oblivious. Now I have two models, ContractInfo and PersonInfo. class ContractInfo(models.Model): ... contract_nr = models.CharField(max_length=20, blank=False, null=False) person = models.ForeignKey(PersonInfo, blank=True, null=True, on_delete=models.CASCADE) class PersonInfo(models.Model): ... person_firstname = models.CharField(max_length=25, blank=True, null=True) person_prefix = models.CharField(max_length=15, blank=True, null=True) person_lastname = models.CharField(max_length=50, blank=True, null=True) They both have their own forms. I want to be able to either pick an existing name that is already registered, or make a new one if the name isn't registered yet. It has to be on the same page. My original views.py before I had this bright idea: def addcontract(request): addcontract = AddContractForm() addperson = AddPersonForm() if request.method == "POST": form = AddContractForm(request.POST) if form.is_valid(): contract = form.save(commit=False) contract.user = request.user contract.contract_warning = vehicle.contract_end-datetime.timedelta(days=30) contract.contract_active = True contract.save() return HttpResponseRedirect(reverse('contracts')) else: form = AddContractForm() else: form = AddContractForm() return render(request,'addcontract.html',{'addcontract':addcontract}) I've tried finding some examples, but either my searching as become worse or there … -
MakeMigrations persisted
Here's the model!! from django.conf import settings from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title Migrations for 'blog': blog\migrations\0001_initial.py - Create model Post Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File Blockquote "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\core\management__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\core\management__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 182, in handle self.write_migration_files(changes) File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 219, in write_migration_files migration_string = writer.as_string() File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\db\migrations\writer.py", line 141, in as_string operation_string, operation_imports = OperationWriter(operation).serialize() File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\db\migrations\writer.py", line 99, in serialize _write(arg_name, arg_value) File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\db\migrations\writer.py", line 51, in _write arg_string, arg_imports = MigrationWriter.serialize(item) File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\db\migrations\writer.py", line 271, in serialize return serializer_factory(value).serialize() File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\db\migrations\serializer.py", line 37, in serialize item_string, item_imports = serializer_factory(item).serialize() File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\db\migrations\serializer.py", line 199, in serialize return self.serialize_deconstructed(path, args, kwargs) File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\db\migrations\serializer.py", line 86, in serialize_deconstructed arg_string, arg_imports = serializer_factory(arg).serialize() File "C:\Users\dill\PycharmProjects\Myblog\venv\lib\site-packages\django\db\migrations\serializer.py", line 339, … -
How to manage slug in views.py django
I'm having trouble dealing with slugs: I have defined different slugs for every article in admin panel but on my website, if I type any random slug(e.g- fvrryybr,34,d4g5tg5) on any page of my app it takes me to the webpage of article function of views.py I don't know how to deal with as I a beginner in Django ____view.py___ def article(request,slug): allarticles = Article.objects.all() context = {'allarticles':allarticles} return render(request,"news/Home/tnews/blog-single.html",context) models.py class Post(models.Model): no = models.CharField(max_length=1000,primary_key=True) title = models.CharField(max_length=100) content = models.TextField() cover = models.ImageField(upload_to='images/') timeStamp = models.DateTimeField(blank=True) slug = models.SlugField(null=False,unique=True) def __str__(self): return self.title class Article(models.Model): heading = models.CharField(max_length=1000) player = models.CharField(max_length=100) article = models.TextField() source = models.CharField(max_length=50) date = models.DateTimeField(blank=True) image = models.ImageField(upload_to='images/') def __str__(self): return 'Article on '+ self.player urls.py path("<slug:slug>",views.article,name='article') -
Is it really possible to build a tree user system in Django?
So i'm trying to create an app that allows me to add users (from here i will call them "clients") and some of these clientes will have the ability to add their own clients. Every client would have "virtual money" on their account and if they have the ability to add clients, they can transfer from his money to their clients. (This may be irrelevant, but you may have to know it just in case). So i create a model (Profile) that has one to one field so everytime i add an user, a profile will be created related to them. class Profile(models.Model): //This one creates a profile with one single users user = models.OneToOneField(User, blank=True, on_delete=models.CASCADE) //Money users have in their accounts money = models.IntegerField(default=0, blank=True) // Some others fields i need like adress, etc //If this is True, this client can add his own clients that should be below him in the tree add_clients = models.BooleanField(default=False) // This client should have a parent, as im (superuser) will be the first user, i should be the parent of every client i add, but then if this client can add clients, the parent should be him instead of me, in … -
How can I pass in a char field that is basically a random string of 32 length characters in the django urls?
Ok, so I created a model which is basically this: class Code(models.Model): unique_id = models.CharField(default=get_random_string(length=32), max_length=32) def __str__(self): return self.unique_id This just creates a random string like "bSh0aO3fSTMTOwTCXg2sl0IKc807yvLa." The thing is I'm trying to get the unique id to be passed through a url so that the creator can make their own poll. I went about it using this code: urlpatterns = [ path('', homepage, name='homepage'), path('create/<str:new_code>', create_poll, name='create_poll') ] Now, for the homepage html template, I have a button that does this: <button class="btn btn-outline-secondary btn-work"><a href="{% url "create_poll" new_code.unique_id %}">Create Poll</a></button> Whenever I click on it, django gives me this error: ValueError at /create/bSh0aO3fSTMTOwTCXg2sl0IKc807yvLa Field 'id' expected a number but got 'bSh0aO3fSTMTOwTCXg2sl0IKc807yvLa'. I know how to pass in pk and ids, but later on down the road, I'll need to create another template where people will enter a code and be redirected to questions that were made that relate to the unique id. What am I missing here? Sorry if this is kinda long, but I tried to read the django docs and looked up how to pass in model char fields to URl, but nothing helps. Thanks in advance -
Getting error when running heroku and django
followed a tutorial setting up an app with django and using heroku. I got everything uploaded, but am getting an error that prevents the app from fulling working. ModuleNotFoundError: No module named 'djangoproject' at=error code=H10 , status=503 gunicorn.errors.HaltServer: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 525, in reap_workers From research that I have done there is talk about Apache and python version conflict. I am using python: 3.7.7 and Apache: Server version: Apache/2.4.41 (Unix) my operating system is macos. Not sure how to fix this issue. -
how to add log traces for django's API dispatcher (django 1.11)
I have an old (Django 1.11) over complicated Django application with overlapping and funnily ordered url matching rules and I want to update it to newer Django versions and to simplify / refactor. For better understanding Id' like to navigate through the application (manually) and retrieve some traces Would it be possible to achieve following without having to add log statements in every view. I'd like to get traces telling me which rule was picked by the url dispatcher (and if possible, but not really necessary), which view with which parameter was called. I'm for example sure, that some rules can just be deleted as they're no more used. decorators, monkeypatches, whatever will do as long as I don't have to change all individual rules and all views to get my traces. -
How to redirect properly in Django URL , I am having issue in redirecting
Having issue with redirecting, I am at registration page("accounts/register") on my website where I want if someone register then a verification code will send on his email id and to verify we have a url "accounts/verify". but when I am trying to register it register a user but does not send them on "accounts/verify" instead it send that to "accounts/register/accounts/verify" , Also please let me know how to use user email address, while registering him into database. I just want his email id to send verification code. Here is my URL.py of my app: from django.contrib import admin from django.urls import path,include from . import views from django.contrib.auth.models import User urlpatterns = [ path('login/', views.login, name='Login-Page'), path('register/', views.register, name='Registeration-page'), path('logout/', views.logout), path('verify/', views.verify, name='verification page') Here is my View.py for registration and profile: from django.shortcuts import render, redirect import requests from django.contrib.auth.models import User, auth from django.contrib import messages from datetime import date import smtplib import random from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def register(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] password2 = request.POST['password2'] if password1==password2: if User.objects.filter(username=username).exists(): messages.info(request, "Username already taken") return redirect('accounts/register') elif … -
How choose random record from DB Django and render result into template?
User on index.html choose Theme question (q_category in models.py), tap on button and get Question(question in models.py). DB of questions already exists (300 questions and 12 themes). How to random question, which filtred by q_category and get result in template? I heard about .objects.order_by('?')[0], but i cant figured it out in my project. Models.py: class Questions(models.Model): question = models.CharField('Вопрос',max_length=200) q_category = models.CharField('Тема',max_length=200) class Meta: verbose_name = "Question" verbose_name_plural = "Questions" def __str__(self): return self.question Views.py: from django.shortcuts import render from django.http import HttpResponse def index(request): return render(request, 'cards/index.html', {}) index.html: {% extends 'base.html' %} {% block content %} <div> <h1>Question generator</h1> <p>Theme question</p> # choose q_category in models.py <button>Get your question</button> </div> {% endblock %} -
python: can't open file 'manage.py
i just finishing running the makemigration & migrate command it's OK but when i run python manage.py createsuperuser i receive this message : python: can't open file 'manage.py': [Errno 2] No such file or directory i did not know what is my mistake this is my python file: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'oasisconsuting.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() maybe (i'm not sure) i change some code or anything -
Django admin page not showing user models
My admin page is working fine except when logged in it is not showing any user models. It is hindering my work as I cannot manage users. I have made custom models as shown below. Database is MySQL. models.py class User(AbstractUser): is_customer = models.BooleanField(default=False) is_restaurant = models.BooleanField(default=False) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) food_pref = models.CharField(max_length=10, default='veg') class Restaurant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) restaurant_name = models.CharField(max_length=100, blank=False) -
waypoint infinite scroll loads the next page only once
Html: <div class="loading" style="display: none;"> <div id=circle2></div> <img class=virus id=incircle2 src="{% static 'icons\virus.png' %}" alt="virus"> </div> {% if entries.has_next %} <a class="infinite-more-link" href="?page={{ entries.next_page_number }}"></a> {% endif %} JS: var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], onBeforePageLoad: function () { $('.loading').show(); }, onAfterPageLoad: function ($items) { $('.loading').hide(); } }); Well I found only one similar question and the recommended solution was to wrap the tag in span as: <span><a href="load-more.php" class="infinite-more-link">More</a></span> But that solution didn't work for me, thank you all for reading.