Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
running virtual env and installing packages in aws lightsail
I want to install a package which requires virtual environment before it can be installed properly. I have installed the project and other packages but there is a pakage which is not installing because I am not running my command from inside the virtual environment. Please how can I make use of virtualenv in django aws lightsail. Thanks -
Another "fk_name ' ' not a foreignkey to" problem [Python/Django]
please don't judge with my question. I tried every suggestion here but still no luck. here's my code --- admin.py from django.contrib import admin from .models import candidates_info, address class addressInline(admin.TabularInline): model = address fk_name = 'id' @admin.register(candidates_info) class candidates_infoAdmin(admin.ModelAdmin): fields =['last_name', 'first_name', 'middle_name', 'moniker'] inlines = [addressInline] models.py import datetime from django.db import models from django.utils import timezone class candidates_info (models.Model): last_name = models.CharField(max_length=50) first_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50) #position = models.ForeignKey('positions', db_column='position_id', on_delete=models.CASCADE, null=False) #birth_date = models.ForeignKey('birthdate', db_column='date_of_birth_id', on_delete=models.CASCADE, null=False) #contact_info = models.ForeignKey('contact_info', db_column='contact_info_id', on_delete=models.CASCADE) addr = models.ForeignKey('address', on_delete=models.SET_NULL, null=True) moniker = models.CharField(max_length=35) #party = models.ForeignKey('political_parties', db_column='political_parties_id', on_delete=models.CASCADE, null=False) registration_dt = models.DateTimeField('date registered') class address(models.Model): lot_no = models.DecimalField(max_digits=5, decimal_places=0) block_no = models.DecimalField(max_digits=5, decimal_places=0) note: the codes commented out (#) are part of my code in models.py which I temporarily disabled as part of my code to see if it's conflicting with the declaration of foreignKey. and another thing, tried declaring and undeclaring fk_name on admin.py but still no luck. Please help guys. Been stock here for a few days now. I can't seem to find the bug. TIA btw.. here's the error from console --- <class 'votenow.admin.addressInline'>: (admin.E202) fk_name 'id' is not a ForeignKey to 'votenow.candidates_info'. -
Django template language doesn't display anything
Django 3.2.9 views.py: from django.shortcuts import render # Create your views here. def index(request): context = { 'name': 'Patrick' } return render(request, 'index.html', context) index.html: <h1> Welcome {{name}} </h1> The outcome: As you can see nothing Workspace: Just in case So my question is obvious, am I missing anything? All the tutorials, the documentation, everything is just like in them, but outcome is differ -
Form wont validate, says that all fields are empty Django
In a view I have 3 forms: forms.py class PostForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(PostForm, self).__init__(*args, **kwargs) class Meta: model = Post fields = ['subtitle', 'latitude', 'longitude', 'tags', 'body'] widgets = { 'body': forms.Textarea(attrs={'class': 'log-body editable'}), 'tags': forms.TextInput(attrs={'id': 'tags-field', 'class': 'log-form-field'}), 'latitude': forms.TextInput(attrs={'id': 'latitude-field', 'class': 'log-form-field'}), 'longitude': forms.TextInput(attrs={'id': 'longitude-field', 'class': 'log-form-field'}), 'subtitle': forms.TextInput(attrs={'id': 'subtitle-field', 'class': 'log-form-field'}), } labels = { 'subtitle': 'Subtitle:', 'tags': 'Tags:', 'latitude': 'Latitude', 'longitude': 'Longitude', 'body': '' } class ImageForm(forms.ModelForm): images = forms.ImageField(label='Images', widget=forms.ClearableFileInput( attrs={ 'multiple': True, 'class': 'file-upload', 'id': 'file-upload-button-image', 'name': 'images'} ) ) class Meta: model = PostImage fields = ('images',) class VideoForm(forms.ModelForm): videos = forms.FileField(label='Videos', widget=forms.ClearableFileInput( attrs={ 'multiple': True, 'class': 'file-upload', 'id': 'file-upload-button-video', 'name': 'images' } ) ) class Meta: model = PostVideo fields = ('videos',) And I have a template that creates a post and stores the videos and pictures and that works great. Where I'm having a hard time is updating a 'Post'. class PostEditView(TemplateView): template_name = 'Logging/edit view.html' post_form_class = PostForm image_form_class = ImageForm video_form_class = VideoForm def get_context_data(self, **kwargs): context = super(PostEditView, self).get_context_data(**kwargs) context['post_pk'] = self.kwargs['pk'] context['post_form'] = PostForm(instance=Post.objects.get(pk=self.kwargs['pk'])) context['image_form'] = ImageForm(empty_permitted=True, use_required_attribute=False) context['video_form'] = VideoForm(empty_permitted=True, use_required_attribute=False) context['images'] = PostImage.objects.filter(post_id=self.kwargs['pk']) context['videos'] = PostVideo.objects.filter(post_id=self.kwargs['pk']) return context def … -
Custom Auth Backend
I am looking to create a custom auth backend for my Django project using one field for private key. How to achieve that with removing the "django.contrib.auth.backends.ModelBackend" and replace it with the new auth? Simply, if private key match public key in the database, login that user, else raise error. Note, at the moment all users have public key (RSA) stored in the database, and the private key in stored in the sessions. -
Can't Download my Video via PyTube ending with mp3
Hello, does anyone know what I did wrong? Or why my video is downloaded in mp4 but NOT in mp3? def converter(request): if request.method == 'POST': link = request.POST['link'] video = YouTube(link) format = request.POST['format'] if format == "3": stream = video.streams.get_audio_only() download_folder = os.path.expanduser("~")+"/Downloads/" stream.download(download_folder) os.rename(stream.download + ".mp3") elif format == "4": stream = video.streams.get_highest_resolution() download_folder = os.path.expanduser("~")+"/Downloads/" stream.download(download_folder) return render(request, 'home/videoconverter.html',) -
request.get: Temporary failure in name resolution. Cannot use Session()
Inside of a Django web app, I synchronously call an external API using requests. request(url=api_url, method="GET") This gets called roughly 1 or 2 times per minute, and can scale up to 10 times per minute. It mostly works fine, though sometimes I get this error: HTTPSConnectionPool(host='example.com', port=443): Max retries exceeded with url: /api_url/endpoint.json (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f637a4e63a0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution')) Now, I understand the correct solution would be to use Session() so that the underlying TCP connection is reused and requests doesn't have to perform a name resolution every time (which, as we've seen, could sometime fail for no avoidable reason). However, Session() would not persist once my Django app has responded to the user. The app works synchronously: I would need an external service that persists the TCP connection to external APIs, only for this purpose... that'd be madness. More simply, I'd like to cache the name resolution somewhere, potentially for days. Is this possible? I have the IP address the api_url resolves to. But I obviously can't query that directly. What's the solution here? -
Best way to declare additional data in Django project
I'm looking for the best practice in order to declare the additional data in a Django project. Imagine I need to store a huge list of choices to use in app1/models.py (I have seen a lot of best practices keep declaring those choices in the body of the models). In another scenario, Imagine I need to keep tens of config data in order to use them in my views.py. Is it common to declare them in the function/class? In my opinion, there would be two common methods in order to do that. (Not sure even recommended at all) Method #1 I can actually keep them all in my settings.py file and access them with importing (like from django.conf import settings). settings.py: ... NBA_TEAMS = ( ("red", "Bulls"), ("yellow", "Lakers"), ... ) Method #2 Keep them all in a file named data.py right next to the settings.py, and try importing it at the end of the settings file like this. settings.py ... try: from .data import NBA_TEAMS, .. except: pass Is there any best practice about this issue? Thank you. -
How to migrate from Sqlite to PostgresSQL in Django? OperationalError
I am learning to use Django through a tutorial in which we are developing a small project, i'm trying to connect a PostgresSQL database and do the migrations, but i have certain problems when doing 'python manage.py migrate' in the terminal Settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'DEMO_TEST', 'USER' : 'postgresql', 'HOST': 'localhost', 'PASSWORD':'lew123lew123', 'PORT': '5432', } } Traceback File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\django\db\backends\postgresql\base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was the direct cause of the following exception: 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 "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\django\core\management\commands\migrate.py", line 75, in handle self.check(databases=[database]) File "C:\Users\lewis\anaconda3\envs\myenv\lib\site-packages\django\core\management\base.py", line 419, … -
Force tests to fail if migrations aren't run
I'm blatantly oblivious sometimes, and it led me down a 30 minute blackhole trying to figure out why my constraints weren't being applied in my tests. Turns out I forgot to run makemigrations. Is there a way to configure pytest or django to fail without makemigrations? I know if very clearly warns me Your models have changes that are not yet reflected in a migration, and so won't be applied. Just looking for something a little more obvious/in your face? -
TypeError: expected str, bytes or os.PathLike object, not JpegImageFile (or PngImageFile)
When I am uploading a picture to check a picture according to tensorflow h5 model, I am loading image using load_model of tensorflow.keras.models but it is not accepting. For JPG, it is showing TypeError: expected str, bytes or os.PathLike object, not JpegImageFile and for PNG, it is showing as TypeError: expected str, bytes or os.PathLike object, not PngImageFile. What to do now? I tried the code with raw python but it worked nicely. Code: #views.py import numpy as np from tensorflow.keras.models import load_model from tensorflow.keras.preprocessing import image pic = request.FILES['image'] img = Image.open(pic) detection=load_model(os.path.join(settings.BASE_DIR,'static/auto_chloro_model.h5')) test_img=image.load_img(img,target_size=(48,48)) test_img=image.img_to_array(test_img) test_img=np.expand_dims(test_img,axis=0) result=detection.predict(test_img) a=result.argmax() print(a) #models.py class image(models.Model): img = models.ImageField(upload_to="images_api", default="") def __str__(self): return self.product_name #forms.py class imageForm(forms.ModelForm): image = forms.ImageField() class Meta: model = image fields = ['image'] -
how can i use browser_cookie3 on deployed app (heroku)
if request.method=="POST": link=request.POST.get('link') try: link=link.replace("https://www","") link="https://mbasic"+link cookies = browser_cookie3.chrome(domain_name='.facebook.com') html=requests.get(link,cookies=cookies).content.decode('utf-8') s=BeautifulSoup(html,'html.parser') l=s.find('a', {'href': re.compile(r'/video_redirect/')}) url=l['href'] url="https://mbasic.facebook.com"+url print(url) return JsonResponse(json.dumps({'fblink': url}), safe=False) except ConnectionError: return JsonResponse(json.dumps({'error': 'Invalid Link','fblink': ''}), safe=False) deployment to heroku was successful. but when i ran the function, it gives me error 2021-11-05T22:11:32.239159+00:00 app[web.1]: Internal Server Error: /VideoDownloader/downloadFb 2021-11-05T22:11:32.239180+00:00 app[web.1]: Traceback (most recent call last): 2021-11-05T22:11:32.239181+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/secretstorage/init.py", line 72, in dbus_init 2021-11-05T22:11:32.239181+00:00 app[web.1]: connection = open_dbus_connection() 2021-11-05T22:11:32.239186+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/jeepney/io/blocking.py", line 332, in open_dbus_connection 2021-11-05T22:11:32.239186+00:00 app[web.1]: bus_addr = get_bus(bus) 2021-11-05T22:11:32.239187+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/jeepney/bus.py", line 53, in get_bus 2021-11-05T22:11:32.239187+00:00 app[web.1]: return find_session_bus() 2021-11-05T22:11:32.239187+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/jeepney/bus.py", line 42, in find_session_bus 2021-11-05T22:11:32.239188+00:00 app[web.1]: addr = os.environ['DBUS_SESSION_BUS_ADDRESS'] 2021-11-05T22:11:32.239188+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/os.py", line 679, in getitem 2021-11-05T22:11:32.239189+00:00 app[web.1]: raise KeyError(key) from None 2021-11-05T22:11:32.239189+00:00 app[web.1]: KeyError: 'DBUS_SESSION_BUS_ADDRESS' 2021-11-05T22:11:32.239189+00:00 app[web.1]: 2021-11-05T22:11:32.239190+00:00 app[web.1]: The above exception was the direct cause of the following exception: 2021-11-05T22:11:32.239190+00:00 app[web.1]: 2021-11-05T22:11:32.239190+00:00 app[web.1]: Traceback (most recent call last): 2021-11-05T22:11:32.239190+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner 2021-11-05T22:11:32.239190+00:00 app[web.1]: response = get_response(request) 2021-11-05T22:11:32.239191+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response 2021-11-05T22:11:32.239191+00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs) 2021-11-05T22:11:32.239191+00:00 app[web.1]: File "/app/VideoDownloader/views.py", line 48, in downloadFb 2021-11-05T22:11:32.239191+00:00 app[web.1]: cookies = browser_cookie3.chrome(domain_name='.facebook.com') 2021-11-05T22:11:32.239192+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/browser_cookie3/init.py", line 632, in chrome 2021-11-05T22:11:32.239192+00:00 … -
Why does Django add a dollar sign in my URL pattern? (
I spent my entire day trying to fix this bug and I have no idea how to do it. I am trying to create a new markdown file and redirect the user to the new page after submitting the form. I tried to change the URL name, tried to change variable names but nothing works. The problem may be the fact that Django adds a dollar sign in my URL pattern but I am not sure about it because I have tried to give the URL the value of an existing page. I would appreciate a detailed explanation for this problem. my views.py: def entry(request, entry): entryPage = util.get_entry(entry) if entryPage is None: message = messages.warning(request, 'There is not a page with this name.') return render(request, 'encyclopedia/error.html', { 'entryTitle': entry, 'message': message }) else: return render(request, 'encyclopedia/entry.html',{ 'entry': markdowner.convert(entryPage), 'title': entry }) def new(request): if request.method == 'POST': # Get the form form = Post(request.POST) if form.is_valid(): # Clean the form title = form.cleaned_data['title'] lower_title = form.cleaned_data['title'].lower() text = form.cleaned_data['textarea'] entries = util.list_entries() # Check for existing entry for entry in entries: if lower_title == entry.lower(): message = messages.warning(request, "There is already a page with this name.") context = { … -
List & tuple aren't working despite addressing `django.core.excptions.ImproperlyConfigured: The TEMPLATE_DIRS setting must be a list or a tuple` error
I've been hitting a snag with my Django app. Running Python manage.py runserver in my development environment, I get this error: django.core.excptions.ImproperlyConfigured. The TEMPLATE_DIRS setting must be a list or a tuple. After changing TEMPLATE_DIRS to a tuple in settings.py as this TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),) I got : TypeError('Invalid path type: %s' % type(value).__name__)TypeError: Invalid path type: tuple. I got a similar response when I changed it to a list. Meanwhile, running Python manage.py runserver outside the development environment I got: expected str, bytes or os.PathLike object, not tuple on both times I changed TEMPLATE_DIRS to a list and tuple. I should also add that my template files aren't loading. I get: Using the URLconf defined in myProject.urls, Django tried these URL patterns, in this order: accounts/ admin/ The current path, index/, didn't match any of these Here is the project tree: |_______myApp |______ |______pycache__ | |______migrations | |________init__ | |______admin | |______apps | |______models | |______tests | |______urls | |______views |______myProject | |________init__ | |______asgi | |______settings | |______urls | |______wsgi |______env |______static |______templates |______myApp |______index.html |______signup.html manage.py myProject/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('accounts/', include('accounts.urls')), path('admin/', admin.site.urls), ] myApp/urls.py from … -
I am having problems with crispy_forms and formsets
I am using django_crispy_forms and have 2 formsets within the main form. The formsets are generating & saving data correctly, except for the first row, the data is never saved. In the source of the page, the first row does not have an instance number and the second row has an instance number of 0. for example, the id of vegetationType for the first row is id_vegetation-prefix-VegetationType, for the second row it is id_vegetation-0-VegetationType. If I remove the formhelper from the html page ({% crispy formset_vegetation%} instead of {% crispy formset_vegetation formset_vegetation.form.helper%}, the formset renders correctly without the extra row at the top, but the rows are not formatted as an inline formset. Does anyone see what I am doing incorrectly? models.py class Landcover(models.Model): Site = models.ForeignKey(Site, on_delete=models.RESTRICT, default=None, blank=True, editable=True, verbose_name='1. Site Name') Recorders = models.ManyToManyField(ProjectStaff, default=None, verbose_name = '2. Recorders(s)', help_text='select all that apply') Date = models.DateField(default=None, verbose_name='3. Date') Latitude = models.DecimalField(max_digits=9, decimal_places=6, default=None, verbose_name='4. Latitude') Longitude = models.DecimalField(max_digits=9, decimal_places=6, default=None, verbose_name='5. Longitude') class VegetationLevels(models.Model): Landcover = models.ForeignKey(Landcover, on_delete=models.RESTRICT, default=None, editable=True) VegetationLevel = models.ForeignKey(VegetationLevel, on_delete=models.RESTRICT, default=None, verbose_name='Vegetation Level') VegetationType = models.ManyToManyField(VegetationType, default=None, verbose_name='Vegetation Types') class DensiometerReadings(models.Model): Landcover = models.ForeignKey(Landcover, on_delete=models.RESTRICT, default=None, editable=True) Latitude = models.DecimalField(max_digits=9, decimal_places=6, default=None) Longitude … -
How to route to specific viewset methods Django
I've been studying the viewset and router docs for Django and I can't figure out how to set up a route to access the method on a viewset. For example, here is my urls.py: from rest_framework.routers import DefaultRouter from users.views import (UserViewSet, testing) router = DefaultRouter() router.register(r"users", UserViewSet, basename="users") urlpatterns = [ path('testing', testing) ] And then this is my views file in my user directory @csrf_exempt class UserViewSet: def create(self): return JsonResponse({ 'the create endpoint' }) @csrf_exempt def testing(request): return JsonResponse({ "title": "My json res" }) Using postman, I can hit the endpoint example.com/testing and have the json response logged out. However, I try to hit example.com/users/create and I get a 404. I thought the basename propery when registering the viewset with the router would group all of the methods inside that class under that route path and then the methods would all be their own endpoint. Am I thinking about this incorrectly? Any help would be lovely as I am new to Django. I've mostly done Express and Laravel. Thanks! -
Vagrant provision fatal in: TASK [Start yarn]
I'm trying to set up Vagrant and while trying vagrant provision I get the error below: TASK [Start yarn] ************************************************************** fatal: [default]: FAILED! => {"changed": false, "msg": "Unable to start service yarn: Job for yarn.service failed because the control process exited with error code.\nSee \"systemctl status yarn.service\" and \"journalctl -xe\" for details.\n"} PLAY RECAP ********************************************************************* default : ok=25 changed=3 unreachable=0 failed=1 skipped=2 rescued=0 ignored=0 Ansible failed to complete successfully. Any error output should be visible above. Please fix these errors and try again. systemctl status yarn.service says Unit yarn.service could not be found, but the TASK [Deploy yarn install] during Vagrant provision has status ok: [default]. How can I solve the problem? -
Using signals in django, trying to generate code for SMS verification but generated code is not visible in admin. what am i missing?
folder structure enter image description here models.py from face_detect from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,null=True) mobile = models.CharField(max_length=10,null=True) add = models.CharField(max_length=10,null=True) image = models.FileField(null=True) def __str__(self): return self.user.username models.py from otp from django.db import models from django.contrib.auth.models import User from face_detect.models import Profile import random # Create your models here. class Code(models.Model): number = models.CharField(max_length=5, blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return str(self.number) #otp verification def save(self, *args, **kwargs): number_list = [x for x in range(10)] code_items = [] for i in range(5): num = random.choice(number_list) code_items.append(num) code_string = "".join(str(item) for item in code_items) self.mobile = code_string super().save(*args,**kwargs) signals.py from otp from face_detect.models import Profile from django.contrib.auth.models import User from .models import Code from django.db.models.signals import post_save from django.dispatch import receiver @receiver(post_save, sender=User) def post_save_generate_code(sender, instance, created, *args, **kwargs): if created: Code.objects.create(user=instance) apps.py from otp from django.apps import AppConfig class OtpConfig(AppConfig): name = 'otp' def ready(self): import otp.signals init.py from otp default_app_config = 'otp.apps.OtpConfig' admin.py from otp from django.contrib import admin from .models import Code # Register your models here. admin.site.register(Code) code seen in http://127.0.0.1:8000/admin/otp/code/ enter image description here code is not visible. how can i make … -
keep users logged in using Knox Token Authentication django
I am having a hard time trying to figure this out. I am trying to use the django rest api knox token authentication and React. This is what my code looks like in Authenticate.js export function LoginComponent (props) { const [state, setState] = useState({credentials : {username: '',password: '',}}) const [hasLoggedIn, setHasLoggedIn] = useState(false) const Login = (event) => { event.preventDefault() fetch("http://127.0.0.1:8000/users/accounts/api/auth/login",{ method: "POST", headers: {'Content-Type': 'application/json'}, body: JSON.stringify(state.credentials) }) .then( data => data.json()).then( data => { console.log(data.token) props.userLogin(data.token) } ) .then( console.log(hasLoggedIn), setHasLoggedIn(true), props.LoggedIn(hasLoggedIn)) .catch(error => console.error()) } const Register = (event) => { fetch("http://127.0.0.1:8000/users/accounts/api/auth/register",{ method: "POST", headers: {'Content-Type': 'application/json'}, body: JSON.stringify(state.credentials) }).then( data => data.json()).then( data => { console.log(data.token) } ).catch(error => console.error()) } const inputChanged = (event) =>{ const cred = state.credentials; cred[event.target.name] = event.target.value setState({credentials: cred}) } return ( <div> <label> Username: <input type='text' name='username' value={state.credentials.username} onChange={inputChanged} /> </label> <br/> <label> Password: <input type='password' name='password' value={state.credentials.password} onChange={inputChanged} /> </label> <br/> <button onClick={Login}>Login</button> <button onClick={Register}>Register</button> </div> ) } This is a code I made from a youtube video The problem comes while trying to keep the users authenticated, if you refresh on this current code, you will end up losing the Token, which means you have to login … -
Why does upload_to in ImageField not working at all when i try to save uploaded image from user in views
I am trying to make a simple mail service with very simple architecture project. At this moment my backend part of development is almost done, but i have stoped already fro two days because of i have no idea why does images saving not working. Obviously, i expect that user upload his profile avatar and it's saving to path i've set in upload_to. Path to image must looks like profiles/UserName/his_profile_img.jpeg For last two days i have spent more than 12 hours by trying to solve it. This is my model where is my trouble ImageField: from django.db import models from datetime import datetime, timedelta from django.contrib.auth.models import User def username(user, file): string_username = str(user).split()[0] return f"profiles/{string_username}/{file}" class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="Profile") ##### This is here avatar = models.ImageField(default="/profiles/profile.png", upload_to=username) name = models.CharField(max_length=30, blank=True) surname = models.CharField(max_length=30, blank=True) email = models.EmailField(max_length=64, blank=True) bio = models.CharField(max_length=1024, blank=True) def username(self): return self.user.username @property def joined(self): joined = self.user.date_joined.strftime("%d %B %Y") is_today = joined == datetime.today().strftime("%d %B %Y") if is_today: return "today" is_yesterday = joined == datetime.date(datetime.today() - timedelta(days=1)).strftime("%d %B %Y") if is_yesterday: return "yesterday" return f"{joined}" def __str__(self): return f"{self.user} profile" This is a view function, which doesn't save image: def … -
How to duplicate part of html code in django using jinja2?
I need to duplicate a certain part of the code through the Django admin panel. But I do not know how this can be implemented. My teacher suggested that this can be done through jinja2, but I don't really understand how to use jinja2 for my purposes. I would be very grateful to anyone who can help either find information or show you how to implement it. this is the html code that needs to be duplicated <td class ="sale"> {% if good.image %} <img src="{{ MEDIA_URL }}{{ good.image_sale }}"> {% endif %} {% for good in goods %} <h1 class="description">{{ good.description_text }}</h1> {% endfor %} <a class="buy" href="#openModal" > <span >Купить</span></a> {% for good in goods %} <h1 class="price" >{{ good.price_text }}</h1> {% endfor %} </td> I do not know what else to add, if you need something else, write, I will add -
Upload a file in Django Admin, but not as a model's FileField
I'm working with Django 3 and I need to upload a (zip) file via the Django Admin. All the information that I've found online refers to uploading files as a models' FielField. But in my case, I don't want to associate the uploaded file to any model. I just want to upload it and run a certain management command based on its content, and delete it afterwards. If needed, I can use JQuery in the Django Admin pages to help accomplish this goal. Any pointers on how to do this? -
how to remove a null value from session cart dictionary in django
here is my views.py logic to add product in session cart def index(request): categoryID= request.GET.get('category') product= request.POST.get('product') cart=request.session.get('cart') if cart: quantity=cart.get(product) if quantity: cart[product]=quantity+1 else: cart[product]=1 cart['product']=1 else: cart['product']= 1 request.session['cart']=cart print(cart) print(product) category=Category.get_all_categories() if categoryID: products = Product.get_all_products_by_id(categoryID) else: products=Product.get_all_products() prddata={ 'product' : products, 'cat': category, } return render(request,'index.html',prddata) I have added two product in cart but when I print cart in terminal {'product': 1, '1': 1, '2': 4, 'null': 1} 2 [06/Nov/2021 01:10:25] "POST / HTTP/1.1" 200 13104 this null is being added I don't know how. How to prevent this or remove it from cart? please help. -
Query data using filter Django/python
I'm pretty new to the Django backend framework. I have been able to easily query data, but now I'm trying to filter that data. When I run the application it will load the landing page and other pages, but when I try to naviagate to the FRReports page I get "Error during template rendering In template C:\Users\n9177d\webdart\DjangoWebProject1\DjangoWebProject1\webdart\templates\webdart\base.html, error at line 16 'webdart' is not a registered namespace" Any ideas or guidance? urls.py from django.urls import path, include from . import views from webdart.views import AboutView from django.contrib import admin admin.autodiscover() # Use '' to default to the home page urlpatterns = [ path('', views.landing, name='webdart-landing'), path('admin/', admin.site.urls), path('home/', views.home, name='webdart-home'), path('data/', views.data, name='webdart-data'), path('data/stationData/', views.data_stationData, name='webdart-data_stationData'), path('data/obscura/', views.data_obscura, name='webdart-data_obscura'), path('data/tiz/', views.data_tiz, name='webdart-data_tiz'), path('data/mcv/', views.data_mcv, name='webdart-data_mcv'), path('data/viewer/', views.data_viewer, name='webdart-data_viewer'), path('data/multiSiteReport/', views.data_multiSiteReport, name='webdart-data_multiSiteReport'), path('antennaBias/', views.documents_antennaBias, name='webdart-documents_antennaBias'), path('FRReports/', views.DocRepositoryListView.as_view(), name='list'), path('<int:pk>', views.documents_FRReports.as_view(), name='webdart-documents_FRReports'), #path('FRReports/', views.documents_FRReports, name='webdart-documents_FRReports'), path('IERSBulletinA/', views.documents_IERSBulletinA, name='webdart-documents_IERSBulletinA'), . . . views.py from django.core.paginator import Paginator from django.shortcuts import render from django.http import HttpResponse from django.views.generic import TemplateView, ListView, DetailView from webdart.models import Person, DocRepository from webdart.filters import DocRepositoryFilter class DocRepositoryListView(ListView): model = DocRepository template_name = 'webdart/FRReports.html' def get_context_data (self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = DocRepositoryFilter(self.request.GET, queryset=self.get_queryset()) return context class documents_FRReports(DetailView): … -
Django + gUnicorn timing out with POST requests with large sizes
Sending a 'large' POST request to gUnicorn will cause it to freeze and eventually timeout. This is both on my production server and development server (both running Ubuntu 20.04). It just freezes before returning [CRITICAL] WORKER TIMEOUT (pid:10000) Django's default dev server works without issues. My WSGI file: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoProject.settings') application = get_wsgi_application()