Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting this error while populating through faker
Faker error while populating a database It worked when i created populate_firstapp but now it is showing an error -
Problem with MySQL databases on a CentOS Droplet
I'm setting up a server for a website and a part of my application, and I'm using a DigitalOcean Droplet that's running CentOS 7. However, I simply can't connect to a database that's on the server, from the server. When I install MySQL 8.0 the service won't start, it says that it can't find mysql.sock, MySQL 5.7 works fine but I always get the "Error establishing a connection to the database" on my website. The user data for connecting to the database is fine, so we got to the conclusion that the Perl MySQL DBD module is missing, however when we try to install that it updates MySQL to version 8.0 and MySQL won't start then. We are not sure which versions we are supposed to use, any help would be appreciated. We are using Python 2.7 and Django 1.12 '''Warning: The Perl module DBD::mysql is not installed on your system, so Webmin will not be able to reliably access your MySQL database. Click here to install it now. '''' -
KeyError, Exception Value: 'object'
1 I'm working on Django. I'm getting the error below. I didn't find the solution despite the much increased. Codes in views.py class UpdateVote(LoginRequiredMixin,UpdateView): form_class = VoteForm queryset = Vote.objects.all() def get_object(self,queryset=None): vote = super().get_object(queryset) user = self.request.user if vote.user != user: raise PermissionDenied('can not change another user vote') return vote def get_success_url(self): movie_id = self.object.movie.id return reverse('core:movie_detail', kwargs={'pk':movie_id}) def render_to_response(self, context, **response_kwargs): movie_id = context['object'].id movie_detail_url = reverse('core:movie_detail',kwargs={'pk':movie_id}) return redirect(to=movie_detail_url) class MovieDetail(DetailView): queryset = Movie.objects.all_with_prefetch_persons() def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) if self.request.user.is_authenticated: vote = Vote.objects.get_vote_or_unsaved_blank_vote(movie=self.object,user=self.request.user) if vote.id: vote_url_form = reverse('core:UpdateVote',kwargs={'movie_id':vote.movie.id,'pk':vote.id}) else: vote_url_form = (reverse('core:create_vote',kwargs={'movie_id':self.object.id})) vote_form = VoteForm(instance=vote) ctx['vote_form'] = vote_form ctx['vote_url_form'] = vote_url_form return ctx Codes in form.py I have used this form to link with UpdateView from django import forms from django.contrib.auth import get_user_model from .models import Movie,Vote class VoteForm(forms.ModelForm): user = forms.ModelChoiceField(widget=forms.HiddenInput,queryset=get_user_model().objects.all(),disabled=True) movie = forms.ModelChoiceField(widget=forms.HiddenInput,queryset = Movie.objects.all(),disabled=True) value = forms.ChoiceField(widget=forms.RadioSelect,choices=Vote.VALUE_CHOICE) class Meta: model = Vote fields = ('value','user','movie',) urls.py This is the url mapping for the view. from django.contrib import admin from django.urls import path from .views import MovieList,MovieDetail,PersonDetail,CreateVote,UpdateVote app_name = 'core' urlpatterns = [ path('movies/', MovieList.as_view(), name='movie_list'), path('movie/<int:pk>/', MovieDetail.as_view(), name='movie_details'), path('person/<int:pk>/', PersonDetail.as_view(), name='person_details'), path('movie/<int:movie_id>/vote/', CreateVote.as_view(), name='create_vote'), path('movie/<int:movie_id>/vote/<int:pk>', UpdateVote.as_view(), name='UpdateVote'), ] HTML template This is the … -
Django. Rest framework. How to add object ID in XML?
In DRF, I create XML in which I need to assign the object id to the main tag It should look as follows: <offer internal-id="Object ID"> <type></type> <category></category> <url></url> </offer> I have a problem with the offer tag as I don’t know how to insert the object ID into it. Nested tags are generated perfectly, there are no problems with them. Here is my views.py: class ZemlaXMLRenderer(XMLRenderer): root_tag_name = 'feed' item_tag_name = 'offer' def _to_xml(self, xml, data): if isinstance(data, (list, tuple)): for item in data: xml.startElement(self.item_tag_name, {'internal-id': 'Object ID'}) self._to_xml(xml, item) xml.endElement(self.item_tag_name) super()._to_xml(xml, data) Ideally, the output should be the following structure: <offer internal-id="1"> <type></type> <category></category> <url></url> </offer> <offer internal-id="2"> <type></type> <category></category> <url></url> </offer> Thank! -
Django Converting to CBV + tests
I'm trying to test my app. I went over the documentation, and managed to make the test for my URL's and all views but one. I'm having trouble converting it to a class view and I'm not really sure what kind of tests should I do here ? Anyone mind helping me out ? here is the view that I'm trying to convert and test : def add_comment_to_article(request, pk): article = get_object_or_404(Article, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = article comment.save() return HttpResponseRedirect(reverse('news:article', kwargs={"article_id": article.pk})) else: form = CommentForm() return render(request, 'news/add_comment_to_article.html', {'form': form}) The view is in charge of adding a comment to my Article post. Thank you !! -
Django-ckeditor not loading edits with crispy-forms
I have a cripsy form and I want to change one field from Textarea to CKEDitorUploadingWdidget So my form looks like this (I have left in what was previoulsy working: class RenameStudyForm(BetterModelForm): name = forms.CharField(label='Study Name', max_length=51, required=False) # Update study name #waiver = forms.CharField(widget=forms.Textarea, label='Waiver of Documentation', required=False) waiver = forms.CharField(widget=CKEditorUploadingWidget(), label='Waiver of Documentation', required=False) I have amended my model as follows: class study(models.Model): researcher = models.ForeignKey("auth.user") # Researcher's name name = models.CharField(max_length = 51) # Study name instrument = models.ForeignKey("instrument") # Instrument associated with study #waiver = models.TextField(blank = True) waiver = RichTextUploadingField(blank = True) My template looks has: {% load crispy_forms_tags %} {{ form.media }} {% crispy form %} When I enter the screen to edit the waiver I get a rich text field to edit, as I would expect. However, nothing I enter into the field is passed back to the form. Within the form I added a print statement, as below def clean(self): cleaned_data = super(RenameStudyForm, self).clean() print(cleaned_data['waiver']) The print always gives the original text. Can anyone help me please -
use Django request.session inside utility function
I am trying to call request.session.get('items', {}) from a custom util function util.py. but in that file, request object is not accessible, I can pass the request object from views.py but i don't want to. is there any way to use request object inside the custom functions (not view/template). I have tried to import from django.http import HttpRequest but this class doesn't have any session variable. django beginner, any help is appreciated thanks. util.py: def processData(data=None): ## get items form session items = request.session.get('items', {}) ## error name 'request' is not defined # append with data items.update(data) return items -
Rewriting functions of ModelViewSet with two serializers
EpisodeImage is connected with foreign key to Episode model. So, Episode has a multiple image loading. But, I am confused how perform all this things combined in API. According to this code everything about episodes works fine, but user has to be able add multiple images in episode, so i am thinking how to perform this by overriding methods. Also, there should be two serialiezers, but I don't think exactly how to do that. Creating different endpoint is bad idea, because during creating episode user will add images too. models.py class Episode(models.Model): ... story = models.ForeignKey(Story, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) episode_number = models.IntegerField(null=True) class EpisodeImage(models.Model): episode = models.ForeignKey(Episode, related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to=upload_location) admin.py class EpisodeImageInline(admin.TabularInline): model = EpisodeImage extra = 3 class EpisodeAdmin(admin.ModelAdmin): inlines = [EpisodeImageInline] admin.site.register(Episode, EpisodeAdmin) serializers.py class EpisodeSerializer(serializers.ModelSerializer): story = serializers.IntegerField(source='story.id', read_only=True) class Meta: model = Episode fields = '__all__' class EpisodeImageSerializer(serializers.ModelSerializer): episode = EpisodeSerializer(read_only=True) class Meta: model = EpisodeImage fields = '__all__' views.py class EpisodeView(viewsets.ModelViewSet): serializer_class = EpisodeSerializer def get_queryset(self): story_id = self.kwargs['story_id'] return Episode.objects.filter(story=story_id) def perform_create(self, serializer): return serializer.save(story=story) def perform_update(self, serializer): return super(EpisodeView, self).perform_update(serializer) def perform_destroy(self, instance): return super(EpisodeView, self).perform_destroy(instance) -
Restart gunicorn in django codes
I deployed my Django application to the internet and every time after changing codes, I have to run this command to make changes happen: sudo systemctl restart gunicorn Is there any way to run this command through codes (for example in views)? or schedule it? Or is there any way to force Gunicorn restarts after changing in codes? I have tried Subprocess but I couldn't make it work. -
Multi searching DJANGO
I have just finished one tutorial where a user can search cities, but it is possible to enter only one city. If i would like to search Oslo, Budapest in the same time it is impossible. Do you know what can I add to change it? Views: from django.views.generic import TemplateView, ListView from django.db.models import Q from .models import City class HomePageView(TemplateView): template_name='home.html' class SearchResultsView(ListView): model = City template_name = 'search_results.html' def get_queryset(self): query = self.request.GET.get('q') object_list = City.objects.filter( Q(name__icontains=query) | Q(state__icontains=query) ) return object_list TEMPLATE: <h1>Search Results</h1> <ul> {% for city in object_list %} <li> {{ city.name }}, {{ city.state }} </li> {% endfor %} </ul> -
Converting SQL join query to django ORM
I am new to django models and trying to convert legacy MySQL queries to django models. I have two tables tb1 and tb2. I want to join the two and use both of their fields to get results. class Tb2(models.Model): tb2_id = models.ForeignKey('Tb1', models.DO_NOTHING, primary_key=True) profile = models.CharField(max_length=15) version = models.CharField(max_length=15) class Tb1(models.Model): id = models.BigAutoField(primary_key=True) job_id = models.BigIntegerField(blank=True, null=True) """ SELECT s.*, IF(count(distinct p.version)<=1, TRUE, FALSE) is_profile_same, MAX(p.version) ver, FROM tb1 s LEFT JOIN tb2 p ON p.tb2_id=s.id WHERE s.id in ('10','9') group by s.id """ Tb1.tb1.filter().select_related('Tb2').annotate(join_profiles=Count('id')) I have left joined the two tables on the ids. I am not sure how to add the if and max conditions using the fields of the tb2. Every time i try to use the fields it gives me FieldError. Can someone help? -
Daemonizing Celery--No module named 'celery' error
I'm trying to daemonize Celery 4.3.0 on Ubuntu 18 following the official documentation. This is for a Django project to off-load intensive tasks. When the server is running the celery.service should make the Celery worker available to process tasks. However, Apache2 won't even run. If I tail the Apache log I see: [Sun Sep 29 07:42:07.621273 2019] [wsgi:error] [pid 2648:tid 140134825535232] [remote 92.4.204.209:55952] File "<frozen importlib._bootstrap>", line 971, in _find_and_load [Sun Sep 29 07:42:07.621279 2019] [wsgi:error] [pid 2648:tid 140134825535232] [remote 92.4.204.209:55952] File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked [Sun Sep 29 07:42:07.621285 2019] [wsgi:error] [pid 2648:tid 140134825535232] [remote 92.4.204.209:55952] File "<frozen importlib._bootstrap>", line 665, in _load_unlocked [Sun Sep 29 07:42:07.621291 2019] [wsgi:error] [pid 2648:tid 140134825535232] [remote 92.4.204.209:55952] File "<frozen importlib._bootstrap_external>", line 678, in exec_module [Sun Sep 29 07:42:07.621297 2019] [wsgi:error] [pid 2648:tid 140134825535232] [remote 92.4.204.209:55952] File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed [Sun Sep 29 07:42:07.621303 2019] [wsgi:error] [pid 2648:tid 140134825535232] [remote 92.4.204.209:55952] File "/var/www/html/examgap/examgap/__init__.py", line 5, in <module> [Sun Sep 29 07:42:07.621307 2019] [wsgi:error] [pid 2648:tid 140134825535232] [remote 92.4.204.209:55952] from .celery import app as celery_app [Sun Sep 29 07:42:07.621313 2019] [wsgi:error] [pid 2648:tid 140134825535232] [remote 92.4.204.209:55952] File "/var/www/html/examgap/examgap/celery.py", line 5, in <module> [Sun Sep 29 07:42:07.621317 2019] [wsgi:error] [pid … -
Django filtering for URLs and VIEWS - "Page not found at /collection/..."
I am retruning all records for specific object in Django successfully. My url.py is path('city/', views.TestListCity.as_view()) From postman I just GET: http://192.168.99.100:8080/collection/city and it returns all records. Example: { "id": 3, "name": "Bor", "region": { "id": 2, "name": "Sun" } }, Now I want to filter records with column name. I tried this: urls.py path('city/(?P<name>.+)/$', views.TestListCity.as_view()), views.py class TestListCity(generics.RetrieveAPIView): serializer_class = TestListCitySerializer def get_queryset(self): name = self.kwargs['name'] return City.objects.filter(name=name) I try GET: http://192.168.99.100:8080/collection/city?name=Bor But then 404: <title>Page not found at /collection/city</title> I also tried second approach: urls.py path('city/<str:name>/', views.TestListCity.as_view()) views.py class TestListCity(generics.RetrieveAPIView): serializer_class = TestListCitySerializer queryset = City.objects.all() lookup_field = 'name' But exactly the same response. -
groupby action on django queryset
I have a db table like this: id | col1 | col2 | col3 1 | 2 | b | c 2 | 1 | a | a 2 | 2 | b | c 1 | 3 | b | c I need to write a queryset to have: {'id':1, 'count_col1': 5, 'id':2, 'count_col1':3} how can I do it? it can be done by groupby in pandas, but I don't know how to do it here. -
Bootstrap 4 select form field isn't working with django
I am new to django and using bootstrap4 form with django. When I use input field text and date it works fine and save data into django admin but if I add Select for categories, it doesn't work and returns following error: ValueError at / The view app_budgetlist.views.home didn't return an HttpResponse object. It returned None instead. I worked for 2 straight days and couldn't figure out what's wrong! Can you help please? Here is my code: models.py from django.db import models # Create your models here. class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class MonthlyBudget(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) budget_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) forms.py from django import forms from .models import MonthlyBudget class MonthlyBudgetForm(forms.ModelForm): class Meta: model = MonthlyBudget fields = ['category', 'budget_amount'] view.py from django.shortcuts import render, redirect from .models import Category, MonthlyBudget from .forms import MonthlyBudgetForm def home(request): project = MonthlyBudget.objects.all() categories = Category.objects.all() if request.method == "POST": form = MonthlyBudgetForm(request.POST or None) if form.is_valid(): form.save() else: return render(request, 'home.html', {'project':project, 'categories':categories}) home.html <form class="form-inline" method="POST"> {% csrf_token %} <input type="text" name="budget_amount" class="form-control mb-2 mr-sm-2" id="budget-amount" placeholder="Amount"> <div class="form-group"> <label for="category">Select Category</label> <select id="category" class="taskCategory" name="category"> <option class="disabled" value="">Choose a category</option> {% for … -
Django: null value in column "is_admin" violates not-null constraint
Simple Question: Why do I get this error: Integrity Error: null value in column "is_admin" violates not-null constraint When I Create a User with This Code? # views.py user_obj = UserProfile.objects.create_user( username = 'username', email = 'test@example.com', password = 'password', ) The Error Sounds clear enough, except that I don't have a column called "is_admin" in my custom user model. I've tried specifying that "is_admin = False" in the code above and in the Customer user manager below, but when I do that, I get a new error that says 'is_admin' is an invalid keyword argument for this function - Here are the details... # models.py ### My Custom User Model Extending AbstractBaseUser class UserProfile(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) username = models.CharField(max_length=255, unique=True) # ... other stuff [definitely nothing called "is_admin"] is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_editor = models.BooleanField(default=False) objects = UserProfileManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] As a sanity check, here is my Customer user manager: # models.py class UserProfileManager(BaseUserManager): def _create_user(self, username, email, password, **extra_fields): if not username: raise ValueError('The given username must be set') email = self.normalize_email(email) username = self.model.normalize_username(username) user = self.model(username=username, email=email, **extra_fields) # user = self.model(username=username, email=email, is_admin = False, **extra_fields) … -
pre_delete signal not working in specific directory
i want remove file from storage when a File instance removed.trying to use django signal. here is my model File: class File(models.Model): orig_name = models.CharField(_('Original Name'), max_length=255) uuid = models.CharField(_('uuid'), unique=True, max_length=36) md5sum = models.CharField(_('md5sum'), max_length=32, null=True) filesize = models.PositiveIntegerField(_('Filesize'), null=True) link = models.CharField(_('link'), max_length=1000) meta = JSONField(default=get_empty_dic) create_date = models.DateTimeField(default=timezone.now) conversation = models.ForeignKey('conversation.Conversation', on_delete=models.CASCADE) the architecture of every app are same.means all of app have own signals directory and in signals's directory we have __init__.py and handlers.py files .here is a brief tree of my app with some detail for file's app: apps ├── conversation ├── post └── file ├── admin.py ├── apps.py ├── __init__.py ├── models.py ├── signals │ ├── handlers.py │ └── __init__.py ├── tests.py ├── urls.py └── views.py here is apps/file/signals/handlers.py : from django.db.models.signals import pre_delete from django.dispatch import receiver from apps.file.models import File @receiver(pre_delete, sender=File) def remove_file_from_storage(sender, instance, *args, **kwargs): print('pre_delete signal for File working') # some code is here and app/file/signals/__init__.py file is empty. in this project we are using multiple signals and all of them working fine but i don't know why this signal not working.other signal are from custom and build-in signal both. please notice when i moving def remove_file_from_storage function into … -
when i startapp "article", and python manage.py runserver, and I do not know why "module 'article.admin' has no attribute 'site" this error happen?
I startup an app named "article" but and configure a import like this:from article import * in the setting configure file, then when i run "python manage.py runserver" the error ocuur like this "AttributeError: module 'article.admin' has no attribute 'site', when I comments 'from article import *' with '#', it will work on well, I do not know how "from article import *" raise the problem. when I comments 'from article import *' with '#', it will work on well from article import * atterns = [ path('admin/', admin.site.urls), url(r'^article/',include('article.urls',namespace='article')), ] File "", line 205, in _call_with_frames_removed File "D:\pythonTestfolder\xuegod\blogtest\blogtest\urls.py", line 25, in path('admin/', admin.site.urls), AttributeError: module 'article.admin' has no attribute 'site' -
django 2.1 HTML form submitting to db error
i am trying to post the data from html form to my db, however i get the error that the url does not exist. what am trying to do is later on turn the test form into dynamic add fields using HTML and Jquery rather than using formset for ease UI designing and handle it in dango back end. also note that am assigning the foreign key which is the startup_name by passing it through the url to test view. the code is as following: models.py: class Startup(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) startup_name = models.CharField('Startup Name', max_length = 32, null = False, blank = False) class Team (models.Model): str_team = models.ForeignKey(Startup, on_delete=models.CASCADE) name = models.CharField('Name',max_length = 32, null = False, blank = False) position = models.CharField('Title/Position', max_length = 32, null = False, blank = False) qualification = models.CharField('Degrees/Qualifications', max_length=32,null=False,blank=False) views.py: def create_startupform(request): if request.method == 'POST': form = startupform(request.POST) if form.is_valid(): result = form.save(commit=False) result.author = request.user result.save() return redirect('test', startup_id = result.pk) else: form = startupform() return render(request, 'str_name.html', {'form': form}) def test (request, startup_id): stup = Startup.objects.get(id=startup_id) if request.method == 'POST': na = request.POST.get("name") po = request.POST.get("position") qu = request.POST.get("qualification") ref = Team(name = na, position = po, … -
How to run celery in django tests using PyCharm
I'm trying to test my django application functionalities. Some of my tasks are using celery. How can I run celery in my test environment using PyCharm? -
Is it possible Django model filter by LogEntry by user added in ModelAdmin?
I am working with a blog site. I want to add some feature that like admin filter post can modify only that user added. I want to use Django builtin LogEntry model. Any can help me? -
How to return multiple items in a get_queryset function in Django?
So I have a web app where the user can enter their information, and eventually I want to display all of it, but at the moment this code right here class UserPostListView(ListView): model = Post template_name = 'mainapp/user_posts.html' context_object_name = 'posts' def get_queryset(self): user = get_object_or_404(User,username=self.kwargs.get('username')) first_name = get_object_or_404(User,first_name=self.kwargs.get('first_name')) return Post.objects.filter(author=user).order_by('-published_date') It gives me an error, and it says User not found. I have tried add this to the end of the return statement .order_by('-published_date'),first_name However this did not work. This is the relevant urls.py file responsible for the user posts path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), This is the UserProfileInfo model class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50,blank=True,null=True) last_name = models.CharField(max_length=50,blank=True,null=True) description = models.CharField(max_length=150) image = ProcessedImageField(upload_to='profile_pics', processors=[ResizeToFill(150, 150)], default='default.jpg', format='JPEG', options={'quality': 60}) joined_date = models.DateTimeField(blank=True,null=True,default=timezone.now) verified = models.BooleanField( default=False) def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) And here is the relevant bit of the user-posts.html <div class="sidebar"> <p class="active" href="#">{{ view.kwargs.username }}</p> <button class="commentbtn"><a class="aclass" href="#">Connect with {{ view.kwargs.username }}</a></button> <p>{{ view.kwargs.first_name }}</p> <p>Lorem</p> </div> I want to be able to display the first name of the person in the ```{{ view.kwargs.first_name }}, however everything I have tried has failed to work I expected no … -
python django 2.2.4 ImportConfigured Error in urls.py
Question When I ran Django web server with 'python manager.py runserver', some error happened. It seems like [django.core.exceptions.ImproperlyConfigured: The included URLconf 'myproject.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.] Project tree is like below: root project myapp: __init__.py urls.py views.py myproject: __init__.py urls.py settings.py uwsgi.py manage.py __init__.py myproject/urls.py code: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls', namespace='myapp')), ] myapp/urls.py code: from myapp import views from django.urls import path urlpatterns = [ # path('/', views.Home.as_view(), name='home'), path('signup/', views.Signup.as_view(), name='signup'), path('signin/', views.Signin.as_view(), name='signin'), path('signout/', views.Signout.as_view(), name='signout'), path('make_csr/', views.MakeCSR.as_view(), name='make_csr'), path('upload_csr/', views.UploadCSR.as_view(), name='upload_csr'), path('publish_cer/', views.PublishCER.as_view(), name='publish_cer'), ] Detailed error message: (cert_mgmt) C:\Users\wenca\Desktop\Python\virtual_environment\cert_mgmt\python\Src>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\Python37\lib\site-packages\django\urls\resolvers.py", line 581, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Program Files\Python37\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Program Files\Python37\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Program Files\Python37\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper … -
SQL injection in Django Update Radiolist - Burp Suite
I'm new to programming. I have developed a Web application using python django framework. I have a particular view that updates the status of a particular row in the database from active to inactive and vice versa. and i have used html forms (Radiolist) and django templates in the hmtl page to create a front end. I have used Django's ORM - Update method to update the fields accordingly. But when I run a security audit using Vega security audit tool, I get an alert saying that there is a possible sql injection. I have tried everything but this error doesn't seem to go this is the html code <form class="" action = "{% url 'CHApp_new:update_statement' %}" method="post"> {% csrf_token %} <table class="table table-striped table-dark two" align="center"> {% for x in sobjects %} <tr> <td>{{forloop.counter}}</td> <td>{{x.statement}}</td> {% if x.status == 'y' %} <td>Active</td> {% else %} {% if x.status == 'n' %} <td>Inactive</td> {% endif %} {% endif %} <td style= "text-align:center"><input id= "{{forloop.counter}}" type="checkbox" name= "{{forloop.counter}}" value={{x.id}}></td> <input type="hidden" name="radiolist" value="{{forloop.counter}}"> </tr> {% endfor %} </table> <table align = "center"> <tr> <td><input type="submit" class = "btn btn-primary" name="Update" value="Cycle Activate/Deactivate"></td> </tr> </table> </form> and this is the django view. … -
Is there a way to get the url of a particular image from a django formset?
The challenge I'm facing right now is that I can't seem to display a particular image saved using formset by using the code {{items.images.url}} on my django template. I want to display the first image Before I edited my model to have a separate class to hold my advert images, I could display a particular image using {{items.image_1.url}} but now I can't. I have tried media/{{items.images.values.first.image}}, it worked but I don't think it's the right way to go about it, what if I want to display just the second image on the formset, then that code won't work. Please help. My models class Advert(models.Model): """All adverts""" STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField(max_length=49) description = models.TextField() price = models.PositiveIntegerField() date_created = models.DateTimeField(auto_now_add=True) date_posted = models.DateTimeField(auto_now=True) category = models.ForeignKey( Category, related_name='advert', on_delete=models.DO_NOTHING) status = models.CharField( max_length=10, choices=STATUS_CHOICES, default='draft') class Meta: ordering = ['-id'] def __str__(self): return self.title class AdvertImage(models.Model): advert = models.ForeignKey( Advert, related_name='images', on_delete=models.CASCADE) image = models.ImageField( upload_to='product_pictures') def __str__(self): return self.advert.title My views def view_all(request): """View All view""" view_all_list = Advert.objects.all().order_by('date_posted') context = { "view_all_list": view_all_list } return render(request, 'view-all.html', context) My template <!-- list BEGIN --> {% for items in vehicle_list %} <a> <img …