Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to autofill form with url variable?
I'm trying to autofill a form in django with the url variable that I set in urls.py, but I'm not really sure how I could be able to do this, I tried to use form.instance but apparently it only works with users, so here's the code so you can check out what I'm talking about. views.py class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'app1/createpost.html' def form_valid(self, form, sym): form.instance.author = self.request.user form.instance.stock = self.request.sym return super().form_valid(form) models.py class Post(models.Model): title = models.CharField(max_length= 255) header_image = models.ImageField(null = True, blank = True, upload_to = 'images/') author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank = True, null = True) #body = models.TextField() post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default='coding') snippet = models.CharField(max_length=255) likes = models.ManyToManyField(User, related_name = 'blog_posts') stock = models.ForeignKey(StockNames, null=True, on_delete = models.CASCADE) def total_likes(self): return self.likes.count() def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('app1:article-detail', args=(self.id,)) class StockNames(models.Model): name = models.CharField(max_length=255) symbol = models.CharField(max_length=255) def __str__(self): return self.symbol urls.py urlpatterns = [ path('add_post/<str:sym>',AddPostView.as_view(), name='addpost'), ] forms.py class Meta: model = Post fields = ('title','category', 'body', 'snippet', 'header_image', 'stock') widgets = { 'title': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Title', 'length':'100px'}), #'author': forms.TextInput(attrs={'class': 'form-control', 'value': '', … -
CSRF verification failed. Request aborted. No Form
I am receiving a "CSRF verification failed. Request aborted" network error when I call my js function with ajax/jquery in it. As far as I understand, this is usually associated with forms but I don't have any forms in this piece of my code. I tried adding {% csrf_token %} to my button but that didn't do anything. I'd appreciate any help. Thanks! modCalc.html {% extends 'base.html' %} {% block title %}Modulo Calculator{% endblock %} {% block content %} {% block nav-modCalc %}<a href="#" class='active'>Modulo Calculator</a>{% endblock %} <div class='main'> {% if user.is_authenticated %} <div class='leftAndRight'> <p id='highscore' class='highscore'>Highscore: {{ user.highscore }}</p> <p id='timer' class='timer'>0:00</p> </div> <br /> <br /> <div class="center"> <p id='level' class='level'>Level 1</p> </div> <div class="center"> <button onclick='generateNums();' id='generate' class='generate'>Generate Problem</button> </div> <div class='formulaDiv'> <span class='formula'><p id='num1' class='num'></p></span> <span class='formula'><p class='symbol'>%</p></span> <span class='formula'><p id='num2' class='num'></p></span> <span class='formula'><p class='symbol'>=</p></span> <span class='formula'><input type='number' id='answer' class='answer'></input></span> </div> <p id='required' class='required'></p> <div class='center'> <button onclick='checkAnswer();' id='grade' class='grade' disabled>Grade</button> </div> <div class='leftAndRight'> <p id='results' class='results'></p> <p id='inRow' class='inRow'></p> </div> {% else %} <p>You are not logged in</p> {% endif %} </div> {% endblock %} modCalc.js ... function checkAnswer(){ if(document.getElementById('answer').value != ""){ if(num1 % num2 === parseInt(document.getElementById('answer').value)){ inRow++; if(inRow > highscore){ highscore = … -
How can I get only the hour or minute part from post request in Django?
I want to receive only the hour part or minute part in django. Right now i'm using remindTime = request.POST.get("remindTime") to get the time but I only want the hour or minute or day or month. How can I do that? here is the model class Reminder(models.Model): remindTime = models.DateTimeField(auto_now_add=False, auto_now=False) how I get the time if request.method == "POST": remindTime = request.POST.get("remindTime") Ty! -
pytest: how to avoid repetition in custom User manager testing
I'm testing a custom user manager with pytest and factory_boy. I want to test those cases where information required to create a new user is incomplete, but I have different required parameters at the moment there are 3 (email, username, identification_number) but there may be more in the future. Manager class UserManager(BaseUserManager): """ Define a manager for custom User model. """ def create_user( self, email: str, username: str, identification_number: str, password: Optional[str] = None, is_active: bool = True, is_staff: bool = False, is_admin: bool = False, ) -> User: """ Creates and saves a User. """ if not email: raise ValueError(_("Users must have an email address.")) if not username: raise ValueError(_("Users must have a username.")) if not identification_number: raise ValueError(_("Users must have an identification number.")) user = self.model(email=self.normalize_email(email)) user.set_password(password) user.username = username user.identification_number = identification_number user.active = is_active user.staff = is_staff user.admin = is_admin user.save(using=self._db) return user Tests import pytest from django.contrib.auth import get_user_model from my_app.users.tests.factories import UserFactory pytestmark = pytest.mark.django_db class TestsUsersManagers: def test_user_with_no_email(self): proto_user = UserFactory.build() # User created with factory boy User = get_user_model() with pytest.raises(TypeError): User.objects.create_user() with pytest.raises(TypeError): User.objects.create_user( username=proto_user.username, identification_number=proto_user.identification_number, password=proto_user._password, ) with pytest.raises(ValueError): User.objects.create_user( email="", username=proto_user.username, identification_number=proto_user.identification_number, password=proto_user._password, ) def test_user_with_no_username(self): proto_user = UserFactory.build() … -
Retrieve objects from one model according multiple field values in Django
What I have In my application I have a model called cases, which has three fields fulfilled, caducity and prescription; Which are used to keep deadlines for the case. It should be stressed that the three dates may seem at first sight to be the same but they are different terms used in the law. I need to retrieve those cases whose fields fulfilled, caducity and prescription values match a specific date. class Case(TimeStampedModel, models.Model): """Representation of a legal case.""" fulfillment = models.DateField( verbose_name=_("Fulfillment"), default=date.today, help_text=_("Select the case fulfillment date."), ) caducity = models.DateField( verbose_name=_("Caducity"), default=date.today, help_text=_("Select the case caducity date."), ) prescription = models.DateField( verbose_name=_("Prescription"), default=date.today, help_text=_("Select the case prescription date."), ) My solution Create a custom manager in which I can filter those cases that match a specific date. from datetime import date, timedelta TODAY = date.today() YESTERDAY = TODAY - timedelta(days=1) class CaseManager(models.Manager): """Define a manager for Case model.""" def all_expired(self) -> "QuerySet[Case]": """Get all fulfilled, caducated and prescribed cases.""" return self.get_queryset().filter( Q(fulfillment__range=[YESTERDAY, TODAY]) | Q(caducity__range=[YESTERDAY, TODAY]) | Q(prescription__range=[YESTERDAY, TODAY]) ) class Case(TimeStampedModel, models.Model): """Representation of a legal case.""" # ...fields objects = CaseManager() Then I can retrieve those cases whose expiration date is the same as … -
Generic detail view Index must be called with either an object pk or a slug in the URLconf
I am trying to have one form and one modelin one view which is working. But when I am trying to save the form I am getting the error message: Generic detail view Index must be called with either an object pk or a slug in the URLconf. Here are my views nad urls: class Index(generic.CreateView): template_name='home.html' form_class=DistributionForm models=Lecturer queryset = Lecturer.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context ['lecturer_list'] = Lecturer.objects.order_by('lecturer') return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) urls.py from django.urls import path from . import views from django.conf.urls.static import static from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns app_name='distribution' urlpatterns=[ path('',views.Index.as_view(),name='home'), path('hocalar/<slug:slug>/',views.LecturerDistribution.as_view(),name='lecturer_distribution'), path('dersler/<slug:slug>/',views.LectureDistribution.as_view(),name='lecture_distribution'), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Thank You in Advance -
Django - Google Drive API how to store and retrieve file using Django
I have a requirement of uploading and downloading image files in google drive via web application built using Django. I have explored using Django Google Drive Storage API, it seems to be working while saving files. But I have no clue where the files are getting saved and how to read the files. if anyone has experience using Django google drive API or have a recommendation for storing files in google drive would highly be helpful at this moment. Thank you. -
Page not found (404) Django error -after working fine "No User matches the given query"
I'm working with Django framework and after have my code running fine. I logged a user out and when I refreshed the browser I got "Page not found (404)" error. It seems to me that the get_object_or_404 method in views.py is looking for a reference to a user that doesn't exist. How can I fix this, should I change the schema of my DB of just use a different method to get User? models.py class User(AbstractUser): pass class PostSerializer(models.Manager): def get_posts(self, *args, **kwargs): return self.all() def get_post(self, post_id, *args, **kwargs): return get_object_or_404(self, id=post_id) def get_user_posts(self, username, *args, **kwargs): return self.filter(username=username) def get_user_post(self, post_id, user, *args, **kwargs): return get_object_or_404(self, pk=post_id, username=user) class Post(models.Model): username = models.ForeignKey( "User", default=1, on_delete=models.CASCADE, related_name="posts") content = models.TextField(blank=True) timestamp = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField( 'User', default=None, blank=True, related_name='likes') objects = PostSerializer() def serialize(self): return { "id": self.id, "username": self.username, "content": self.content, "timestamp": self.timestamp.strftime("%b %-d %Y, %-I:%M %p"), "likes": self.likes } @property def count_likes(self): return self.likes.all().count() def __str__(self, *args, **kwargs): return self.content LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike'), ) class Like(models.Model): user = models.ForeignKey('User', on_delete=models.CASCADE) userpost = models.ForeignKey('Post', on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default=' Like ', max_length=10) def _str_(self): return str(self.userpost) class Follow(models.Model): following = models.ForeignKey( 'User', … -
bootstrap 4 nested column not stacking
new to bootstrap and experimenting on a pet project. am a bit at my wits ends here. my understanding is if you have <div class="col-sm-12 col-lg-5"> and <div class="col-sm-12 col-lg-7 "> on small screen each would take a new row (12 cols). vs on a large screen they'd share the row (5+7). in my code the second table(fruits) is supposed to share row with the chart on large screens and split on small screen but when I try small screens in debugging mode, the second column with the chart gets pushed out of the parent column (off screen). I have no clue what exactly is wrong here. any help would be appreciated bellow is a portion of the code <div class="container"> <div class="row"> <div class="media content-section col-sm-12 col-md-12 col-lg-12"> <form action="" method="post"> {% csrf_token %} <label class="switch" ><input type="checkbox" id="togBtn" /> <div class="slider round"> <!--ADDED HTML --><span class="on">BUY</span ><span class="off">SELL</span ><!--END--> </div></label > <div class="table-responsive-md"> <table class="table table-sm table-bordered tableformat"> <thead> SUMMARY <small class="text-muted" >(edit cells to adjust position)</small > <tr> <th scope="col">col 1</th> <th scope="col">col 2</th> <th scope="col">col 3</th> <th scope="col">col 4</th> <th scope="col">col 5</th> <th scope="col">col 6</th> <th scope="col">col 7</th> <th scope="col">col 8</th> <th scope="col">col 9</th> </tr> </thead> … -
Failed to Load Resource In Production but Not Locally
I am working on a Django project and I have it deployed on pythonanywhere.com. In my project, I am using Django Jsignature which works fine on my local machine. In production, however, when I load the particular template, I get this error in my console - 'myurl' portion is not the real url. https://myurl.com/static/js/jSignature.min.js net::ERR_ABORTED 404 (Not Found)``` So I don't get this locally, but do in Production. Can anyone suggest for me where to start on this? I'm not even really sure where to begin, it's my first time deploying anything. -
Permission denied: - Save File Django
Dears, I'm trying to save a file on the server using pdfformfill. When I'm using server Django, I don't have any problem, but, when I'm using the production environment, I have this error: Environment: Request Method: POST Request URL: xxxxxx Django Version: 2.1.15 Python Version: 3.8.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap4', 'bootstrap_datepicker_plus', 'easy_pdf', 'Home'] Installed 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'] Traceback: File "/home/ascende/Ascende/env/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/ascende/Ascende/env/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/home/ascende/Ascende/env/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ascende/Ascende/env/lib/python3.8/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "/home/ascende/Ascende/Site/Home/views.py" in fundiarioContagem 435. pdformfill.fill_pdf(fields, '/home/ascende/Ascende/Site/media/PDF/PMC06/PMC06.pdf', '/home/ascende/Ascende/Site/media/PDF/PMC06/CON_' + imprime.SeloChave + '.pdf') File "/home/ascende/Ascende/env/lib/python3.8/site-packages/pdformfill/__init__.py" in fill_pdf 13. with open(fdf_file_name, "wb") as fdf_file: Exception Type: PermissionError at /projetos/contagem/questionarios/fundiario/0100100100001 Exception Value: [Errno 13] Permission denied: '3b7d6e83-a2f6-4664-bae0-f812c1391502' I change the owner of my project to the user www-data, but I have the same problem. Can you help-me to solve this problem?? Best Regards, -
Beginner Django: Python ImportError and ModuleNotFoundError
im practising using Django/Python to make a blog. It has been going well but got stuck recently with Two errors, the first has gone now but comes back when I move things around. the second is the current error with the current state. djangogirls/mysite/urls.py", line 3, in from . import views ImportError: cannot import name 'views' from 'mysite' current error: djangogirls/blog/views.py", line 4, in from forms import PostForm ModuleNotFoundError: No module named 'forms' Here are some of my files: views.py from django.shortcuts import render from django.utils import timezone from .models import Post from django.shortcuts import render, get_object_or_404 # Create your views here. def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.post_list, name='post_list'), path('post/<int:pk>/', views.post_detail, name='post_detail'), path('post/new/', views.post_new, name='post_new'), ] forms.py from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'text',) Not completely sure about the structures yet (very beginner), so any advice would be so appreciated -
Integrating jquery ajax in TWO Django views
I am trying to call ViewTwo() from a template under ViewOne(). However, I got a NOT FOUND url when the ajax is called. Problem: With url in jquery code LINE 4, throws NOT FOUND: /pathx/forView2/45 ^ when I change the url to pathx/forView2/45, NOTE: the leading slash is removed it throws NOT FOUND: /pathx/forView1/45/pathx/forView2/45 Jquery code $(document).ready(function(){ var id_number =$("#someID").text(); $("#btnSelect").click(function(){ var url = '/pathx/forView2/0'.replace(0,id_number); //Set the var url string $.ajax({ url: url, method: 'GET', data: { project_id: id_number, }, success: function(response){ $("#id_some_element").text(response.some_data); } }); }); }); URL path('pathx/forView1/<int:pk>/', views.ViewOne, name='viewOne'), path('pathx/forView2/<int:pk>/', views.ViewTwo, name='viewTwo'), viewOne Code: def viewOne(request, *args, **kwargs): ... return render(request, 'someFolder/someTemplate.html', {'prediction_model': formModel}) viewTwo Code: def viewTwo(request, *args, **kwargs): ... if request.method == 'GET' and request.is_ajax(): data = { 'some_data': 'some data' } return JsonResponse(data, status = 200) ... return render(request, 'someFolder/someTemplate.html', {'xdata': xdata}) -
how to accept qoutes in string value in csv to django
So I'm wondering what is the way to pass single/double qoute in the string value in csv file uploaded in Django. I have this problem when I got the error: DataError at /path/ (1406, "Data too long for column 'height' at row 1") Case there are some data that looks like this: 5'7"1/2 in the excel so when I remove those qoute it works fine. what I want is that user can put those qoutes in the excel whatever they want. -
Where can I find the Django database cache? Reference tables searching for CharField as ForeignKey
I'm constructing a database in Django with seven tables. Six of the tables reference the first table (PrimaryKey table) for their ForeignKey field. The PrimaryKey table has seven fields, including the 'id' AutoField. The six ForeignKey tables continually reference a CharField as the PrimaryKey, while I need them to reference the AutoField. (Not sure why this happened in the first place, but that's not the question). I have deleted the database, cleared the caches, restructured the models, etc. etc., but the six reference tables still look for this CharField as the PrimaryKey. My only thought is that there's a database cache somewhere that I can't find, any ideas on where to find it? Or, if you think a hidden cache is not problem, let me know. Thanks. -
Django Form ForeignKey plain text widget (get label, not value)
I'm using a custom PlainTextWidget to show the value of form fields in a form (similar to Django's admin read-only display). This works great, however it fails for ForeignKey fields (and Boolean), or basically anything with a value/label setup. I've found a few solutions online, but most involve creating a separate widget for each foreignkey model and using that, which is a pretty ugly solution. Does anyone have any better ideas as to how to get the label for a given value in a simple widget for the ChoiceField based form fields? The goal would be to have the PlainTextWidget return the label field that gets displayed by the templates in the default widgets. Thanks -
Heroku error: bash: web:: command not found
so today my heroku website was working fine but then I had to make lots of changes to the file and I definitely did something to it because now it doesn't work anymore. I don't know what could've changed the configuration but here are my settings: import os import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'secretkeyhere' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', '.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'core', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] ROOT_URLCONF = 'mysite.urls' 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', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'djangogirls', 'USER': 'name', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '', } } db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': … -
Django how to display the value of user's input
I want to display a value that user types I am able to get the value using this lines: def on_submit_click(req): name = req.GET['search'] return render(req, 'search_test.html') But i'm not quite sure how to display it on the website I tried doing this in the search_test.html: <h1 class="text-white text-center">{{ name }}</h1> But it didn't work either. -
AJAX request is not refreshing <select> when <select> is modified by multi.js library
I have a Django form with a multi-select on it. I am using the multi.js library to modify the look & feel of the multi-select. I am also using the Django Bootstrap Modal Forms package to be able to add new options to my select list without leaving/refreshing the page. Currently, when I add a new item via the modal form, it is added in the back-end, but the multi-select does not get updated from the JsonResponse. If I remove the code that applies the multi.js functionality to the multi-select, then it is refreshed properly when the modal window closes. As per this issue in GitHub, I thought I might just have to trigger the change function for the select element, but that doesn't seem to work for me. I've tried adding $select.trigger( 'change' ); to the last line of the createQuestionModalForm function, but even though that is hit in the debugger after submitting the modal, it doesn't seem to do anything. Here's the relevant JS: $('#id_questions').multi(); $(function () { function createQuestionModalForm() { $("#addQuestion").modalForm({ formURL: "{% url 'question_create' %}", asyncUpdate: true, asyncSettings: { closeOnSubmit: true, successMessage: "test", dataUrl: "/projects/question_update", dataElementId: "#id_questions", dataKey: "question_select", addModalFormFunction: createQuestionModalForm } }); } createQuestionModalForm(); }); … -
on opening filefield(contains mp4 video) url , it denies access to it. but only videos not other types like image
my get request in django rest framework returns a url which containes a file(mp4 video) but when i open the url it deny access .but only files which have videos not other types like image or any file(my api is deployed on cpanel host) . but why? how can i fix it?) here is my code: models.py class Videos(models.Model): title = models.CharField(max_length=100, null=True) video = models.FileField(upload_to='videos', null=True) i created a filefield here and i uploaded a video with mp4 format in django admin serializers.py class VideosSerializer(serializers.ModelSerializer): class Meta: model = Videos fields = ('id', 'title', 'video') and this is my views: views.py from rest_framework.generics import ListAPIView from rest_framework.permissions import AllowAny from .serializers import VideosSerializer from .models import Videos class VideosView(ListAPIView): permission_classes = (AllowAny,) serializer_class = VideosSerializer queryset = Videos.objects.all() and in the end urls urlpatterns = [ path('videos', VideosView.as_view(), name='videos') ] when i call the request it gives me the url and it works fine . but when i open the url link it denies access with a 403 forbbiden error and i didn't use any authentication or user . cause i just want to give the url.i don't need authentcation classes . as i told before this happens on … -
How to achieve the Spotify API's authorization code flow with Django and React/Redux?
I have a React/Redux/Django app that I want to integrate with Spotify. Specifically I want to give my app access to the user's playlists and also change the playback in the user's Spotify app or embedded player. I imagine this would be enabled by a "connect to Spotify" button somewhere on the user's profile page, which begins the Authorization flow as stated by the Spotify API. However, I have no idea how I would even begin this process. I tried an axios request as seen in some tutorials, but that just gave me CORS errors. Then I tried a plain old link and now there's a code in my url bar that I have no idea what to do with. Has anyone implemented something similar that I can take a look at or have any advice? Note that I have already done my googling and read all the medium articles, please do not share those with me. -
Unable to find/ import .py file in the same directory Visual Studio Code
I have been all over the internet and spent hours trying to fix this. It may be something pretty straight forward so please cut me some slack. This is my first time using Visual Studio Code. I have already tried the solutions presented in the links below: VS Code - pylinter cannot find module vscode import error for python module Can't get VSCode/Python debugger to find my project modules https://code.visualstudio.com/docs/python/environments My folder structure looks like this: I am trying to run the urls.py file which tries to import the views file using- from . import views But I get the following error: Traceback (most recent call last): File "c:/Users/abc/projects/telusko/calc/urls.py", line 7, in from . import views ImportError: cannot import name 'views' I have tried all possible combinations, and currently my launch.json file looks like this: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Current File", "type": "python", "request": "launch", "program": "${file}", "console": "integratedTerminal" }], "env": {"PYTHONPATH": "c:/Users/abc/projects/telusko/test/Scripts/python.exe"}, "python.pythonPath": "c:/Users/abc/projects/telusko/test/Scripts/python.exe" } I am using a virtual env to run this project, the env is located at - "c:/Users/abc/projects/telusko/test/" And … -
<audio></audio> tag displays error in Safari and doesn't allow skip in Google-Chrome
I'm using a Django based web application that plays music from a database using the tag in HTML5. This has worked successfully on Firefox, but plays on Google Chrome without allowing any ability to skip through the song, and does not allow any play whatsoever on Safari. Anytime I try, I receive the error below from the audio section. Image from website loaded on safari <div id="beat{{forloop.counter}}"> <img class="image" src="{{beat.artwork.url}}" style="width:100%;" alt="Card image"/> <div class="middle" style="height:100%; top:50%"> <p class="text-white font-weight-bold" style="margin-bottom:0%;">{{beat}}</p> <p class="text-white" style="margin-bottom:0%;">The Island Prince</p> <div style="margin-top:0%; margin-bottom:0%; margin-left:5%; width:90%;"> <audio controls src="{{beat.beatFile.url}}" type="audio/mpeg" style="width:100%;"></audio> </div> <p class="text-white" style="text-align:left; margin-bottom:0%;"> Tags: {% for tag in beat.tag.all %} {{tag}} {% endfor %} </p> <p class="text-white font-weight-bold" style="text-align:center;margin-bottom:0%;">Purchase Today</p> <button type="button" data-product="{{beat.id}}" data-action="add" style="padding-bottom: 10px;" class="btn-lg btn-dark btn-block update-cart">Add To Cart</button> </div> </div> -
Django: Submit button gets triggered twice
Hi, I am making currently a form where the user can edit his profile image. I am trying to delete the profile image that the user had before, after he changes his profile image to a new one. I made so far the scripts, but by the print commans I found out, my submit button(my script) get's triggered twice. Some Informations: I am using Django 3.1 - Python 3.7.2 - JS,Bootstrap from CDN html site code {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }}</p> </div> </div> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Informazioni sul profilo</legend> {{ u_form|crispy }} {{ p_form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Aggiorna</button> </div> </form> <!--form here--> </div> {% endblock content %} models.py from django.db import models from django.contrib.auth.models import User from PIL import Image, ImageChops import os import time # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='profile_pics/default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() # path = 'media/profile_pics/' media_pics = os.listdir(path) img = Image.open(self.image.path) for imgm in media_pics: … -
Time mismatching in admin section
I am buiding an app in Django, it is hosted on Heroku. It gets some data via API and then saves it into a model, with the time and date of the record. This model shows the time and date in its objects name. Last_update_time = models.DateTimeField(blank=False, null=False, default=timezone.now ) def __str__(self): return "%s --- [ %s ]" % (self.Target_area_input_data.Name, datetime.strftime(self.Last_update_time, "%H:%M:%S %d-%m-%Y") ) The information is then displayed in a template. The time displayed in the template is correct (it corresponds to the time displayed by my pc clock, 22:33 in the example), but when I access my model in Django admin, it is two hours earlier (20:33 in the example). The strange thing is that when I access the object fields view, the time is right (22:33 in the example). What could be the problem? In my settings I have: TIME_ZONE = 'Europe/Berlin' USE_TZ = True I tryed to change USE_TZ = False only resulting in the time in the object fields view being two hours earlier (20:33 in the example), like the others, and the message "you are 2 hours ahead from the server time" appearing. It seems that the problem started after I had to reset …