Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
App deployed on Heroku doesn't show data from MySql DB
On development, I set up a clever cloud MySQL database to my Django project with these settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db-name', 'HOST': 'db-name-mysql.services.clever-cloud.com', 'PORT': 3306, 'PASSWORD': 'password', 'USER': 'user' } } It worked normally, so I created some data on this DB for testing. I deployed this app on Heroku, and when I successfully deploy it, I realized that the data shown on Heroku, is not the same as my clever cloud DB. I don't know if Heroku is using another database or why is not using my database. -
Trying to add variant product to cart js Django
Trying to add variant product to cart js Django I just don't really know how to add it to my cart in js and get it in my utils.py the code works well before I added variants to my models.py I am really torn how to make it work what is the right idea to add it fo function addCookieItem in cart.js and render it in the utils.py models.py class Product(models.Model): VARIANTS_CHOICES = ( ('None', 'None'), ('Size', 'Size'), ('Color', 'Color'), ('Size-Color', 'Size-Color'), ) category = models.ForeignKey("Category", on_delete=models.SET_NULL, blank=True, null=True) title = models.CharField(max_length=300) description = models.TextField() image = models.ImageField(default="") price = models.FloatField(default=0) slug = models.CharField(max_length=300) variant = models.CharField(choices=VARIANTS_CHOICES, max_length=70, blank=True, null=True) def __str__(self): return self.title def imageURL(self): try: url = self.image.url except: url = "" return url def image_tag(self): if self.image.url is not None: return mark_safe('<img src="{}" height="50" />'.format(self.image.url)) else: return "" class Images(models.Model): product = models.ForeignKey("Product", on_delete=models.SET_NULL, blank=True, null=True) title = models.CharField(max_length=300) image = models.ImageField(default="") def __str__(self): return self.title def imageURL(self): try: url = self.image.url except: url = "" return url class Color(models.Model): name = models.CharField(max_length=500) code = models.CharField(max_length=300, blank=True, null=True) def __str__(self): return self.name def color_tag(self): if self.code is not None: return mark_safe('<p style="background-color:{}" > Color </p>'.format(self.code)) else: return … -
Django - images uploaded by user does not display and shows 404 when Debug = False
I am developing a Django and using ImageFiled attributes into models that I need to display later. When I run the website in dev (DEBUG = True) it works, but when I change it to False (Production) uplaoded images do not display anymore and the console shows: "GET HTTP/1.1" 200 As I saw in other open questionsI tried to add in settings: MEDIA_ROOT = os.path.join(BASE_DIR, 'images') and in urls urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) But this doesn't work and even creates the same issue as in production. settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', 'gallery.apps.GalleryConfig', 'storages', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.locale.LocaleMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] DEBUG = False if not DEBUG: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_URL = 'static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) Update: The documentation says: URL that handles the media served from MEDIA_ROOT, used for managing stored files. It must end in a slash if set to a non-empty value. You will need to configure these files to be … -
How to display related information in two classes in django admin?
I'm working in django admin with two classes: Conference and Team. I created objects for both of them and I want them to be related. I created Conference North and South and I want to display the name of the teams that belong to each conference. But I also want to go to Teams and have a list of them and display to which conference they belong. Something like this (all in django admin. I'm not working with views): "App": Conferences North (and in another column "Team 1, Team 2") South ("Team 3", "Team 4") Teams Team 1 (North) Team 2 (North) Team 3 (South) Team 4 (South) I know I could set a ForeignKey to both of them but the goal is to create the Conference, add the teams and then on Teams having de conference display automatically. So that if I change something in one of the classes, it changes all automatically. Any idea how to do this? Thanks -
Django Rest Framework: QuerySet filtering not working as expected
I am using Django 3.2 and Django Rest Framework for an API. I am having difficulty getting it to work the way I would expect. I have a position table with sample data similar to this: [ { id: 1, position_date: '2022-01-01', symbol: 'AAPL', shares: 100 }, { id: 2, position_date: '2022-01-01', symbol: 'TSLA', shares: 100 }, { id: 3, position_date: '2022-01-01', symbol: 'GOOG', shares: 100 }, { id: 4, position_date: '2022-01-02', symbol: 'AAPL', shares: 200 }, { id: 5, position_date: '2022-01-02', symbol: 'TSLA', shares: 200 }, { id: 6, position_date: '2022-01-02', symbol: 'GOOG', shares: 200 }, { id: 7, position_date: '2022-01-05', symbol: 'AAPL', shares: 300 }, { id: 8, position_date: '2022-01-05', symbol: 'TSLA', shares: 300 }, { id: 9, position_date: '2022-01-05', symbol: 'GOOG', shares: 300 }, ] This data contains stock positions on a certain date. This daily snapshot position info is created only on weekdays/days the market is open, so there are gaps in the dates for weekends/market holidays. I want to query positions by position_date /api/v1/positions?position_date=<YYYY-MM-DD>, with the caveat that when you pass in a date that is not directly associated with a position, then you get the positions for the greatest date that is less than … -
Cannot Fill out form HTML
So I have a login screen that I have built, and I am using 3JS for the background animation. As of right now, I cannot actually click on the form to fill out the fields. When I hover my mouse over the Username input field, I can see that my mouse goes to the text input mode, but I cannot click on the element. Below is the HTML for this: {% extends "home/base.html" %} {% block title %} Login Page {% endblock title%} {% block content %} <main> <canvas id="bg" style="z-index: -1 !important; pointer-events: none !important"> </canvas> <div id='loginform' class="container-fluid fixed-top"> <div class="form-content my-3 p-3" style="z-index: 400"> <div class="container"> <div class="row justify-content-center"> <div class="col-lg-5"> <div class="card shadow-lg border-0 rounded-lg mt-0 mb-3"> <div class="card-header justify-content-center"> <h3 class="font-weight-light my-1 text-center">Sign In</h3> </div> {% if form.errors %} <div class="alert alert-danger alert-dismissible" role="alert"> <div id="form_errors"> {% for key, value in form.errors.items %} <strong>{{ value }}</strong> {% endfor %} </div> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> {% endif %} <div class="card-body"> <form method="POST"> {% csrf_token %} <div class="form-row"> <div class="col-md-10 offset-md-1"> <div class="form-group"> <a href="{% url 'social:begin' 'github' %}" class="btn btn-link btn-lg active btn-block">Sign in with GitHub</a> <a href="{% url 'social:begin' 'google-oauth2' … -
How to test django apps when my authorization is remote?
Currently I am using some tests like this: @pytest.mark.django_db(databases=["default"]) def test_list_boards(api_client): baker.make(Board) baker.make(Board, name="new") url = reverse("v1:boards-list") response = api_client().get(url) assert response.status_code == 200 assert len(json.loads(response.content)) == 2 edit: since I'm not using django User, this is my custom User: class User: def __init__(self, token, name, user_id, email, is_mega_user, is_authenticated): self.token = token self.name = name self.user_id = user_id self.email = email self.is_mega_user = is_mega_user self.is_authenticated = is_authenticated But now, I've added new custom authorization and permission classes in my application, so currently my tests are failling because of it. And I was thiking: What about when I dont have internet connection? I will not be able to test? How can I handle it? -
Django: Why is the Image Field not working
Good day, I am testing some stuff with Django image Fields and the user model. The point is simply that any user can upload and update a profile picture. But when I select a picture and press upload, I get the message 'This field is required. So it's as if I haven't selected anything. \\photo.html <form method="POST"> {% csrf_token %} {{ form }} <button type="submit">Upload</button> </form> \\views.py def photo_view(request): try: profile = request.user.userimage except UserImage.DoesNotExist: profile = UserImage(user=request.user) if request.method == 'POST': form = UserImageForm(request.POST, instance=profile) if form.is_valid(): form.save() return redirect('/dashboard/user/profile') else: form = UserImageForm(instance=profile) return render(request, 'photo.html', {'form': form}) \models.py class UserImage(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE) photo = models.ImageField( upload_to='images/', height_field=None, width_field=None, max_length=100) def __str__(self): return str(self.user) \\settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' I tried it with this one https://www.geeksforgeeks.org/imagefield-django-models/ Do someone know a solution? Or should I even use the ImageField when working with images? Thank you very much! :-) -
How do I store and retrieve user-defined rules in Django
I'm working on a requisition system using Django, and I want to implement a feature that allows the admin to set up rules. Instead of having to add a new feature for the tiniest of works, I want the admin to just add that as a rule, something similar to what Gmail does with filters. Basically a statement, condition, and action kinda pair. For example: FOR statement (all users, userId is less than, username starts with, etc.) WHERE condition (userID is equal to, date is less than, username starts with, etc.) PERFORM an action (delete user, assign user to new group, etc.) I am struggling with the logic for saving and retrieving this. Seeing that the statement, condition, and action pair will always change, how do I store these rules to DB and test against the rules while retrieving? Thanks -
When i go to add in the database on the admin panel, there is no input for username
Everytime i enter the admin panel and add a new account, each field allows me to enter a input except for the userID Model from asyncio import FastChildWatcher import email from pyexpat import model from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class userCouncil(BaseUserManager): def create_user(self, userID, password=None): if not email: raise ValueError("Email is required") user = self.model(userID = self.normalize_email(userID)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, userID, password): user = self.model(userID = self.normalize_email(userID)) user.set_password(password) user.is_staff = True user.is_admin = True user.save(using=self._db) return user class sni(models.Model): SNI = models.CharField(max_length=10, primary_key=True) # USERNAME_FIELD = 'SNI' def __str__(self): return self.SNI class Account(AbstractBaseUser): userID = models.EmailField(max_length=80, unique=True) name = models.CharField(max_length=100) dateOfBirth = models.DateField(max_length=8, null=True) homeAddress = models.CharField(max_length=100, null=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) sni = models.OneToOneField(sni, on_delete=models.CASCADE, null=True, blank=True) USERNAME_FIELD = 'userID' objects = userCouncil() def __str__(self): return self.userID def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True Admin from statistics import mode from attr import field from .forms import createUserForm from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import Account, sni class AccountAdmin(UserAdmin): list_display = ('userID', 'is_staff', 'is_admin') search_fields = ['userID'] readonly_fields = ('id','userID') add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('userID','name','password1','password2','dateOfBirth','homeAddress', 'is_staff', 'is_admin', 'sni' ), … -
Class Based View - Fields aren't created in database (python Inherits\django cbv)
I'm trying create a model inherit following this tutorial: https://www.digitalocean.com/community/tutorials/understanding-class-inheritance-in-python-3 Everything work. Can access FirstName property in child and show in view but when I run makemigration/migrate,inheriteds fields aren't created in table in database. (core-shark / core-trout) What's Can I doing wrong? Is possible, using python inherits and CBV, to create fields in database by makemigration/migrate? Thanks in advanced model.py class Fish(models.Model): def __init__(self, first_name, last_name="Fish"): self.first_name = first_name self.last_name = last_name def swim(self): print("The fish is swimming.") def swim_backwards(self): print("The fish can swim backwards.") class Meta: verbose_name = 'Fish' abstract = True def __str__(self): return self.first_name class Shark(Fish): def __init__(self, first_name, last_name="Shark", skeleton="cartilage", eyelids=True): self.first_name = first_name self.last_name = last_name self.skeleton = skeleton self.eyelids = eyelids def swim_backwards(self): print("The shark cannot swim backwards, but can sink backwards.") class Trout(Fish): def __init__(self, water ='', price = 0): self.water = water self.price = price super().__init__(self) class Meta: verbose_name = 'Trout' view.py class IndexView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) sammy = Shark("Sammy") terry = Trout() terry.first_name = "Terry" context['sammy'] = sammy context['terry'] = terry return context index.html ... <body style="color:red"> <h1>Fish Name: {{sammy.first_name}}</h1> <h1>Fish Name: {{terry.first_name}}</h1> </body> ... [2 project git -
Django aggregate field, but filtered by date
I,m trying to annotate a sum of another model, but filtered by date. I have the models Employee and Shift, the Shift one has a DecimalField called dur, a DateTimeField start and a foreign key employee. class Employee(models.Model): name = models.CharField(max_length=64) class Shift(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) start = models.DateTimeField() dur = models.DecimalField(max_digits=4, decimal_places=2, default=0) With Employee.objects.all().annotate(Sum('shift__dur')) I could add the total of all shifts, but how can I filter these shifts, e.g. to sum just the shifts in a given date range? Thanks in advance! -
Django self.groups.add(group) not adding group
I have a User model with role field. I want each user to be in one Group that corresponds to their role. So I try to set their group everytime user is saved. The problem is that user is not in any group after save. The important part of User model ... role = models.CharField('Rola', max_length=32, choices=RoleChoices.choices, null=True, blank=True ) def save(self, *args, **kwargs): self._set_role_stuff() super().save() self._set_group() pass def _set_role_stuff(self): if self.role and not self.role == RoleChoices.CLIENT: self.is_staff = True else: self.is_staff = False def _set_group(self): self.groups.clear() group = Group.objects.get(name='Fotograf') self.groups.add(group) How can I make it work? -
How can I resolve the 404 error in the product page here?
I'm making a website with a store. It looks like this: store -> catalog -> all products - > single product. When I going to a page with a single product, i get 404 error. views.py def product_view(request: WSGIRequest, product_slug: str): try: product = ( Product.objects .prefetch_related('productimage_set') .filter(slug=product_slug) .first() ) is_in_cart = CartProduct.objects.filter( product=product, cart__user=request.user, cart__active=True).first() context = { 'product': product, # 'is_in_cart': is_in_cart, } except Product.DoesNotExist: raise Http404 return render( request, 'shop/product.html', context) def category_list(request: WSGIRequest, category_slug: str): try: category: Category = ( Category.objects .prefetch_related("product_set") .get(slug=category_slug)) except Category.DoesNotExist: raise Http404 return render( request, 'shop/category.html', {"category": category}) urls.py path('', views.CatalogList.as_view(), name='shop'), path('<slug:category_slug>/', views.category_list, name='category'), path('<slug:product_slug>/', views.product_view, name='product') base urls path('admin/', admin.site.urls), path('shop/', include('page.shop.urls')), templates {% if product.productimage_set.all %} {% for image in product.productimage_set.all %} <div> <img src="{{ image.image.url }}" alt="{{ product.name }}"> </div> {% endfor %} {% endif %} -
Django displaying related objects
I have models for ProjectNotes and for ProjectNotesComments. ProjectNotesComments have a foreign key that is the ProjectNotes id. I am able to save comments on notes. I can see them in the admin panel. However I have not been able to figure out how to display the comments on the notes. Here are the models: class ProjectNotes(models.Model): title = models.CharField(max_length=200) body = tinymce_models.HTMLField() date = models.DateField(auto_now_add=True) project = models.ForeignKey(Project, default=0, blank=True, on_delete=models.CASCADE, related_name='notes') def __str__(self): return self.title class ProjectNoteComments(models.Model): body = tinymce_models.HTMLField() date = models.DateField(auto_now_add=True) projectnote = models.ForeignKey(ProjectNotes, default=0, blank=True, on_delete=models.CASCADE, related_name='comments') Here is the view: class ProjectNotesDetailView(DetailView): model = ProjectNotes id = ProjectNotes.objects.only('id') template_name = 'company_accounts/project_note_detail.html' comments = ProjectNotes.comments This is the template I am currently using to test getting the comments to display: {% extends 'base.html' %} {% block content %} <div class="section-container container"> <div class="project-entry"> <h2>{{ projectnotes.title }}</h2> <p>{{ projectnotes.body | safe }}</p> </div> <div> </div> {% for comment in comments %} <div class="comments" style="padding: 10px;"> <p class="font-weight-bold"> {{ comment.body | linebreaks }} </div> {% endfor %} <h2><a href="{% url 'add_project_note_comment' projectnotes.pk %}">add note</a></h2> {% endblock content %} -
Clients getting timed out when attempting to connect to the public websocket server (Python)
def first(request): PORT = 7890 print("Server listening on Port " + str(PORT)) async def echo(websocket, path): print("A client just connected") try: async for message in websocket: print("Received message from client: " + message) await websocket.send("Pong: " + message + "\npath - " + path) except websockets.exceptions.ConnectionClosed as e: print("A client just disconnected") loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) start_server = websockets.serve(echo, "", PORT) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() return HttpResponse("done") The above mentioned code is a Django request to start the websocket which has been deployed to aws elasticbeanstalk. def main(): async def listen(): url = "http://something.com:7890" # Connect to the server async with websockets.connect(url) as ws: # Send a greeting message await ws.send("Hello oku[dated!") # Stay alive forever, listening to incoming msgs while True: msg = await ws.recv() print(msg) # Start the connection asyncio.get_event_loop().run_until_complete(listen()) The second script is a locally run file to connect the websocket. So I keep getting an error while attempting to connect to the websocket saying asyncio.exceptions.TimeoutError at the last line of the script. So I wanted to know on how this can be made proper. Note: Both the website (websocket server) and client work fine when the code is run locally. The error is being caused only when the … -
Dynamic Url Routing In Django not working
dynamic url routing in post not working . it works properly without dynamic url but shows Page not found (404) Request Method: GET error urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index ,name='index'), path('count', views.count ,name='count'), path('register', views.register ,name='register'), path('login', views.login ,name='login'), path('logout',views.logout , name='logout'), path('post/<str:pk>/', views.post, name='post') ] views.py from django.shortcuts import render , redirect from django.http import HttpResponse from .models import Feature from django.contrib.auth.models import User, auth from django.contrib import messages # Create your views here. def post(request,pk): return render(request,'post.html',{'pk': pk}) post.html <h1>the value of pk is {{pk}}</h1> -
How to redirect any website by clicking an image in html where framework is Django?
Here, I want to redirect www.facebook.com if I click that Facebook logo but as I have a port number of 127.0.0.1:8000 therefore after clicking the image I'm redirecting http://127.0.0.1:8000/www.facebook.com and for that I'm getting Page Not Found(404) Error How can I fix this so that it will only redirect fb or insta? <ul class="nav col-md-4 justify-content-end list-unstyled d-flex"> <li class="ms-3"><a class="text-muted" href="www.facebook.com"><img src="/static/fb.png"></a></li> <li class="ms-3"><a class="text-muted" href="www.instagram.com"><img src="/static/insta.png"></a></li> <li class="ms-3"><a class="text-muted" href="www.twitter.com"><img src="/static/twitter.jpg"></a></li> </ul> -
django.db.utils.DatabaseError: ORA-02267: column type incompatible with referenced column type
Im using Django and Oracle, I have to use some table from another Scehma class ModelTable1(models.Model): official_id = models.CharField(db_column="ID_OFFICIAL", primary_key=True, max_length=20) field_1 = models.CharField(max_length=25, db_column="COLUMN_X", blank=True, null=True) field_2 = models.CharField(max_length=25, db_column="COLUMN_Y", blank=True, null=True) class Meta: db_table = '"SCHEMAX"."TABLE1"' default_permissions = [] managed = False When I try to relationship with a model from my schema and running the migration I have this error: django.db.utils.DatabaseError: ORA-02267: column type incompatible with referenced column type My model definition is: class ModelTable2(AuditDataMixin): id = models.AutoField(db_column='ID', primary_key=True) official_id = models.ForeignKey( ModelTable1, models.DO_NOTHING, db_column="ID_OFFICIAL" ) status = models.CharField(db_column='ESTADO', max_length=2, blank=True, null=True) class Meta: db_table = 'TABLE2' default_permissions = [] When I went to the table I can see the problem, SCHEMAX.Table1.ID_OFFICIAL is type Varchar2(20) and MYSCHEMA.Table2.ID_OFFICIAL is type NVARCHAR2(20). What could I do than When I run migration the FK be created like Varchar2? Thanks!! -
Django views not able to show the dictionary object data
I have the below queryset query_data= <QuerySet [{'month': datetime.date(2022, 1, 1), 'count': 9}, {'month': datetime.date(2021, 12, 1), 'count': 9}]> But when I try to do in views {% for mm in query_data %} <span>{{mm['month'] | date: 'F' }}</span> {%endfor%} It is not showing the data but if I did <span>abcd</span> it is showing the abcd -
Uploding Multiple Imgs in Django-rest-framework using React js
Hey I am trying upload multiple img to django rest framework using react js. However, I tried with only one pic and It's done,but not multiple. I really don't know what's the fields for that. here is my model.py class Notes(models.Model): title = models.CharField(max_length=50) desc = models.TextField() time=models.TimeField(auto_now=True) img = models.ImageField(upload_to='img',null=True) #here I want multiple img src user = models.ForeignKey(User, on_delete=models.CASCADE , related_name='notes') def __str__(self): return self.title Serializer.py class NoteSerializer(serializers.ModelSerializer): class Meta: model = Notes fields = ['id','title','desc','img','time'] views.py class getNotes(ModelViewSet): authentication_classes = [BasicAuthentication ,TokenAuthentication] permission_classes = [checkPermission] parser_classes = (MultiPartParser, FormParser) queryset = Notes.objects.all() serializer_class = NoteSerializer def list(self, request , **kwa): notes = Notes.objects.filter(user=request.user.id) serialzer = NoteSerializer(notes, many=True) return Response(serialzer.data) def create(self, request, **kwargs): notes = NoteSerializer(data=request.data) if notes.is_valid(): print(request.user) notes.save(user=request.user) return Response(notes.data) else: return Response(notes.errors) What should I do for getting multiple img and save them all... Frontend Part function to send img using fetch api let uploadPicture = (e)=>{ console.log(e.target.files); // setImg(e.target.files); let img=[]; let fd = new FormData() for (var index = 0; index < e.target.files.length; index++) { console.log(e.target.files[index]); img.push(e.target.files[index]) } fd.append('pic',e.target.files[0]) console.log("Fd ",fd.get('pic')); setImg(fd.get('pic')) console.log("Cimg ",Cimg); } This is input tag <div className="mb-3"> <label htmlFor="img" className="form-label">Picture</label> <input type="file" multiple className="form-control" placeholder='Enter your img...' onChange={uploadPicture} … -
When I run my Django project developed on Windows on Ubuntu it gives errors as below, even after creating virtualenv and configured properly
Here is the errors I have installed and created virtualenv as same like the one on Windows and replaced it on Ubuntu with that new one. I could activate the virtual but when I do python3 manage.py runserver it gives error as like below. If someone help, it will be grateful. Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/pema/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/pema/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/pema/.local/lib/python3.6/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/pema/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 61, in execute super().execute(*args, **options) File "/home/pema/.local/lib/python3.6/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/pema/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 96, in handle self.run(**options) File "/home/pema/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 105, in run self.inner_run(None, **options) File "/home/pema/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/home/pema/.local/lib/python3.6/site-packages/django/core/management/base.py", line 423, in check databases=databases, File "/home/pema/.local/lib/python3.6/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/pema/.local/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/pema/.local/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/pema/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 416, in check for pattern in self.url_patterns: File "/home/pema/.local/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/pema/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 602, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/pema/.local/lib/python3.6/site-packages/django/utils/functional.py", line … -
django For loop in html table want arrange data based on column then go to second row
how make loop for every column in table then move for next row from data retired from model as per photo the next entry come in next row but i need it to come in first row second column <thead> <tr class="bg-light-gray"> <th class="text-uppercase">Time </th> <th class="text-uppercase">Monday</th> <th class="text-uppercase">Tuesday</th> <th class="text-uppercase">Wednesday</th> <th class="text-uppercase">Thursday</th> <th class="text-uppercase">Friday</th> <th class="text-uppercase">Saturday</th> <th class="text-uppercase">Sunday</th> </tr> </thead> <tbody> {% for item in groupcoursesform %} <tr > <td class="align-middle">09:00am</td> <td> {% if item.day == 'Monday' %} <div class="font-size13 text-light-gray">{{item.group_name}}</div> {% endif %} {% if item.day == 'Tuesday' %} <div class="font-size13 text-light-gray">{{item.group_name}}</div> {% endif %} </td> </tr> {% endfor %} for loop -
No installed app with label 'admin' when adding dj_rest_auth
In my django project, i have already included the admin in installed apps like this, INSTALLED_APPS = [ "django.contrib.admin", ] I am already using django admin well. After some time, i needed to install dj_rest_auth module to my project, but whenever i add this module, it raises the error No installed app with label 'admin' File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/project/urls.py", line 21, in <module> path("admin/", admin.site.urls), File "/project/lib/python3.8/site-packages/django/utils/functional.py", line 256, in inner self._setup() File "/project/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 529, in _setup AdminSiteClass = import_string(apps.get_app_config('admin').default_site) File "/project/lib/python3.8/site-packages/django/apps/registry.py", line 162, in get_app_config raise LookupError(message) LookupError: No installed app with label 'admin'. -
Django error. module 'django.http.request' has no attribute 'POST'
I am new to Django and I am trying to create a simple web application. I've created a login form and added a hyperlink for signing up for new users. Unfortunately, I got the following error. module 'django.http.request' has no attribute 'POST' In the bellow you will find view.py code: from django.shortcuts import render from django.http import HttpResponse, request from django.db import connection from django.contrib.auth.decorators import login_required import pyodbc def index(request): if 'Login' in request.POST: rows = [] username = request.POST.get('username') if username.strip() != '': rows = getLogin(username) if len(rows) > 0: return render(request, 'login/welcome.html') else: return render (request, 'login/index.html') else: return render (request, 'login/index.html') else: return render (request, 'login/index.html') def newUser(requset): if 'NewUser' in request.POST: return render(request,'login/newuser.html') def getLogin(UserName=''): command = 'EXEC GetLogin\'' + UserName + '\'' cursor = connection.cursor() cursor.execute(command) rows = [] while True: row = cursor.fetchone() if not row: break userName = row[0] password = row[1] name = row[2] email = row[3] rows.append({'userName': userName, 'password': password, 'name': name, 'email': email}) cursor.close() return rows @login_required(login_url='/') def readLogin(request): if request.user.is_authenticated: rows = getLogin() return render(request, 'login/loginsdata.html', {'rows': rows}) else: return HttpResponse('You are not authenticated</br>') Here urls.py code of the login app: from django.urls import path from . import …