Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSRF verification failed. Request aborted. (Python Request Module)
I have this function in my views.py (Django project) def boardsJson(request): user=request.GET.get('user') password=request.GET.get('password') : : Bla Bla Bla : : return HttpResponse("Login Success") I am tryingto login by this request module. import requests URL = "http://35.196.206.72:8000/boardsJson/" PARAMS = { 'user':'1234567890', 'password':'kak', } r = requests.get(url = URL, params = PARAMS) print(r.text) Every thing is well until I am using the GET method to login. But if I use the POST(I Just replaced the "GET" with "POST" every where) method then I am getting the message something like bellow. <p>CSRF verification failed. Request aborted.</p> <p>You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.</p> <p>If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for âsame-originâ requests.</p> So please help me to solve it. Thank you. -
Dynamic Choices (Those that get updated for new values entered.)
In this project, I got three types of users: ChalkSlateAdmin (this is not a superuser, administrator or staff, etc.), Student and Teacher. All of these can be considered ChalkSlateUser as each have a OneToOne Relationship with the model. ChalkSlateAdmin can be considered an institute and any time someone registers as a ChalkSlateAdmin, there is a new institute as ChalkSlateAdmin has that attribute. Teachers and Students can join institutes (ChalkSlateAdmin attribute) that are already registered. So, I need to create a form that has choices of institutes that are currently registered. My question is, how can I define choices that change depending on what institutes (ChalkSlateAdmin attribute) are registered? Before this, I used constant string values for choices like male & female. models.py, from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db import models class MyAccountManager(BaseUserManager): def create_user(self, username, email, password=None): if not email: raise ValueError("Users must have an email address.") if not username: raise ValueError("Users must have a username.") user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user=self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.user_type = 1 user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) class ChalkSlateUser(AbstractBaseUser): # required to include email = models.EmailField(verbose_name='email', unique=True, … -
Django CORS_ORIGIN_WHITELIST not working while CORS_ORIGIN_ALLOW_ALL does
I am trying to use django-cors-header for my api but the whitelist is not working. If I set CORS_ORIGIN_ALLOW_ALL=True it works, but my white list does not. CORS_ORIGIN_WHITELIST = [ 'http://127.0.0.1:8000', ] Any suggestions as to what I am doing wrong? -
How to authenticate a Django session using captcha?
I have built a website, and a captcha. The captcha is generated by models and displayed on a template. Views from resumesite.models import Chess_board import json def home(request): return render(request, 'home.html', {}) def chess(request): board = Chess_board() data = mark_safe(json.dumps(board.rep)) return render(request, 'captcha_original.html',{'board': data}) I would like to redirect all requests to the captcha, and on completion of the captcha redirect to website and allow full access for duration of the session (i.e. for period of 20 minutes). How would you suggest going about this? Options Middleware/decorator authenticating by ip address (I have read this won't work if user is using a proxy) Custom login form, with decorator @login_required(login_url="/chess/") Integrating with REST and using token authentication -
django search on site taggit
model class Bb(models.Model): image = models.ImageField(upload_to=get_timestamp_path, verbose_name='Pic') author = models.ForeignKey(AdvUser, on_delete=models.CASCADE, verbose_name='Author') created_at = models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='Date') tags = TaggableManager() def delete(self, *args, **kwargs): for ai in self.additionalimage_set.all(): ai.delete() super().delete(*args, **kwargs) class Meta: verbose_name_plural = 'Posts' verbose_name = 'Post' ordering = ['-created_at'] view def index(request): query = request.GET.get('q') if query: query = request.GET.get('q') #.split(" ") posts = Bb.objects.filter( #tags__name__in=query # this is an invalid request logic: tags__name__iexact=request.GET.get('q') ).distinct() else: posts = Bb.objects.all() paginator = Paginator(posts, 1) page_number = request.GET.get('page') posts = paginator.get_page(page_number) return render(request, 'main/home.html', {'query': query, 'posts': posts}) it is necessary to display all the posts in which there are certain some tags. I'm trying to implement a tag-based site search, like on pornhub or rule34. I expect to get the result analog: enter image description here django-taggit is a reusable Django application designed to make adding tagging to your project. -
django-filter Filter based on year of a database column
I have a column (dob) as date in the database. How do I filter on the year of it? class PersonFilter(django_filters.FilterSet): class Meta: model = Person fields = ['first_name','last_name','dob',] -
FileNotFoundError - [Errno 2] No such file or directory: '/static/background.jpg' - Django
I wrote the following code, in Python, Django framework: class ImageGenerator: def __init__(self, tip): self.tip = tip def remove_transparency(self, im, bg_colour=(250, 250, 250)): if im.mode in ('RGBA', 'LA') or (im.mode == 'P' and 'transparency' in im.info): alpha = im.convert('RGBA').split()[-1] bg = Image.new("RGBA", im.size, bg_colour + (255,)) bg.paste(im, mask=alpha) return bg else: return im def generate(self): print('Triggered') border = 3 home_url = self.tip.fixture.home.image_url away_url = self.tip.fixture.away.image_url home_name = self.tip.fixture.home.name away_name = self.tip.fixture.away.name response = requests.get(home_url) home = self.remove_transparency(Image.open(BytesIO(response.content))) home_w, home_h = home.size response = requests.get(away_url) away = self.remove_transparency(Image.open(BytesIO(response.content))) away_w, away_h = away.size background_image = Image.open('/static/background.jpg', 'r') When I execute this code I get the following error: FileNotFoundError at /fixtures/view/54848 [Errno 2] No such file or directory: '/static/background.jpg' Request Method: POST Request URL: http://127.0.0.1:8000/fixtures/view/54848 Django Version: 3.0.3 Exception Type: FileNotFoundError Exception Value: [Errno 2] No such file or directory: '/static/background.jpg' Exception Location: /home/sander/.local/lib/python3.6/site-packages/PIL/Image.py in open, line 2809 Python Executable: /usr/bin/python3 Python Version: 3.6.9 Python Path: ['/home/sander/git/football', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/sander/.local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Fri, 28 Feb 2020 18:56:54 +0000 I defiend the following variable in the django settings file: STATIC_URL = "/static/" STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static') I tried using the static function from from django.templatetags.static import static. … -
Django - aggregate fields value from joined model
my goal here seems to be simple: display the Sum (aggregation) of a foreign model particular field. The difficulty consist in the current set-up, kindly take a look and let me know if this need to be changed or I can achieve the goal with current model: class Route(models.Model): name = models.CharField(max_length=50) route_length = models.IntegerField() class Race(models.Model): race_cod = models.CharField(max_length=6, unique=True) route_id = models.ForeignKey(Route, on_delete=models.CASCADE, related_name='b_route') class Results(models.Model): race_id = models.ForeignKey(Race, on_delete=models.CASCADE, related_name='r_race') runner_id = models.ForeignKey(Runner, on_delete=models.CASCADE, related_name='r_runner') Now, I am trying to have like a year summary: Runner X have raced in 12 races with a total distance of 134 km. While I was able to count the number of races like this (views.py) runner = Runner.objects.get(pk=pk) number_races = Results.objects.filter(runner_id=runner).count() For computing the distance I have tried: distance = Results.objects.filter(runner_id=runner).annotate(total_km=Sum(race_id.route_id.route_length)) This code error out stating that on views.py - distance line Exception Type: NameError Exception Value: name 'race_id' is not defined I am sure I did not u/stood exactly how this works. Anybody kind enough to clarify this issue? Thank you -
pass variable from one view to another (I don't think I need requests.sessions as I don't need global access to this value)
I'm building a job-board type of website. After searching a zip code on the index page, the user is taken to the search_results page. On this page is a list of jobs in the area and a form for users to subscribe by email to be alerted about new posts. Here is the view: def search_results(request): query =request.GET.get('query') # zip code jobs = [] # logic for querying Job objects and filling 'jobs' list omitted form = JobSeekerEmailForm() # pass email subscription form to template return render(request, 'job/search_results.html', {'query':query, 'jobs': jobs, 'form':form}) In the search_results.html template, if the user submits the JobSeekerEmail() they are redirected to the email_subscription view: <form action="{% url 'email_subscription' %}" method="POST"> <input type = 'text' placeholder="Email"/> <button type="submit" name="button">Submit</button> </div> {% csrf_token %} </form> In this view I just save the email and attempt to redirect back to search_results, so the user can continue browsing jobs in the zip code they searched for: def job_seeker_email(request): if request.method == 'POST': form = JobSeekerEmailForm(request.POST) if form.is_valid(): form.save() return redirect('search_results') # search results will throw an error because there is no longer a 'query' value but this will fail. Is there a way to pass the original query value … -
Adding django project root directory to installed apps
I tried to add a project-wide management command the way it was described in documentation. However django didn't register the command as the project root (directory containing settings.py) wasn't in INSTALLED_APPS, so I added it and it worked. Is it safe to do this? -
How to customize admin model save to insert values into multi tables in Djagngo Admin
I'm a beginner to Django . I have to Models : class AvailableReservation(models.Model): startDate = models.DateField() endDate = models.DateField() isActive = models.BooleanField(default=False) count = models.IntegerField(blank=False, null=False) class ReservationDetails(models.Model): reservationDate = models.DateField(); reservation = models.ForeignKey(Reservation, on_delete=models.CASCADE)``` count = models.IntegerField(blank=False, null=False) The first class is registered in admin.py admin.site.register(AvailableReservation, AvailableReservationAdmin) and this is my admin interface for adding AvailableReservation Add AvailbleReservations Screen Now, after clicking the save button, inputs should be stored into AvailableReservation and ReservationDetails. But with some calculations. First, the user inputs go to the AvailableReservation. Second, I want to calculate the how many days between the startDate and the endDate. Then insert records(equal to the number of days between the startDate and the endDate) into the ReservationDetails -
Django-filters: Filtering on upper case values BooleanFilter
I want to filter on a field (say first_name). The user should be able to either input upper or lower case. Is this the right approach ? Instead, should I do icontains using this: https://django-filter.readthedocs.io/en/master/guide/usage.html#overriding-default-filters Thanks ! class PersonFilter(django_filters.FilterSet): first_name_upper = django_filters.BooleanFilter(field_name='first_name',method='filter_upper') class Meta: model = Person fields = ['first_name_upper',] -
How to turn a Django QueryDict into a list of Django ORM OR filters?
I would like to turn this: http://127.0.0.1:8000/fields_data/?field_name__exact=053&field_name__exact=064 into this: fields = Fields.objects.filter(Q(field_name__exact='053')| Q(field_name__exact=field'064)) There could be additional numbers of field_name__exacts, it's not known until runtime. In views.py, I can turn the URL into a QueryDict easily because request.GET is already a QueryDict object. According to the docs, QueryDict was designed in part so that the same key name could be used with multiple values, a common pattern in urls. I then try to turn the QueryDict into something compatible with **kwargs by using: fields = serialize('geojson', Fields.objects.filter(**request.GET.dict())), but request.GET.dict() looks like this: {'field_name__exact': ['053', '064']}. As a result, I only ever get back the second object. I'm starting to suspect I may need to write something more sophisticated involving comprehensions, but I feel like I'm really close. Can someone help me with the correct syntax to turn the QueryDict (multi-valued keys) into an OR'd set of Q()'s? -
Redirect to same view but remember the previous query value
I'm building a job-board type of website. After searching a zip code on the index page, the user is taken to the search_results page. On this page is a list of jobs in the area and a form for users to subscribe by email to be alerted about new posts. After subscribing by email, I want to redirect them to the same view but I no longer have access to their original zip code query. I use the following view: def search_results(request): # query db for Job objects to display (this code not important) query =request.GET.get('query') zcdb = ZipCodeDatabase() zipcode = zcdb[query] zip_codes_in_radius = [z.zip for z in zcdb.get_zipcodes_around_radius(query, 15)] jobs = [] for zip in zip_codes_in_radius: jobs_in_zip = Job.objects.filter(business__zip_code = zip) if jobs_in_zip: jobs += jobs_in_zip # Email subscription form if request.method == 'POST': form = JobSeekerEmailForm(request.POST) if form.is_valid(): form.save() return redirect('search_results') # will no longer have access to 'query' and thus cannot grab Job objects from db else: form = JobSeekerEmailForm() return render(request, 'job/search_results.html', {'query':query, 'jobs': jobs, 'form':form}) Upon subscribing to email alerts, I want to redirect the user to this same search_results view so they can continue browsing. If a user does submit the JobSeekerEmailForm(), they are … -
Accessing other user profile Django
Hi I was wondering how can I build a view that can shows the details of another user, for example their name, email address, and etc. Using Django views? Without compromising the user that is being viewed? For example user A can view user B profile when it requests mysite.com/B. Thanks in advance. -
DRF, queryset by a models choices field
I have the following Django rest framework model: from django.db import models from django.utils import timezone from Project_Level.CONSTANTS import AREAS class KnownLocation(models.Model): name = models.CharField(name="Name", unique=False, max_length=150, blank=False, help_text="Enter the name of the location's name") area = models.CharField(name='Area', max_length=8, choices=AREAS) date_added = models.DateTimeField(default=timezone.now) latitude = models.FloatField(name="Latitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", default=1) longitude = models.FloatField(name="Longitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Longitude, second when extracting from Google Maps.", default=1) AREAS = [ ('210', '210'), ('769', '769'), ('300', '300') ] serializer: from rest_framework.serializers import Serializer from .models import KnownLocation class KnownLocationSerializer(Serializer): class Meta: model = KnownLocation fields = ('id', 'Name', 'Area', 'Latitude', 'Longitude') I want to write a view with a query set ( maybe a get_queryset method will be better), where the query return all objects which has the same 'area' has the one past in by the user. -
Django model is truncating a decimal place when passed to the view when DecimalField is set
Django Model: class TwoDecimal(models.Model): two_decimal = models.DecimalField(decimal_places=2, max_digits=10) View: def two_decimal(request): test = TwoDecimal( two_decimal = 30.00 ) test.save() return render( request, "test-template.html", {"test": test} ) Template: {{ test.two_decimal }} #==> Displays as 30.0 instead of 30.00 (Despite it being a two decimal field.) This displays properly if it is a query from already saved data. Why is django truncating this decimal place? -
How to display all the data of a CSV file in a HTML page?
I have a code in django that reads a csv file and stores its data in a database, what I intend to do is show that data in an HTML page, this is my view: def addbulkuser(request): prompt = { 'order': 'Order of the file should be: Username, First name, Last name, Email & Password' } if request.method == "GET": return render(request, 'andon/user_form_bulk.html', prompt) data_file = request.FILES['file'] if not data_file.name.endswith('.csv'): messages.error(request, 'This is not a csv file') if data_file.name.endswith('.csv'): data_set = data_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): created = User.objects.update_or_create( username=column[0], first_name=column[1], last_name=column[2], email=column[3], password=column[4], last_login=datetime.now(), ) user = User.objects.get(username=column[0]) user.set_password(user.password) user.save() andon_user_group = Group.objects.get(name='andon_user') andon_user_group.user_set.add(user) col = column colu = messages.success(request, 'Users added successfully') context = {'col': col, 'colu': colu } return render(request, 'andon/user_form_bulk.html', context) return render(request, 'andon/user_form_bulk.html') The variable "col" contains all the data in the csv file and I have it called this way in the HTML: {% for column in col %} {{ column }} {% endfor %} But it only shows me in the html the last data in the CSV file, how could I show all the data? Regards. -
djang oscar voucher and offers
if i have a single offer that gives 10% off and also i have a voucher that give 10% off in same products. when i add these two offers to my basket, voucher discount not applied. if i change the priority of offers i can add voucher but single offer discount not applied. i need to apply these two offers to the basket. i created a custom condition for voucher offers. then i tried to consume 0 quantity to that offer. but it's not working as i expected class CustomCouponCondition(CountCondition): ''' oscar_customize.offer.models.CustomCouponCondition ''' name = "Custom Coupon Conditions" class Meta: proxy = True def consume_items(self, offer, basket, affected_lines): for __, line in self.get_applicable_lines(offer, basket, most_expensive_first=True): line.consume(0, offer=offer) -
How to extract href link from this given code using bettersoup. i have tried other results on stack overflow
i am trying to scrap magnetic link from website. I am trying Beautifulsoup. I'm using pycharm with env. This is how the href elements I need look like: -
Drag and Drop a folder with submit button using jQuery and Ajax
I am working on a project where I have to drag and drop folder to upload into the database. I am using Django, jQuery and ajax for this purpose. But the problem is whenever I am trying to submit the form, I am getting this error: CSRF verification failed. Request aborted. Moreover, it's not working in chrome, showing this problem: This site can’t be reached Here is my code: View.py: class BasicUploadView(View): def get(self, request): file_list = file_information.objects.all() return render(self.request, 'fileupload_app/basic_upload/index.html',{'files':file_list}) def post(self, request): file_obj = file_store() zipfile = ZipFile('test1.zip','a',ZIP_DEFLATED) #need to zip folder before storing if request.method == "POST": for upload_file in request.FILES.getlist('file'): for chunk in upload_file.chunks(): zipfile.writestr(upload_file.name,chunk) zipfile.close() file_obj.file = File(open(zipfile.filename,'rb')) file_obj.fileName = os.path.basename(zipfile.filename) file_obj.save() data = {'name':file_obj.fileName, 'url':file_obj.fileName} return JsonResponse(data) HTML: <div style="margin-bottom: 20px;"> <form id="my-form" method="POST" action="{% url 'fileupload_app:basic_upload' %}" enctype="multipart/form-data"> {% csrf_token %} <div id="file-wrap"> <p>Drag and drop file here</p> <input id="my-file" type="file" name="file" multiple draggable="true"> </div> <div> <input type="submit" value="upload"> </div> </form> </div> JS: $(function () { var csrftoken = $.cookie('csrftoken'); $("#my-file").on('change', function (e) { $("#file-wrap p").html('Now click on Upload button'); }); $("#my-form").on('change', function (e) { var eventType = $(this).attr("method"); var eventLink = $(this).attr("action"); $.ajax({ type: eventType, url: eventLink, data: new FormData( this ), … -
Defaut password reset form error: with Django and gmail
I am currently trying to create a password reset form for my site.I have looked on several questions simmilar to this one but none provide the answer for me. I have also created an app password on the gmail website and I am using that as I have 2FA. I am getting the error: SMTPSenderRefused at /password-reset/ (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError n8sm12016723wrm.46 - gsmtp', 'webmaster@localhost') . My settings.py code: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAL_HOST_USER = '***********' EMAIL_HOST_PASSWORD = '*********' urls.py file, where the view has been instanciated: from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from users import views as user_views urlpatterns = [ path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='password_reset'), path('password-reset/done', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name='password_reset_done'), path('password-reset-confirm/<uidb64>/<token>', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm'), ] -
Date field not appearing in a Django form
I have created a Django form which almost works correctly All of the fields appear with their Labels and Help Text. If I define the Field type as Dropdown it works perfectly, But if I define a field as Date it just seems to act as a normal Single line text. (A form with html <input type="date" id="today" name="today"> works perfectly in the browser so that isn't the problem) Am I missing something? -
Redirect button to django admin auth views
That could be a stupid question... But I am trying to create a button in my django navbar to redirect to the admin authentication views, and did not manage to find the answer to my question when googling. I manage to do: <li><a href="{% url 'admin:appname_model_perm' %}">Manage XYZ</a></li> and: <li><a href="{% url 'admin:index' %}">Main view</a></li> but I cannot find a way to create one for admin:auth... Here is what I tried: <li><a href="{% url 'admin:auth' %}">Manage auth</a></li> <li><a href="{% url 'admin:authentication' %}">Manage auth</a></li> <li><a href="{% url 'admin:authenticate' %}">Manage auth</a></li> Also, and because I feel stupid to ask the above question, is there a way in django to get a list of all available registered urls? Instead of having this quite useless error message: Reverse for 'auth' not found. 'auth' is not a valid view function or pattern name. Thank you for your help -
How to remove some elements of list input in django admin
i have a list like this in my django admin : Do you know if it's possible to remove some elements of that list ? for example i would like to remove all "gateway" that have the status "inactive" ( status=False ). Here gateway model : class Gateway(models.Model): def __str__(self): return self.name name = models.CharField(max_length=255) logo = models.TextField() status = models.Boolean() I don't even know if it's possible to do some filter on a list in django admin ... thank for your help !