Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'NoneType' object has no attribute 'name' in Employee
my code for the employer in the models.py for the employer: class Employee(Person): """ Employee details and their rights to portal. """ name = models.CharField(max_length=50, db_index=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) e_id = models.CharField(max_length=20, db_index=True, unique=True) student_permit = models.BooleanField(default=False) company_permit = models.BooleanField(default=False) placement_permit = models.BooleanField(default=False) def __str__(self): return str(self.e_id + '-' + self.name) def __unicode__(self): return unicode(self.e_id + '-' + self.name) My code in the employer in the context_py function : def get_emp_info(Employee): blood_groups = blood_group_helper() genders = gender_helper() info = { 'ename': Employee.name, 'dob': Employee.dob, 'gender': [i for i in genders if Employee.gender in i], 'phone': Employee.phone, 'address': Employee.curr_address, 'emp_id': Employee.e_id, 'bgroup': [i for i in blood_groups if Employee.blood_group in i], 'photo': os.path.join(settings.MEDIA_URL, employee.photo.name) if Employee.photo else None, } return info The error is saying : File "C:\Users\Administrator\placement\placement\helpers\context_helper.py", line 109, in get_emp_info 'ename': Employee.name, AttributeError: 'NoneType' object has no attribute 'name' What is this error ? what is this solution in this error?? -
Cookie not stored on Chrome Mobile but stored on Chrome Desktop - Django
I am running Django server and setting the cookies in the response, using method update_cookie_id(self, seed) of helper class CookieIDInjector. What it does is, -it checks if request contains a cookie with key=cookie_id -if not then it generates a new cookie value using method generate_cookie_id(seed) -Morsel is imported as a workaround to include SameSite cookie attribute since it's not supported by default in Python 2.7 -it inserts cookie attributes into response and returns cookie_id Now my problem is, when I use Chrome Desktop, the cookie is successfully set, but when I use Chrome Mobile, it is not set - the request never contains a cookie, so the log ===cookie_id is empty appears on each request. Response has the code=302 (redirect). Setting expires explicitly, changing 302 to 200, didn't help. Cookie is never stored in Chrome Mobile. Any clues? import datetime from django.http import HttpResponse from http.cookies import Morsel ... class CookieIDInjector(): COOKIE_HOST = 'domain.com' COOKIE_ID_KEY = 'cookie_id' EXPIRES = datetime.datetime.utcnow() + datetime.timedelta(days=365) SAME_SITE = 'None' SECURE = True def __init__(self, request, response, expires): self.request = request self.response = response def update_cookie_id(self, seed): cookie_id = self.request.COOKIES.get(self.COOKIE_ID_KEY, None) if cookie_id is None or cookie_id == "": logger.info('===cookie_id is empty') cookie_id = self.generate_cookie_id(seed) … -
djongo.database.DatabaseError in model.objects.filter()
Employee model has a field: birthDay = models.DateField() I want to filter the objects of Employee whose birthday is in this month. I don't know why this filter method with the month is not working. Please help me. def getEmployeeBirthday(): employee = Employee.objects.filter(birthDay__month=datetime.date.today().month) return employee This is the trackback name", "api_employee"."last_name", "api_employee"."is_staff", "api_employee"."is_active", "api_employee"."date_joined", "api_employee"."role", "api_employee"."name", "api_employee"."email", "api_employee"."gend er", "api_employee"."date", "api_employee"."isActive", "api_employee"."houseNumber", "api_employee"."street", "api_employee"."addressLine", "api_employee"."mobileNumber", "api_employee"."country", "api_employee "."designation", "api_employee"."isWorking", "api_employee"."birthDay" FROM "api_employee" WHERE EXTRACT('month' FROM "api_employee"."birthDay") = %(0)s Params: (6,) Version: 1.3.2 The above exception was the direct cause of the following exception: django.db.utils.DatabaseError -
NoReverseMatch error for download file page
I am working on a django web application. Here the web app generates a pandas dataframe when a form is submitted. This dataframe is stored in the root directory. I have another view that is used for downloading the generated csv file. But when I redirect to the download page, I get a No reverse match error. this is my code so far def randomfilename(stringLength=8): lettersAndDigits = string.ascii_letters + string.digits return ''.join(random.choice(lettersAndDigits) for i in range(stringLength)) def generate_dataframe(request): if request.method == 'POST': ... df = pd.DataFrame(columns=cols) df['title'] = title_lst df['link'] = product_links[:1] fn = randomfilename() df.to_csv('./'+fn+'.csv') return redirect("scraper:download_file", filename = fn) def download_file(request, filename): if request.method == 'POST': file_path = './'+filename file = open(file_path, 'r') mime_type, _ = mimetypes.guess_type(file_path) response = HttpResponse(file, content_type=mime_type) response['Content-Disposition'] = "attachment; filename=%s" % filename return response urls.py urlpatterns = [ path('generate', views.generate_dataframe, name='generate_dataframe'), path('download/<filename>/', views.download_file, name='download_file'), ] -
I want to visualize the database diagram in django but problem in pygraphviz
I am trying to visualize the database diagram in django. in Docker file I have: RUN apt-get install -y python3-dev graphviz libgraphviz-dev RUN apt-get install -y python-pygraphviz pkg-config and in requirements.txt I have: django, psycopg2, djangorestframework, PyJWT, gunicorn, channels, django-extensions, graphviz, cGraph, pygraphviz but I get this error : Building wheel for pygraphviz (setup.py): started Building wheel for pygraphviz (setup.py): finished with status 'error' ERROR: Command errored out with exit status 1: command: /usr/local/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = ... ---------------------------------------- ERROR: Failed building wheel for pygraphviz Running setup.py clean for pygraphviz Successfully built cGraph Failed to build pygraphviz ... ERROR: Service 'web' failed to build: The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1 any idea about this error? -
session store variable in django
hey guys i am trying to make a website that intergrate with my router i have this little problem is that everytime i make a function that get a variable in the api i need to call the session again and get the host ip and etc. Is there any way i can store the session in some function so that i dont need to call the session everytime i am making the new function in view def dashboard(request): mikrotik_session = request.session.get("mikadmin") host = mikrotik_session.get("host") username = mikrotik_session.get("username") password = mikrotik_session.get("password") con = routeros_api.RouterOsApiPool(host=host,username=username,password=password,plaintext_login=True) api = con.get_api() resource_user = api.get_resource("/ip/hotspot/user") content_user = resource_user.get() -
X-Frame-Options preventing load of ajax view
I'm running the following middleware in my settings file: 'django.middleware.clickjacking.XFrameOptionsMiddleware', I've also got the following option set. X_FRAME_OPTIONS = 'SAMEORIGIN' #required for summernote + django 3 I've got several views within my django project that I want to display in an iframe on another website. I've been able to use the following decorator above the views to accomplish this with success: @xframe_options_exempt I've got other views that are called via ajax. I've added this decorator immediately before these views for ajax and I get a '403 Forbidden' error returned (as seen in the browser's consolue) any time the page tries to run these ajax functions. Any thoughts on how I can get these ajax functions to run? Thanks! -
Django admin detailed history
I'm new to django & I need some help with django admin history. Right now I added HistoricalRecords() to my models and then used SimpleHistoryAdmin in django admin to show history. But this only shows me what was changed, when it was changed and by whom. What I'm looking for is detailed history, meaning along with all the things listed previously I need it to tell me what the previous value was before the change & what the value is after the change. For example: Admin changed someones username, in addition to what I'm already getting (time of change, admin who performed the change & what was changed), I need the previous username before the change & current username after the change to be displayed in the history as well. Before I go on writing my own class I was wondering if there is an easier or better way to do this? I'm been looking all over & can't seem to find one. Any help or sense of direction is greatly appreciated. -
Paypal payment Gateway without business accounts
I am currently creating an online website marketplace using django, where users can list products for sale for others to purchase. The problem I am currently facing is the fact that the paypal payment gateway requires a business account as the target payment account. The idea was for registered users to enter their paypal email in their profile, and when their listing gets purchased by another user the payment process is directed directly to the sellers paypal email. Is there a way to direct the payments between users of the website without them needing a business account? -
Django 3: Combine formsets in one dropdown menu
I have a working model of two forms that I would like to combine: forms.py: FS1 = modelformset_factory(SettRelation, fields=("sett", "qty", ), extra=1, widgets={'sett': forms.Select(attrs={'class': 'form-control'}), 'qty': forms.NumberInput(attrs={'class': 'form-control',})}) FS2 = modelformset_factory(PartRelation, fields=("part", "qty", ), extra=1, widgets={'part': forms.Select(attrs={'class': 'form-control'}), 'qty': forms.NumberInput(attrs={'class': 'form-control',})}) views.py: def create_inq_with_sets(request): if request.method == 'GET': inquiry_form = InquiryModelForm(request.GET or None) setts_form = FS1(queryset=SettRelation.objects.none()) parts_form = FS2(queryset=PartRelation.objects.none()) elif request.method == 'POST': inquiry_form = InquiryModelForm(request.POST) setts_form = FS1(request.POST) parts_form = FS2(request.POST) if inquiry_form.is_valid() and setts_form.is_valid() and parts_form.is_valid(): i = inquiry_form.save() for form in setts_form: tmp = form.save(commit=False) tmp.inquiry = i tmp.save() return redirect("inquiry-list") return render(request, "gap/add_inquiry.html", {"inquiry": inquiry_form, "setts": setts_form, "parts": parts_form, }) .html (simplified): {{ setts.management_form }} {% for sett in setts %} {{ sett.sett }} {{ sett.qty}} {% endfor %} {{ parts.management_form }} {% for part parts %} {{ part.part}} {{ part.qty}} {% endfor %} I would like to combine the two formsets in one dropdown menu, as shown on the picture - can I do this just using the template? -
Scrapy item temporary variable
Using DjangoItem, I have the following model in Django class JobOffer(models.Model): min_salary = models.Field() max_salary = models.Field() In scrapy, the salary is extracted as text: '2500 - 3000£' and parsed in a pipeline to fill min_salary and max_salary. However, I can't set a temporary variable; KeyError: 'JobItem does not support field: salary' I've tried with Meta too, but item['salary'] isn't recognised; class JobOffer(models.Model): min_salary = models.Field() max_salary = models.Field() class Meta: salary = '' -
Deserializing from the choice name instead of integer
Lets say I have a book model that looks like this class Book(models.Model): name = models.CharField(max_length=250, null=True, blank=True) CATEGORY_CHOICES = ( (1, 'Fiction'), (2, 'Non-Fiction'), ) category = models.PositiveSmallIntegerField(choices=CATEGORY_CHOICES) class BookSerializer(serializers.ModelSerializer): category = serializers.CharField(source='get_category_display') class Meta: model = Book fields = '__all__' class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer In GET calls this will return a json that looks like this { category:Fiction name: Harry Potter } but if I give the same json in POST call it will throw an error, since it is receiving get_category_display in "validated_data". Is there a way to send the same json and expect it to add it to the records without going through the route of custom create and update functions? -
Saving a form in a foreign key field
I have two models Order and a date model. Order model has a foreign key attribute of date model. I have made a form in which I can update the datefields of an order, but when I click submit it creates a new date object in date model not in the order date field. models.py class Order(models.Model): date = models.ForeignKey('date', null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) quote_choices = ( ('Movie', 'Movie'), ('Inspiration', 'Inspiration'), ('Language', 'Language'), ) quote = models.CharField(max_length =100, choices = quote_choices) box_choices = (('Colors', 'Colors'), ('Crossover', 'Crossover'), ) box = models.CharField(max_length = 100, choices = box_choices) pill_choice = models.CharField(max_length=30) shipping_tracking = models.CharField(max_length=30) memo = models.CharField(max_length=100) status_choices = (('Received', 'Received'), ('Scheduled', 'Scheduled'), ('Processing/Manufacturing', 'Processing/Manufacturing'), ('In Progress','In Progress'), ) status = models.CharField(max_length = 100, choices = status_choices, default="In Progress") def __str__(self): return f"{self.user_id}-{self.pk}" class Date(models.Model): date_added = models.DateField(max_length=100) scheduled_date = models.DateField(max_length=100) service_period = models.DateField(max_length=100) modified_date = models.DateField(max_length=100) finish_date = models.DateField(max_length=100) view.py def dateDetailView(request, pk): order = Order.objects.get(pk=pk) date_instance = order.date form = DateForm(request.POST, request.FILES, instance=date_instance) if request.method == 'POST': if form.is_valid(): order = form.save(commit = False) form.save() context = { 'order': order, 'form': form } return render(request, "date_list.html", context) -
Want to make a website where users can post images and other users can place comments to the images
As per the title of the question I am making a website which can take in the images uploaded by users and other users can comment on the photo uploaded. I am done with the part where users can upload images and am successful in displaying them This is the list page which stores all the photos uploaded. This is the Detail Page of the post made from the inbuilt DetailView model I want to add the user comments in the DetailView page of the images, which is not possible. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='profile_pics', blank=True) age = models.PositiveIntegerField() def __str__(self): return self.user.username class UserPost(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, default=1) image = models.ImageField(upload_to='image_post', blank=True) title = models.CharField(max_length=256) create_date = models.DateTimeField(default=datetime.now) def __str__(self): return self.title def get_absolute_url(self): return reverse("basic_app:post_list", kwargs={'pk':self.pk}) class Comments(models.Model): post = models.ForeignKey(UserPost, on_delete=models.CASCADE, default=1) text = models.TextField(max_length=300) user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, default=1) time_uploaded = models.DateTimeField(default=datetime.now) def __str__(self): return self.text this is the code in the models.py file. I have a post model by which users can post images and a comment model by which users can post comments. class UserPostForm(forms.ModelForm): class Meta: model = UserPost fields = ('title', 'image', 'create_date') class UserComment(forms.ModelForm): class Meta: … -
Django queryset filter empty JSONField
I would like to filter a JSONField my_fieldwhere the JSon is not empty. In the documentation there are has_keyand has_any_key methods but I don't know the possible keys in advance. In SQL it should be something like: select * from my_model where cardinality(my_field)>0; -
How to disconnect login signals from Django
I am implementing custom authentication in Django v 2.2.7. I'd like to disconnect django default login signals. How Can I do it? And where should the code live? See login source Specifically: Disconnect the user_logged_in signal from update_last_login receiver https://docs.djangoproject.com/en/2.2/topics/signals/#disconnecting-signals Signal.disconnect(receiver=None, sender=None, dispatch_uid=None) -
Javascript: event.target.classList unable to locate selected class in 'contains' condition
What I want I need to check to see if an click event target contains a particular class name called .kanban_custom_tag. If it doesn't I want it to called an ajax request. What I've tried On clicking an element that contains the class. The ajax is called and the condition is true (Which is shouldnt). $(document).on('click','.kanban-item', function (event) { if (!(event.target.classList.contains('.kanban_custom_tag'))) { _id = $(this).attr('data-eid') $.ajax({ type: "POST", url: window.location.href, data: { 'booking_id':_id, 'edit':false, 'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val() }, success: render_booking, dataType: 'json', }); } }) I've debugged this by executing event.target.classList : To which the console prints: DOMTokenList(2) ["btn", "kanban_custom_tag", value: "btn kanban_custom_tag"] Any idea where I've gone wrong, I'm sure this is a simple mistake but I've been coding for so long I'm going blind. -
Authentication between two seperate Django projects
I have 2 different projects which i wish to allow them to communicate via DRF's Api rest endpoints. The problem im having is that i wish the authenticate all requests that happens on the endpoint: r = requests.post('http://127.0.0.1:8000/api/ticket/', json = {'email':self.from_address, 'title': self.title , 'content':form['message'].value(), }) So from project A backend view , i will make a post request to Project B's endpoint in the way shown . above. It works however there is no form of authentication. I wish to implement some sort of API key functionality ontop of my current project infrastructure which uses django-simplejwt as its authentication method. Therefore , to safely send infomation from one project to another , what options do i have? -
Send websocket message from Django view?
How can I send a message to the client side (using the current websocket connection) when a user makes a http request to a page on the Django server? I'd like to make it to where a user presses a button on a HTML web page and then that button triggers the server to send a message to the client over the websocket connection. -
MicroSD card files recovery
I have issue with microsd card. It worked fine on my android smartphone, but from one day phone didn't recognize it. When I plug in the card in my laptop(windows)(linux laptop don't see the card), laptop see it, but I can't get files through explorer and the card keep disconnecting-connecting every minute. I can get file through Total Commander but it takes 2 minutes for one 3mb picture. How can I get photos from the card faster? -
djongo.database.DatabaseError in objects.filter()
I don't why this filter method with the month is not working. def getEmployeeBirthday(): employee = Employee.objects.filter(birthDay__month=datetime.date.today().month) return employee This is the trackback name", "api_employee"."last_name", "api_employee"."is_staff", "api_employee"."is_active", "api_employee"."date_joined", "api_employee"."role", "api_employee"."name", "api_employee"."email", "api_employee"."gend er", "api_employee"."date", "api_employee"."isActive", "api_employee"."houseNumber", "api_employee"."street", "api_employee"."addressLine", "api_employee"."mobileNumber", "api_employee"."country", "api_employee "."designation", "api_employee"."isWorking", "api_employee"."birthDay" FROM "api_employee" WHERE EXTRACT('month' FROM "api_employee"."birthDay") = %(0)s Params: (6,) Version: 1.3.2 The above exception was the direct cause of the following exception: django.db.utils.DatabaseError -
Submit button is not working in django form
I am trying to create a employee using a form. I want that after pressing the submit buttom data saves to employee list table and the page redirect to employee list table also. When I see the error log it shows Method Not Allowed (POST) . I think my code is fine but somehow it is not working. employee_add_form.html: {% extends 'base.html' %} {% block content %} {% load static %} <link rel="stylesheet" href="{% static 'employee/css/master.css' %}"> {% load bootstrap4 %} <div class=""> <form class="form" action="{% url 'employee:employee-list' %}" method="post" id="employee_add_form"> {% csrf_token %} <!-- {% bootstrap_css %}--> {% bootstrap_javascript jquery='full' %} {{ form.media }} {{ form.non_field_errors }} <div class="container"> <label for=""><b>Personal Info</b></label> <div class="border"> <div class="form-row"> <div class="col"> {{ form.first_name.errors }} <label for="">First Name</label> {{ form.first_name}} </div> <div class="col"> {{ form.last_name.errors }} <label for="">Last Name</label> {{ form.last_name}} </div> <div class="col"> {{ form.photo_id.errors }} <label for="">Photo ID</label> {{ form.photo_id }} </div> </div> <div class="form-row inline"> <div class="col-4"> {{ form.gender.errors }} <label for="">Gender</label> {{ form.gender }} </div> <div class="col-4"> {{ form.blood_group.errors }} <label for="">Blood Group</label> {{ form.blood_group }} </div> <div class="col-4"> {{ form.religion.errors }} <label for="">Religion</label> {{ form.religion }} </div> </div> <div class="form-row"> <div class="col"> {{ form.birth_date.errors }} <label for="">Date of … -
Django GET request returns 404 even when the file path is correct
I have been following a youtube tutorial but for some reason when I'm trying to load the image from the databas. I checked the img src attribute and the path seems to be correct, but the server returns a 404 error. I'm not sure why the server cannot seem to find the image I want. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm from django.contrib.auth.decorators import login_required # Create your views here. def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request,f'Your account has been created!') return redirect('login') else: form = UserRegisterForm() return render(request,'users/register.html',{'form': form}) @login_required def profile(request): return render(request, 'users/profile.html') profile.html {% extends "blog/base.html" %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }}</p> </div> </div> </div> {% endblock content %} urls.py from django.contrib import admin from django.urls import path, include from users import views as user_views from django.contrib.auth import views as auth_views … -
How to access dataframe from another django view function
I am working on a test django application. In this application, there exists a form which when submitted, generates a pandas dataframe. The view then redirects to another page. The new page has a button to download the file as a csv. How do I access the dataframe that was generated in the view function for the first page in the view function for the second page. here is my code so far def first_page(request): if request.method == 'POST': ... df = pd.DataFrame(columns=cols) ... return redirect("test_app:second_page") def second_page(request): if request.method == 'POST': # ----------------------# # access the dataframe and download it in the client system How do I achieve this? -
Django Ignore string after PK in URL
product urls.py urlpatterns = [ path('<int:pk>/', ProductDetailView.as_view(), name='detail'), ] Currently my url looks like this http://127.0.0.1:8001/product/11/ However I want to also append the slug of the product. http://127.0.0.1:8001/product/11/example-slug/ But it shouldn't matter what the string is behind it, it should just use the pk in order to display the page. It should ignore the string after /11/ how can I do that?