Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Writing JavaScript function in Django models
I would like to get long, lat variables from my models.py, which looks something like this: from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator class Marker(models.Model): latitude = models.FloatField( validators=[MinValueValidator(-90), MaxValueValidator(90)], ) longitude = models.FloatField( validators=[MinValueValidator(-180), MaxValueValidator(180)], ) And add fetch them to the line myLatLng in JavaScript function initMap() { const myLatLng = { lat: -25.363, lng: 131.044 }; const map = new google.maps.Map(document.getElementById("map"), { zoom: 4, center: myLatLng, }); new google.maps.Marker({ position: myLatLng, map, title: "Hello World!", }); } the sample code is here: https://developers.google.com/maps/documentation/javascript/examples/marker-simple So I would like to create a marker from my admin page and display it on the map -
TemplateDoesNotExist at / Home.html Exception Type: TemplateDoesNotExist
My Customers urls.py ''' from django import urls from django.urls import path from django.urls.resolvers import URLPattern from . import views urlpatterns = [ path('', views.Home ,name= 'Home'), path('Hall/', views.Hall ,name= 'Hall'), path('Food_item/', views.Food_item ,name= 'food'), path('About_us/', views.About_us ,name= 'about'), ] ''' My Web_project urls.py ''' from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('customer.urls')), ] ''' Settings.py Templates ''' 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', ], }, }, ] Customers View.py ''' from django.http.response import JsonResponse from django.shortcuts import render def Home(request): return render(request, "Home.html", {"title":" Home"}) def Hall(request): return render(request, "Hall.html", {"title": "Hall"}) def Food_item(request): return render(request, "Food_item.html", {"title": "Food_item"}) def About_us(request): return render(request, "About_us.html", {"title": "About_us"}) ''' My cd is web_project>customer>templates>customer>Home.html The error it showing ''' Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\Nawaf Bhatti\Desktop\New\web_project\templates\Home.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\rest_framework\templates\Home.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site- packages\django\contrib\admin\templates\Home.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site- packages\django\contrib\auth\templates\Home.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\Nawaf Bhatti\Desktop\New\web_project\customer\templates\Home.html (Source does not exist) ''' -
How to serve premium content base on user subscription in django
Hello guys i hope the way i ask this questions meets the standard way of stackoverflow. I have a projects i'm working on. On this project you need to subscribe a plan (monthly, 3 months or 6 months) to gain access to premium blog post contents and if you are not subscribed but registered, you will only get access to regular blog post contents. I've been able to integrate payment api and also the payment is working, i've also been able to save the payment details on a table in my database. What i need now is how do i filter the user based on their subscription status to serve them the premium or regular contents.Below is my Models and Views. # In models.py class User(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) username = models.CharField(max_length=200, unique=True, blank=True) email = models.EmailField(max_length=200, unique=True, blank=False) first_name = models.CharField(max_length=200, blank=True) last_name = models.CharField(max_length=200, blank=True) phone_no = models.CharField(max_length=11,validators=[MaxLengthValidator(11)]) profile_picture = models.ImageField(upload_to="images/profile_image",default="default_user_image.jpeg", blank=True, null=True) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = UserManager() EMAIL_FIELD = 'email' USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email',] def __str__(self): return self.username def get_absolute_url(self): return reverse("admin-update-user", kwargs={"pk": self.pk}) class … -
Angular to Django: Unable to upload a file - file is blank
I am creating a File Upload feature in my application where the user has to upload an excel file along with a date (using a date picker). The user then clicks upload and this calls a view in Django which runs a python class that uploads the data onto an oracle database using SQLAlchemy. I have hit an issue where I don't know how to successfully pass through a file in my service call. In the example below, I have assigned the file to the variable fileToUpload but when this is called in the upload service and assigned in a dictionary, the value of that becomes empty. Please see code below: views.py @api_view(('POST',)) @csrf_exempt def uploader(request): if request.method == 'POST': try: instance= uploader(request.data['data'], request.data['selectedDate']) _ = upload_instance.run_upload_process('data') upload_message = "Success" return Response(upload_message, status=status.HTTP_201_CREATED) except Exception as e: upload_message = 'Error: ' + str(e) return Response(upload_message, status=status.HTTP_400_BAD_REQUEST) file-upload.service.ts DJANGO_SERVER: string = "http://127.0.0.1:8000"; constructor(private http:HttpClient) { } public upload(data: any, selectedDate:any) { let postData = { data, selectedDate }; return this.http.post<any>(`${this.DJANGO_SERVER}/upload/`, postData); } upload.component.ts onChange(event: any) { this.filetoUpload = event.target.files[0]; } inputEvent(event:any) { this.monthEndDate = event.value; } onUpload() { this.loading = !this.loading; this.fileUploadService.upload(this.filetoUpload, this.monthEndDate).subscribe( (event: any) => { if (typeof (event) === … -
How to create a for loop based lightbox gallery with django
(Newbie Django dev here, with no Javascript knowledge) I'm building a Django website designed to display one page for each notice in the db. Some images can be attached to the notices: sometimes none, sometimes a few, up to maximum a dozen. I'd like to display these images on top of the detail.html page, following the example shown here: https://www.w3schools.com/howto/howto_js_lightbox.asp I understood that I need to adapt the code to use a for loop. I did my best to adapt it but I'm stuck with a non working gallery. Here is my code right now, adapted from the tutorial: detail.html <div id="illustrations" class="galerie"> {% for image in object.illustration_objet_archi.all %} <div class="row"> <div class="column"> <img src="{{ image.image_thumbnail.url }}" onclick="openModal();currentSlide({{ forloop.counter }})" class="hover-shadow"> </div> </div> <!-- The Modal/Lightbox --> <div id="myModal" class="modal"> <span class="close cursor" onclick="closeModal()">&times;</span> <div class="modal-content"> <div class="mySlides"> <div class="numbertext"> {{ forloop.counter }} / {{ image.image.count }} </div> <img src="{{ image.image.url }}" style="width:100%"> </div> <!-- Next/previous controls --> <a class="prev" onclick="plusSlides(-1)">&#10094;</a> <a class="next" onclick="plusSlides(1)">&#10095;</a> <!-- Caption text --> <div class="caption-container"> <p id="caption">{{ image.legende }}</p> </div> <!-- Thumbnail image controls --> <div class="column"> <img class="demo" src="{{ image.image.url }}" onclick="currentSlide({{ forloop.counter }})"> </div> </div> </div> {% endfor %} </div> style.css (the body … -
Not Found error after logging in with google using django-allauth
I am using django-allauth package and google provider for authentication in my django project. Everything worked fine in development however when I launched my project on the server, I got an error. When I press the "Log in with Google" button in my sign in page, I get redirected to the page where google asks me to choose my Google account to continue with. Then after this step, where I get redirected to my site, I'm encountered with a Not Found error. I tried a bunch of stuff found online but they didn't work. here is my Google credentials authorized redirect URIs. In my settings.py file I configured allauth as below: # Django-allauth configs AUTH_USER_MODEL = 'accounts.User' AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ] SITE_ID = 1 ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_SIGNUP_REDIRECT_URL = 'accounts:create_profile_url' ACCOUNT_EMAIL_VERIFICATION = 'none' LOGIN_REDIRECT_URL = 'dashboard_url' ACCOUNT_FORMS = { 'login': 'accounts.forms.CustomLoginForm', 'signup': 'accounts.forms.CustomSignupForm', 'change_password': 'accounts.forms.CustomChangePasswordForm', } ACCOUNT_DEFAULT_HTTP_PROTOCOL='https' and I've added 'allauth.urls' in my urlpatterns too urlpatterns = [ ... path('accounts/', include('allauth.urls')), ... ] I … -
Django - filter queryset until Sum is reached
Let's imagine a model called Roll. It stores the outcome of rolling a six-sided die (D6): class Roll(models.Model): outcome = models.PositiveSmallIntegerField('Roll', null=False, blank=False, default=1) There are many rolls, for example: print(list(Roll.objects.all().values_list('outcome', flat=True))) >>> [1, 5, 6, 3, 5, 4, 4, 3, 2] Now, how should I go about to get the latest N rows whose Sum('outcome') reaches an arbitrary amount, without looping in some way or another, until that amount is reached? If we imagine the rolls: pk | outcome | (accumulated sum) 1 | 3 | 3 2 | 2 | 5 3 | 6 | 11 4 | 1 | 12 5 | 5 | 17 6 | 4 | 21 7 | 3 | 24 8 | 4 | 29 9 | 5 | 34 10 | 1 | 35 and the arbitrary amount 20, then the query should pick the pk 6 as the accumulated sum has now reached the amount needed. Could something similar to the below work?: amount = 100 Roll.objects.annotate( accumulated_sum=Subquery( Roll.objects.filter( pk__lt=OuterRef('pk') ).values('pk').order_by('pk').annotate( sum=Sum('outcome', distinct=True) ).values( 'sum' )[:1] ) ).filter( sum_before__gte=amount ) -
Django: get attributes values
I want to get all attributes values, but unfortunately , I got only one which is getting from self.name My models.py class Container(models.Model): number = models.CharField(max_length=13) # Example: MSKU 907032-3 iso_type = models.ForeignKey(Container_type, on_delete=models.CASCADE, null=True) weight = models.PositiveSmallIntegerField(null=True) terminal = models.ForeignKey(Terminal, on_delete=models.CASCADE, null=True) arive_time_to_terminal = models.DateTimeField() port = models.ForeignKey(Port, on_delete=models.CASCADE, null=True) CY = models.DateTimeField() ETD = models.DateTimeField() status = models.ForeignKey(Status, on_delete=models.CASCADE, null=True) order_added = models.DateTimeField() # Change ALL null=False exception STATUS, time = DateTimeField def __str__(self): return self.number Views.py def terminal(request,id): terminal = Terminal.objects.get(name=id) container = Container.objects.all() #terminal_id=1 return render(request, 'main/terminal.html', {'title': 'Terminal', 'terminal': terminal, 'number':container }) and template is: {{ weight }} {{ terminal }} {{ arive_time_to_terminal }} {{ Container.port }} {{ CY }} {{ ETD }} Many Thanks -
Docker Django + Nginx use hostnames
I've createda a docker-compose configuration with one container for Django and another one for Ngnix, but accessing Nginx as client result in: HTTP_HOST header: 'container_name.network_name:port'. The domain name provided is not valid according to RFC 1034/1035. location / { proxy_pass http://container_name.network_name:port; This means that the Nginx proxy reach the remote address of the django container but even if I add only for test purpose ALLOWED_HOST=['*'] to django it still goes to this error. Is there a way to use the container_name.network_name syntax? -
django - how to sum values of the same key?
I want to sum the value of the count key if the values of year_taken have duplicates, how can I do that? so the output would look like this {'year_taken': '2019-2020', 'count': 1}, {'year_taken': '2021-2022', 'count': 3} -
How do I selectively mark books read by a user in the frontend if I have a common dataset of books and a dataset of the particular books read?
I have a "Books" model in django which stores information like the name, author etc (irrelevant here, just mentioning for some context). I display all that information using a Paginator and each user has the option of marking the books he/she has read. To mark them, what I can think of doing is creating another model called "BookStatus" where I insert new entries every time a user reads a book. However, I'm unable to figure out how to actually display that the user has read some particular book next to the book's name while displaying it in the frontend. What would be the easiest way to accomplish this? In short, I have a database of books which are common to all users. For each user I want to store the books he/she has read and while displaying those common books I want to be able to mark them as read/unread on the frontend. -
Django profile model
I am beginner on django and trying to create a profile model that interrelate "User" built-in model via One-To-One relation field, it results impossible to span the user model properties by profile model instance and vise versa. Can someone help me. models.py from django.db import models from django.contrib.auth.models import User class Profile(models.Model): users=models.OneToOneField(User, on_delete=models.CASCADE) image=models.ImageField(default='profilepic.jpg',upload_to='profile_pictures') location=models.CharField(max_length=100) def __str__(self): return self.users.username profileTemplate.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Profile</title> </head> <body> <h2>{{user.username}}</h2> <img src='{{user.Profile.image}}'> </body> </html> -
Unable to server static files Django S3
I'm trying to put static files to S3, and here's what I have so far in settings.py: # AWS S3 Static Files Configuration AWS_ACCESS_KEY_ID = config('AWS_S3_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_S3_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_S3_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = 'public-read' AWS_LOCATION = 'static' AWS_DEFAULT_ACL = None STATICFILES_DIRS = [ 'pakcage404/static', ] STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_REGION_NAME = 'ca-central-1' AWS_S3_USE_SSL = False AWS_S3_ENDPOINT_URL = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.ca-central-1.amazonaws.com" AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.ca-central-1.amazonaws.com/{AWS_STORAGE_BUCKET_NAME}" But when I try to access one of the static files I have uploaded, I was given this error message on the browser: <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>some request ID</RequestId> <HostId>some ID</HostId> </Error> -
How to annotate related table in django?
I have two entities Task and Technology. Technology table has a FK to Task and each task has 9 technologies. enabled category frequency c1 c2 c3 note True 3G 2100 11/03/2010 foo False 4G 700 02/04/2012 bam False 4G 1800 spam True 4G 2100 bim True 4G 2600 bum True 5G 700 tan False 5G 3700 tan True 5G 26000 tan For each tasks I need to annotate a cell of this technology matrix. This means annotate something like: candidates_technologies__3G_2100_enabled candidates_technologies__3G_2100_c1 candidates_technologies__3G_2100_c2 candidates_technologies__3G_2100_c3 candidates_technologies__3G_2100_note candidates_technologies__4G_700_enabled candidates_technologies__4G_700_c1 candidates_technologies__4G_700_c2 candidates_technologies__4G_700_c3 candidates_technologies__4G_700_note candidates_technologies__4G_1800_enabled candidates_technologies__4G_1800_c1 candidates_technologies__4G_1800_c2 candidates_technologies__4G_1800_c3 candidates_technologies__4G_1800_note ... Where candidates_technologies is the related name. Currently this is my solution, but is killing the performance. from django.db.models import Q, F, Value, Case, When, DateField, BooleanField, CharField bool_cols, text_cols = ["enabled"], ["onair_note"] date_cols = [t for t in TECHNOLOGY_COLUMNS if t not in text_cols or t not in bool_cols] columns = date_cols + bool_cols + date_cols def _get_output_field(col): if col in bool_cols: return False, BooleanField() elif col in text_cols: return "", CharField() else: return None, DateField() tech_annotations, whens = {}, [] for category, frequency in TECHNOLOGY_FREQUENCY_LIST: for column in columns: out = _get_output_field(column) key = '_'.join([category, frequency, column]) value = ExpressionWrapper( Case( When( Q(**{'candidates_technologies__category': category}) … -
Change background color in a select option dropdown
I'm rendering a form using django. One of the fields in the form is a select with options. Rendering form field: {{ form.work }} The select options after rendering are: <select name="work" class="form-control" required="" id="id_work"> <option value="" selected="">---------</option> <option value="chair">The chair</option> <option value="table">The table</option> </select> How can i change the background color for each of the values? So when i press the dropdown arrow to see all values with different colors. I used css with no success. select option[value="chair"] { background-color: red !important; } select option:nth-child(2) { background: red; } As a note, the form consists of different fields with select options. I use bootstrap 4. Thank you -
I am getting 'BasePermissionMetaclass' object is not iterable when trying to access the api
I am trying to access the api i made but i keep getting this 'BasePermissionMetaclass' object is not iterable error views.py class BlogPostListView(ListAPIView): queryset = BlogPost.objects.order_by('-date_created') serializer_class = BlogPostSerializer Lookup_field = 'slug' permission_classes = (permissions.AllowAny, ) class BlogPostDetailView(RetrieveAPIView): queryset = BlogPost.objects.order_by('-date_created') serializer_class = BlogPostSerializer Lookup_field = 'slug' permission_classes = (permissions.AllowAny, ) class BlogPostFeaturedView(ListAPIView): queryset = BlogPost.objects.all().filter(featured = True) serializer_class = BlogPostSerializer Lookup_field = 'slug' permission_classes = (permissions.AllowAny, ) class BlogPostCategoryView(APIView): serializer_class = BlogPostSerializer permission_classes = (permissions.AllowAny, ) def post(self, request, format=None): data = self.request.data category = data['category'] queryset = BlogPost.objects.order_by('-date_created').filter(category__iexact = category) serializer = BlogPostSerializer(queryset, many=True) return Response(serializer.data) In settings.py i have : REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] } I havetried everything i can think of but not been able to fix it -
How to update stock through purchase and sale in Django?
I am working on a Django Billing Webapp/Invoicing Webapp. I'm having a problem updating stocks through Purchase and Sales. I want the medicine quantity to increase when there is a purchase and decrease when there is a sale. But after a lot of tries, I cannot achieve it. Please help me to integrate this feature into my Django WebApp. Here are the contents of the files: Models.py from django.db import models from django.utils import timezone from django.shortcuts import render, get_object_or_404 #------------------------Medicine models---------------------------------- gst = ( (0, '0%'), (5, '5%'), (12, '12%'), (18, '18%'), ) # Create your models here. class Medicines(models.Model): Med_HSN = models.IntegerField(default=0) Med_name = models.CharField(max_length=20) Med_Quantity = models.IntegerField(default=0) Med_Manufacturer = models.CharField(blank=True,max_length=50) Med_Expiry = models.CharField(default=1,max_length=10) Med_Batch_no = models.CharField(blank=True,max_length=15) Med_MRP = models.FloatField(blank=False) Med_Rate = models.FloatField(blank=False) Med_GST = models.IntegerField(default=0,choices=gst) date_created = models.DateField(default=timezone.now) def caluclate_value(self): value = self.Med_MRP * (self.Med_GST/100) total_value = self.Med_MRP + value return total_value def get_cost(self): return self.caluclate_value() * self.Med_Quantity def __str__(self): return self.Med_name + " : " + str(self.caluclate_value()) # def caluclate_stock(self): # med_quantity = self(request=self.request).Med_Quantity # get_med_1_quantity = Purchase.med_quantity_1 # value = med_quantity + get_med_1_quantity # print(value) # return value #----------------------------------End Medicines Models-------------------------------------- #---------------------------------Sales Models-------------------------------- from django.core.checks import messages from django.db import models from Customer.models import Customer … -
Expire/Invalidate Session from all browsers except current
I have a django application that is using cookie-based sessions. I have a use-case where, after user changes the password, I update the session using update_session_auth_hash(request, request.user). The problem is when I have logged in from 2 different browsers and I update the password from one browser, it automatically updates the session in other browser. What I want is that, when I change the password in one browser, it should update the session on that browser only and remove/invalidate session from all other browsers. -
Django rest Framework error messages. Does not work
I am new to Django and I am working on a small project, I want an error message to be shown if the user let the field empty. the code that I wrote is not working. Can anyone help me ? def validate_name(school: School): if school.name is None: raise APIException(detail='Name is mandatory.') class SchoolService(object): @staticmethod def validate_create(school: School): validate_name(school) -
Cannot access local django webserver
I cannot seem to figure out why I cannot access my local django webserver from an outside device. I suspect it has to do with port forwarding but none of my attempts to solve it seem to work. I started by following the suggestions posted here How to access the local Django webserver from outside world by launching the server using python manage.py runserver 0.0.0.0:8000 and by entering <my-ip-address>:<port> in my external device' browser. This did not work, so I tried to explicitly make sure port forwarding was enabled by adding the following lines to iptables. iptables -A INPUT -p tcp --dport 8000 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT iptables -A OUTPUT -p tcp --sport 8000 -m conntrack --ctstate ESTABLISHED -j ACCEPT netfilter-persistent save Still, I'm not able to access the local webserver. No error messages show up, the browser just tells me that the address took too long to respond. I've tried to do the above but this time with port 80 and using sudo when needed without avail. In addition I've tried to use this line ALLOWED_HOSTS = ['*'] as suggested by multiple users. I've tried to investigate whether the application is really running on the indicated port … -
How to uncensor passwords in Django Admin page?
I'm creating an admin page for a Cybersecurity project. In admin page's users, a user profile should show the password in uncensored format, such as abcdefghijklmn, but it shows as abc***********. I need to uncensor it. In sqlite3, it is stored in the hashed format. -
'' takes 1 positional argument but 2 were given django
mi codigo parece funcionar, cuando pongo mal el usuario o la contraseña me funciona el mensaje de error, sin embargo cuando quiero ingresar realmente a la pagina oculta, me arroja lo siguiente: TypeError at /administracion/ingreso login_oculto() takes 1 positional argument but 2 were given Request Method: POST Request URL: http://localhost:8000/administracion/ingreso?next=/oculto Django Version: 3.2.8 Exception Type: TypeError Exception Value: login_oculto() takes 1 positional argument but 2 were given Exception Location: C:\Users\OGT\Museum\mu2\views.py, line 48, in login_oculto Python Executable: C:\Users\OGT\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.0 Python Path: ['C:\Users\OGT\Museum', 'C:\Users\OGT\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\OGT\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\OGT\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\OGT\AppData\Local\Programs\Python\Python310', 'C:\Users\OGT\AppData\Local\Programs\Python\Python310\lib\site-packages'] . . . dejo mi codigo de views, urls y html, por favor ayudenme login.html <div class="contenedor_formulario"> {% if error %} <p style="color: black;">{{ error }}</p> {% endif %} <form action="" method="POST" style="text-align: center;"> {% csrf_token %} <table class="tabla_formulario"> <form method="POST" action="{% url 'anyname' %}"></form> <input type="text" placeholder="Usuario" name="username" /> <input type="password" placeholder="contraseña" name="password" /> </table> <input class="boton_formulario" type="submit" value="Ingresar"> </form> </div> urls.py urlpatterns = [ path('administracion/ingreso', views.login_oculto, name='anyname'), path('oculto', views.oculto,name='oculto') ] views.py def login_oculto(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') usuario = authenticate(request, username = username, password = password) if usuario: login_oculto(request, usuario) return redirect('oculto') else: return render (request, 'mu2/login.html', {'error': 'usuario o contraseña incorrecta'}) return render(request, … -
Django iterate on values()
I have somethink like this: vmware = Vmware.objects.values('pk', 'hostname') the result : <QuerySet [{'pk': 1, 'hostname': 'ste1vvcsa'}, {'pk': 3, 'hostname': 'ste1vvcsatest'}]> I want to iterate on it and retreive the values of pk and hostname I have an error when I do somethink like this: for i in vwmare: print(i.hostname) Error : AttributeError: 'dict' object has no attribute 'hostname' -
Django-tables2: How can I add columns based on a queryset that can change
I have a table created in django tables2 which displays related fields of my model queryset. However there is a many-to-many field and I would like to display each object as a column. Obviously this is variable, so I can't hard code this into the table columns like I would with the other fields. One option is to put all M2M objects into the same column, but this could get quite messy (i am not envisaging this being >3 M2M links in total, so separate cols would be best). I've managed to use the init method of the table to get a new col for each link, however I'm struggling with how to actually get the data i need into it.. models: class GenomeBuild(models.Model): build_name = models.CharField(max_length=6) in_use = models.BooleanField(default=False) def __str__(self): return f"{self.build_name}" class Variant(models.Model): chromosome = models.CharField(max_length=2) genomic_location = models.CharField(max_length=50) ref = models.CharField(max_length=1024) alt = models.CharField(max_length=1024) var_type = models.CharField(max_length=60) class Meta: db_table = "variant" unique_together = ( ("chromosome", "genomic_location", "ref", "alt",),) def __str__(self): return variant_str_formatting(variant=self) @property def vNomen(self): return vNomen_str(variant=self) class VariantBuild(models.Model): variant_id = models.ForeignKey( Variant, on_delete=models.CASCADE, db_column="variant_id", related_name="variant_id" ) build_id = models.ForeignKey( GenomeBuild, on_delete=models.CASCADE, db_column="build_id", ) def __str__(self): return f"{self.variant_id} ({self.build_id})" class VariantGeneTranscript(models.Model): variant_builds = models.ManyToManyField( VariantBuild, … -
Django, SFTP storage file handling problem
I am using django-storages in my project. The use case: I upload a file from a vue app. My server side(with django rest framework) handle this request and upload the file(I want to upload images and videos, so png and mp4, mostly). My file model: from django.db import models from storages.backends.sftpstorage import SFTPStorage SFS = SFTPStorage() class File(models.Model): class Meta: verbose_name_plural = "File" name = models.CharField(max_length=255) location = models.CharField(max_length=255) uploadDate = models.DateField() comment = models.CharField(max_length=255, null=True, blank=True) connectedTo = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True) ghbwrzipgw = models.FileField( null=True, blank=True, storage=SFS) def __str__(self): return f'{self.name} (Upload Date: {self.uploadDate}, Connected To: {self.connectedTo})' My file view: from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from measurement_db.models.file import File from measurement_db.serializers.file import FileSerializer @api_view(['GET']) def FileList(request): file = File.objects.all() serializer = FileSerializer(file, many=True) return Response(serializer.data) @api_view(['GET']) def FileDetail(request, pk): file = File.objects.get(id=pk) serializer = FileSerializer(file, many=False) return Response(serializer.data) @api_view(['POST']) def FileCreate(request): serializer = FileSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['PUT']) def FileUpdate(request, pk): file = File.objects.get(id=pk) serializer = FileSerializer(instance=file, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['DELETE']) def FileDelete(request, pk): file = File.objects.get(id=pk) file.delete() return Response(status=status.HTTP_200_OK) And a snippet from my settings.py: DEFAULT_FILE_STORAGE …