Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to find how many objects reference the same foreign key in Django
I'm creating a simple web app that uses Django as its backend. Currently, I have two models: Toy and Attributes. A toy contains a reference to an attribute. My goal is to return an error to the frontend whenever an attribute is going to be deleted but is still referenced by a toy. For example, a train toy could have the attribute "black". When I go to delete black, I should get a not possible error, since "black" is still referenced by the toy train. How would I go about checking the number of references an Attribute has? -
Django ajax how to get object href and image link?
I am implementing ajax in my list views page. Now I am facing problems for rendering image and object href. How to get my object href link and image src link from ajax? here is my code: views.py: class PostJsonListView(View): def get(self, *args, **kwargs): print(kwargs) upper = kwargs.get('num_posts') lower = upper - 1 posts = list(Blog.objects.values('id','title','body','blog_header_image')[lower:upper]) posts_size = len(Blog.objects.filter(is_published='published')) max_size = True if upper >= posts_size else False return JsonResponse({'data':posts,'max': max_size},safe=False) .html <div class="card mb-4" id="card mb-4"></div> <script> const postsBox = document.getElementById('card mb-4') console.log(postsBox) const spinnerBox = document.getElementById('spinner-box') const loadBtn = document.getElementById('load-btn') const loadBox = document.getElementById('loading-box') let visible = 1 const handleGetData = () => { $.ajax({ type: 'GET', url: `/posts-json/${visible}/`, success: function(response){ maxSize = response.max const data = response.data spinnerBox.classList.remove('not-visible') setTimeout(()=>{ spinnerBox.classList.add('not-visible') data.map(post=>{ console.log(post.id) postsBox.innerHTML += `<div class="card-body"> <h2 class="card-title"><a href="">${post.title}</a></h2> </div>` }) if(maxSize){ console.log('done') loadBox.innerHTML = "<h4>No more posts to load</h4>" } }, 500) }, error: function(error){ console.log(error) } }) } handleGetData() loadBtn.addEventListener('click', ()=>{ visible += 3 handleGetData() }) </script> How to get object href so user can click an view the details page? also how to render image url? -
define fields of Django ModelForm class on instantiation
I want my website-users to quickly adjust just one attribute of my model objects in a view (with htmx) (to avoid creating tons of ModelForms just with other fields attributes) that's why I want to create a ModelForm where I can define the displayed form fields on instantiation of the form in the view function, the desired field will be passed as a 'fieldlist' parameter into the view function , somehow like that: class ModelForm(ModelForm): class Meta: model = Model fields = --> how to put the at the ModelForm-instantiation (with a request passed) "fieldlist" parameter here? def __init__(self, *args, **kwargs): fieldlist = kwargs.pop('fieldlist') super(ModelForm, self).__init__(*args, **kwargs) any hints? -
How to send Crypto payments (programmatically) gotten through coinbase commerce
i have successfully integrated coinbase commerce into my django app for receiving cryptocurrency payment from the users. However the site payment process involves receiving payment from a User A which is intended for User B into the site coinbase commerce wallet and then only after User B has completely handed over whatever was the value/asset been paid for, then the payment would go on to be forwarded finally to User B. But the issue is that coinbase commerce has no facility for sending payments. and though payment can be sent with a python api on COINBASE, they are two seperate things and the money/coin in coinbase commerce would not be accessible from COINBASE even if it the same user/profile on the platform. Please does anyone have a solution to this problem...even if it does not use coinbase commerce, the only requirement is that it uses a crypto payment gateway -
Ajax / Django / jQuery - autocomplete titles and remove when user deletes what was typed into input
(Reposted from Reddit) I am in the early stages of generating an autocomplete (I would love for it to be a drop-down from the input I'm using, right now it's divs that are being prepended), when a user begins typing (once >2 characters reached). I had a version that would somewhat-correctly show these results that it's pulling from a massive database after typing into the input has begun. But when I added the "else if" close to the bottom with the intention of removing all divs that have been added once the user starts deleting the typed-in phrase, nothing is coming up now. This is the implementation of my js file as it currently stands: $(document).ready(function() { $( "#movie_titles" ).keyup(function(){ var movie_titles = $('#movie_titles').val(); var has_typed = false; if (movie_titles.length > 2) { $.ajax({ url: '/get_movies', type: 'POST', data: {'movie_titles': movie_titles, csrfmiddlewaretoken: '{{ csrf_token }}' }, dataType: 'json', success: function(response) { // var len = response.length; has_typed = true; $('#movie_titles').empty(); console.log(response) // for (var i = 0; i < len; i++) { $('#result-part').prepend('<div class="movie-title">' + response.title + '</div>'); // $(this).val(''); return false; } }); console.log(movie_titles); } else if (has_typed && movie_titles.length <= 2) { $('#result-part').remove(); } }); }); Any ideas … -
Django passwords changing by themselves
I have a really weird issue, I use django authentication and I use django AbstractUser. The problem is passwords are changing by themselves, I'm not even able to track when this change occurs, even if the App is not used, once I try to login again I can't it tells me the password is wrong, How did I know that the password changed ? I compared the SHA code in database, since I always use "admin" as password for the app. I have some password configs in my settings but I doubt it is linked to them : REST_AUTH_SERIALIZERS = { 'PASSWORD_RESET_SERIALIZER': 'forms.api.serializers.PasswordResetSerializer', } # Password validation AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] this is my User model class User(AbstractUser): ''' model for user extends default django user ''' MALE = 1 FEMALE = 2 GENDER_CHOICES = ( (MALE,'Male'), (FEMALE,'Female') ) gender = models.PositiveIntegerField(choices=GENDER_CHOICES,null=True) email = models.CharField(max_length=256,unique=True,blank=True,null=True) receive_emails = models.BooleanField(default=True) objects = CustomUserManager() created_date = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_date = models.DateTimeField(auto_now=True, blank=True, null=True) Can you please, if anyone has encountered this issue before, let me know and also if there is a solution to solve this. … -
Send csv files with data from db to email python
I have db and there is table called Users. id name last_name status 1 John Black active 2 Drake Bell disabled 3 Pep Guardiola active 4 Steve Salt disabled I would like to send to one email two csv files. The first one will be with name sucess.csv and there will be ID from the table, with status active, and the second one csv will be named failed.csv and inside will be ID with status disabled. Right now my code looks like this: def send_user_report(): logger.info('User report generating') user_data = {} user = Users.objects.values('id', 'status') buffer = io.StringIO() writer = csv.writer(buffer) writer.writerow([]) email = EmailMessage('Users report', body, to=settings.EMAIL_TEST) email.attach('sucess_report.csv', buffer.getvalue(), 'text/csv') email.send() -
Hosting Static Files on AWS - Amazon Bucket - Django
I need to host my static files on AWS in order to sort out some problems I have been having with my Django website. I have been trying to solve this on and off for about a year now while finishing up the rest of the website but now it is the last thing to do and I can't put it off any longer. I have looked at the documentation and looked at so many videos with no luck. Below is everything I have including code and my bucket file configuration that pertains to this problem. Everything that I currently have running should be hosting all my static files on my Amazon Bucket, however, it isn't. I'm not getting an error but when I 'inspect' on google they are all being hosted locally. Thank You so much in advance. P.S. = The gallery folder I have in my bucket is for images that users upload and those images are successfully being hosted on AWS and working fine it's just the static. This means the connection to the bucket is working fine. import django_heroku from pathlib import Path import os from django_quill import quill # Build paths inside the project like … -
Describe MS SQL database for Django legacy integration
I am trying to integrate a legacy DB (MS SQL 2012) into Django just to fetch data (no write operations). I have tried using the inspectdb management command but it only generates tables which don't have any foreign keys. I am fairly certain that the DB tables do not include foreign keys from a different DB (which is currently not supported by django). How do I go about getting all the attributes for each column/field in all of the tables so that I can create Django models on my own? Details that I'm looking for include (but are not limited to) : Column data type, All relational keys (Foreign, o2o, o2m), Max length, Max digits, Isblank, Isnull, Unique, Uniquetogether, Decimal places. -
How to post information from javascript TextInput into a django sqlite database?
I am completely new to website backends and am stumped on how to post information from a TextInput field created in Adobe Animate to a database. I would be able to do this no problem if the TextInput was part of an HTML form, but because it's javascript, I am lost. I've uploaded the project to my Github here: https://github.com/jeremyjed/SavetheDate and the site can be viewed on the repos page here: https://jeremyjed.github.io/SavetheDate/ I also have this page running on my local machine inside django. As you view that, the second to last slide has a TextInput labeled "addrs" and a submit button labeled "submit". Right now I have it so the animation continually loops on this slide to allow a user to input their data. Once the submit button is clicked the animation progresses to the last page. All I'm trying to do is to post the information populated in the TextInput field when the submit button is clicked and save it to django's database. I'm assuming this isn't too complicated, I just cant seem to get it to work. Any help would be really appreciated! -
Dj rest auth using JWT Token stored in HttpOnly cookies
I'm making a Django Rest Framework application with a JWT authentication with tokens stored in HttpOnly cookies. Authentication is performed via reading the access cookie. I'm using a dj-rest-auth library for this purpose, but I'm a little confused of the security aspect of such method. Knowing that having authentication data stored in cookies can be used to perform CSRF attack, how can one protect their web against such attacks for a specific case I've described above? All cookies are set to be SameSite=Lex. Do I need to also send X-CSRFTOKEN header obtained from the backend? That would mean that every request to the api will need to have that header. What should be the optimal setup having all those libraries? -
Django how to save value to model without being present on form post
I have the following Model/form/view: Model class Account(models.Model): username = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=150) identifier_type = models.ForeignKey(IdentifierType, on_delete=models.SET_NULL, null=True) actflag = models.CharField(max_length=1, blank=True) created_date = models.DateTimeField(blank=True, null=True) comments = models.TextField(_( 'comments'), max_length=500, blank=True) priority_type = models.ForeignKey(PriorityType, on_delete=models.SET_NULL, null=True) deadline_date = models.DateTimeField(blank=True, null=True) def __str__(self): return self.name Form class PortfolioForm(forms.ModelForm): portfolio = forms.CharField(widget=forms.Textarea) class Meta: model = Account fields = ['name', 'comments', 'priority_type', 'deadline_date', 'identifier_type', 'portfolio'] View def portfolios(request): if request.user.is_authenticated: if request.POST: fm = PortfolioForm(request.POST) user = User.objects.get(username=request.user) if fm.is_valid(): messages.success(request, 'Portfolio has been created.') fm.save() return redirect('portfolios') else: fm = PortfolioForm() context = {"name": request.user, "form": fm} return render(request, 'portfolios.html', context) else: return redirect('login') The form works fine with posting via my template, however you will notice there are some fields within my model that are not in my form I would like to fill in automatically without the user having to fill in - for example username field I would like this to be current user that submits the form and also created_date would like the current date time the user has submitted the form. I tried to add the following to my view under if fm.is_valid(): attempting to save username as current user to the … -
Hosting Static Files on AWS - Amazon Bucket - Django
I need to host my static files on AWS in order to sort out some problems I have been having with my Django website. I have been trying to solve this on and off for about a year now while finishing up the rest of the website but now it is the last thing to do and I can't put it off any longer. I have looked at the documentation and looked at so many videos with no luck. Below is everything I have including code and my bucket file configuration that pertains to this problem. Everything that I currently have running should be hosting all my static files on my Amazon Bucket, however, it isn't. I'm not getting an error but when I 'inspect' on google they are all being hosted locally. Thank You so much in advance. P.S. = The gallery folder I have in my bucket is for images that users upload and those images are successfully being hosted on AWS and working fine it's just the static. This means the connection to the bucket is working fine. import django_heroku from pathlib import Path import os from django_quill import quill # Build paths inside the project like … -
django How do I print functions as they are called?
It's the best way I've found so far. https://pypi.org/project/Autologging/ from autologging import traced @traced class SocialAccountAdapter(DefaultSocialAccountAdapter): def pre_social_login(self, request, sociallogin): user = sociallogin.user print(user.email) raise Exception('test') However, this method only print the decorated class. Is there any way to print all the connected subclass functions when they are called? -
How to get data from config file (config.json) in real time in settings.py file in django
I have a project made in Django. I have only added social auth for login purposes. I want selected emails only to log in to the website. I used social-auth-app-django library for social auth and added a variable SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_EMAILS to the settings.py file where it contains a list of all the emails permitted for logging in. My project directory looks something like this: project_parent/ ----project/ --------settings.py --------wsgi.py --------asgi.py --------urls.py ----app/ --------models.py --------views.py --------urls.py --------admin.py ----db.sqlite3 ----manage.py ----config.json Here is the config file: { "OAUTH2": { "WHITELISTED_EMAILS": [ "xyz@gmail.com", "abc@gmail.com", "efg@gmail.com", "lmn@gmail.com" ] } } In settings.py file I have loaded the config file like this: config = open('./config.json',) data = json.load(config) SOCIAL_AUTH_GOOGLE_OAUTH2_WHITELISTED_EMAILS = data['OAUTH2']['WHITELISTED_EMAILS'] I have made a webpage that takes the new mail id (need to add to the config file) and appends that particular mail id (or a list of mail ids) to the config.json file. But now the problem arises, the newly added mails don't reflect directly to the variable defined in the settings.py file. For that, I need to restart the code in order to get the latest config file. Every time I add a mail id, I need to restart the code. I thought to … -
Error NoReverseMatch at /contacto/perfil-contacto/1/
Estoy haciendo una agenda de contactos y tengo un problema a la hora de redireccionar a una url en la plantilla. Cuando quiero editar un contacto me aparece el siguiente error: NoReverseMatch at /contacto/perfil-contacto/1/ Reverse for 'actualizar_contacto' with arguments '('',)' not found. 1 pattern(s) tried: ['contacto/actualizar\-contacto/(?P[^/]+)$'] Donde el error en la plantilla es el siguiente: <a href="{% url 'contacto:actualizar_contacto' perfil.id %}"></a> La urls del archivo principal es esta: urlpatterns = [ path('admin/', admin.site.urls), path('', login_required(Inicio.as_view()), name='index'), path('contacto/', include(('MiApp.Contacto.urls','contacto'))), path('usuario/', include(('MiApp.Usuario.urls','usuario'))), path('accounts/login/', Login.as_view(), name='login'), path('logout/', login_required(logoutUsuario), name='logout'), ] Y en mi app tengo la siguiente url que corresponderia a donde quiero dirigirme, que seria la de perfil_contacto: urlpatterns = [ path('nuevo-contacto/', CrearContacto.as_view(), name='nuevo_contacto'), path('perfil-contacto/<str:pk>/', PerfilContacto.as_view() , name='perfil_contacto'), path('actualizar-contacto/<str:pk>/', ActualizarContacto.as_view() , name='actualizar_contacto'), path('eliminar-contacto/<str:pk>/', EliminarContacto.as_view(), name='eliminar_contacto'), ] Como se puede ver tiene la "pk" tanto en la url como en la plantilla. Si me pueden ayudar lo agradeceria, gracias. -
I want to get all the wallpapers who have similar name, tags to the wallpaper which is rendered
view.py def download(request, wallpaper_name): wallpaper = Wallpaper.objects.get(name=wallpaper_name) context = {'wallpaper': wallpaper} return render(request, 'Wallpaper/download.html', context) models.py class Tags(models.Model): tag = models.CharField(max_length=100) wallpaper model class Wallpaper(models.Model): name = models.CharField(max_length=100, null=True) size = models.CharField(max_length=50, null=True) pub_date = models.DateField('date published', null=True) resolution = models.CharField(max_length=100, null=True) category = models.ManyToManyField(Category) tags = models.ManyToManyField(Tags) HTML <ul> <li>{{wallpaper.name}}</li> {% for i in wallpaper.tags_set.all %} <li>{{i.tags}}</li> {% endfor %} url.py path('<wallpaper_name>/', views.download, name="download"), Like example the wallpaper I have choosen to download has tags nature and ocean so I want all the wallpapers who have this tag -
How to do an category filter tab logic in django template with js or vue
I am working on categories and brands, one brand can have many categories and I am displaying a button for each category on a Django template and all the brands below but I want that when I press a button category only display the brands that have that category models.py class Filter(models.Model): text = models.CharField(max_length=20) def __str__(self): return self.text class Category(models.Model): filter = models.ForeignKey(Filter, on_delete=models.CASCADE, null=True) icon = models.FileField(upload_to='img', null=True) class Brand(models.Model): logo = models.ImageField(upload_to='img', null=True) url_logo = models.URLField(max_length=200, null=True) filters = models.ManyToManyField(Filter) views.py class HomePageView(TemplateView): template_name = "index.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update({ 'category_list': Category.objects.all(), 'brand_list': Brand.objects.all() }) return context index.html {% for category in category_list %} <a href="#"><i><img src="{{ category.icon.url }}" alt="{{ category.filter }}"></i>{{ category.filter }}</a> {% endfor %} {% for brand in brand_blocks %} <div> <a href="{{ brand.url_logo}}"> <img src="{{ brand.logo.url }}" /> </a> </div> {% endfor %} -
problems serving two django backend apps and two angular frontend app on the same ip address
i have a digitalocean ip address 143.20.20.14 ip set up with two domains members.com and sales.com to server two django app each with angular frontends. for each app i have setup separate files as follows: this is my members.com gunicorn socket file [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target this is my sales.com gunicorn file gunicornsales.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicornsales.sock [Install] WantedBy=sockets.target this is my member.com gunicorn service gunicorn.service file [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=webapps Group=www-data WorkingDirectory=/home/webapps/membersdir ExecStart=/home/webapps/membersdir/members_env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ membersbackend.wsgi:application [Install] WantedBy=multi-user. this is my sales.com gunicorn.service file gunicornsales.service [Unit] Description=gunicorn daemon Requires=gunicornsales.socket After=network.target [Service] User=webapps Group=www-data WorkingDirectory=/home/webapps/salesdir ExecStart=/home/webapps/salesdir/sales_env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicornsales.sock \ salesbackend.wsgi:application [Install] WantedBy=multi-user. my nginx files are as follows this is my members front end file membersfrontend server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html/membersfrontend; index index.html index.htm index.nginx-debian.html; server_name members.com; location / { add_header Access-Control-Allow-Origin *; # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. #try_files $uri $uri/ =404; try_files $uri $uri/ /index.html; } } this is my sales frontend file salesfrontend server { listen 80 … -
Can I use a single search bar for searching different things?
I'm trying to use a single search bar for searching different models. Is it possible to handle it with one view? my views.py file: class SearchResultsView(ListView): model = Food template_name = 'restaurant/food_search_results.html' context_object_name = 'data' def get_queryset(self): query = self.request.GET.get('search') if query is not None: return Food.objects.filter(name__icontains=query) else: return Food.objects.none() my models.py file: class Food(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to=upload_path) description = models.TextField(max_length=500) created = models.DateTimeField(auto_now_add=True) meal_category = models.ManyToManyField(MealCategory, related_name="meal") food_restaurant_category = models.ManyToManyField(FoodRestaurantCategory, related_name="food_cat") class Restaurant(models.Model): name = models.CharField(max_length=100) -
Prediction percent
I am searching to find solution. I can't make percent to my prediction. Here is only 0 for no risk and 1 - when pacient has heart disease. How can I upgrade my code and show percentage of risk? I've tried a lot of things, but it doesn't work. Still 0 and 1 predictions = {'SVC': str(SVCClassifier.predict(features)[0]), 'LogisticRegression': str(LogisticRegressionClassifier.predict(features)[0]), 'NaiveBayes': str(NaiveBayesClassifier.predict(features)[0]), 'DecisionTree': str(DecisionTreeClassifier.predict(features)[0]), } pred = form.save(commit=False) l=[predictions['SVC'],predictions['LogisticRegression'],predictions['NaiveBayes'],predictions['DecisionTree']] count=l.count('1') result=False if count>=2: result=True pred.num=1 else: pred.num=0 pred.profile = profile pred.save() predicted = True And here is my Logistic Regression example: from sklearn.linear_model import LogisticRegression classifier =LogisticRegression() classifier.fit(X_train,Y_train) y_Class_pred=classifier.predict(X_test) from sklearn.metrics import accuracy_score accuracy_score(Y_test,y_Class_pred) from sklearn.metrics import confusion_matrix cm = confusion_matrix(Y_test, y_Class_pred) from sklearn.metrics import classification_report print(classification_report(Y_test, y_Class_pred)) from sklearn.metrics import roc_auc_score from sklearn.metrics import roc_curve logit_roc_auc = roc_auc_score(Y_test, classifier.predict(X_test)) fpr, tpr, thresholds = roc_curve(Y_test, classifier.predict_proba(X_test)[:,1]) plt.figure() plt.plot(fpr, tpr, label='Logistic Regression (area = %0.2f)' % logit_roc_auc) plt.plot([0, 1], [0, 1],'r--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic') plt.legend(loc="lower right") plt.savefig('Log_ROC') plt.show() Newdataset = pd.read_csv('newdata.csv') ynew=classifier.predict(Newdataset) -
Django code cannot install a pickled sklearn variable
I am building a Django site which contains a segmentation application. A difficulty I am having is importing the segmentation kmeans / hclusters variables which have been stored via joblib. To try to minimize the factors involved, I am building the clusters on the same machine (new M1 Macbook) as the machine I am loading the variables into. I have also utilized the same environment structure (both Python 3.10 environments) and synched the numpy, pandas and scikit-learn environments. I am unable to deduce what is preventing the joblib load in the Django environment. The error occurs when using pickle / pickle5 as well. Error message when attempting import: Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydevd_bundle/pydevd_exec2.py", line 3, in Exec exec(exp, global_vars, local_vars) File "<input>", line 1, in <module> File "/Users/username/miniforge3/envs/website/lib/python3.10/site-packages/joblib/numpy_pickle.py", line 587, in load obj = _unpickle(fobj, filename, mmap_mode) File "/Users/username/miniforge3/envs/website/lib/python3.10/site-packages/joblib/numpy_pickle.py", line 506, in _unpickle obj = unpickler.load() File "/Users/username/miniforge3/envs/website/lib/python3.10/pickle.py", line 1213, in load dispatch[key[0]](self) File "/Users/username/miniforge3/envs/website/lib/python3.10/pickle.py", line 1538, in load_stack_global self.append(self.find_class(module, name)) File "/Users/username/miniforge3/envs/website/lib/python3.10/pickle.py", line 1580, in find_class __import__(module, level=0) File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs) File "/Users/username/miniforge3/envs/website/lib/python3.10/site-packages/sklearn/cluster/__init__.py", line 6, in <module> from ._spectral import spectral_clustering, SpectralClustering File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import module … -
get data from one column in db django
I have table in my db Users: id name last_name status 1 John Black active 2 Drake Bell disabled 3 Pep Guardiola active 4 Steven Salt active users_data = [] I would like to get all id and all status row from this db and write to empty dict. What kind of querry I should use? filter, get or smth else? And what if I would like to get one column, not two? -
Base "/" not found in Django
My django project ornaments has only one app called balls. I would like the server to point to its index when I do manage.py runserver. I changed urls.py as follows but I get this error: [![enter image description here][1]][1] from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('balls/', include('balls.urls')), path('admin/', admin.site.urls), ] urlpatterns += [ path('', RedirectView.as_view(url='balls/', permanent=True)), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)``` I am also including the project structure. Please note that the string `ball` appears nowhere in my code (as per a search).[![enter image description here][2]][2] [1]: https://i.stack.imgur.com/6JL2c.png [2]: https://i.stack.imgur.com/1pjCg.png -
Get name of image when uploading
I am using this code to check the size of an image before uploading on the model. I would like to get the image name so I can communicate to the users what the offending file is. How would I go about this. def validate_image(image): file_size = image.file.size if file_size > settings.MAX_UPLOAD_SIZE: raise ValidationError("Max size of file is 3MB") image = models.ImageField(default='default.jpg',validators=[validate_image])