Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to register an instance method as a Signal receiver via decorators?
There are multiple ways to register class methods as Signal receivers in Django. Using the built-in receiver decorator is an obvious solution, but can work only with static methods or simple functions: from django.db.models.signals import post_save from django.dispatch import receiver class SignalCollection: @receiver(post_save) def some_signal(sender, instance, created, **kwargs): # code pass With instance methods, this decorator won't work as such methods require self as a first parameter. In this case, instantiating after defintion is what works: class SignalCollection: def some_signal_a(self, sender, instance, created, **kwargs): # code pass def some_signal_b(self, sender, instance, created, **kwargs): # code pass collection = SignalCollection() post_save.connect(collection.some_signal_a) post_save.connect(collection.some_signal_b) The potential issue with this is that it's not well encapsulated, and in case of many methods contains a lot of repeation. For solving this issue, I intended to apply custom decorators. My question is: is it possible to create such a decorator, either for the class itself, or for its methods, that can perform connections without instantiating the class? My research yielded no results, and many of my attempts were failed - adding receiver through method_decorator can work, but in none of my snippets were the signals triggered, meaning the connection did not happen. Creating a class decorator … -
instead of downloading the file, it downloads the HTML file
I want to download the files that I uploaded into the admin inside my template. But instead of downloading the file, it downloads the HTML file. view.py def download(request, path): file_path = os.path.join(settings.MEDIA_ROOT, path) if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="media/upload/bookfile/filepath") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 model.py filepath= models.FileField(upload_to='upload/bookfile', null=True, blank=False, validators=[validate_Bookfile]) url.py urlpatterns = [ url('download/(?P<path>.*)',serve,{ 'document_root':settings.MEDIA_ROOT}), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) template.html <li id="sell"><a href="{{Book.filepath.url}}" download="{{Book.filepath.url}}">download</a></li> -
How to add upload files fuctionality in changelist view page of model admin using django 3?
Code snippets that I was able to add so far: Model class: class MboxForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(MboxForm, self).__init__(*args, **kwargs) csv_file = forms.FileField(required=True, label="Select CSV file") class Meta: model = Mbox fields = ['some_field', ] widgets = { 'csv_file': forms.FileInput(), } In admin.py: class MboxAdmin(admin.ModelAdmin): actions = [import_from_csv, export_to_csv] def get_form(self, request, obj=None, **kwargs): kwargs['form'] = MboxForm return super().get_form(request, obj, **kwargs) def get_urls(self): urls = super().get_urls() my_urls = [ path("upload_csv", self.upload_csv, name='upload_csv') ] return my_urls + urls urls = property(get_urls) def upload_csv(self, request): if request.method == 'POST': form = MboxForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('admin/change_list.html') else : return render(request, 'admin/change_list.html', {'form': form, 'opts': Mbox._meta}) else: return render( request, 'admin/change_list.html', context ) def changelist_view(self, request, extra_context=None): extra_context = {} extra_context['submit_csv_form'] = MboxForm if 'action' in request.POST and request.POST['action'] == 'import_from_csv': if not request.POST.getlist(admin.ACTION_CHECKBOX_NAME): post = request.POST.copy() for u in Mbox.objects.all(): post.update({admin.ACTION_CHECKBOX_NAME: str(u.id)}) request._set_post(post) return super().changelist_view(request, extra_context=extra_context) This button displays in place of the add button in the listing page with the template but is not functional i.e. doesn't display the file browser to upload any file. It on the contrary displays error {% extends "admin/change_list.html" %} {% load i18n admin_urls static admin_list %} {% block object-tools %} {% if … -
Disable unique constraint on Django's ManyToManyField
From the Django documentation for ManyToManyField: If you don’t want multiple associations between the same instances, add a UniqueConstraint including the from and to fields. Django’s automatically generated many-to-many tables include such a constraint. How do I disable this constraint? Is the only way to provide an explicit through table? Or is there a way to tell Django to not add the UniqueConstraint to the generated many-to-many-table? -
AttributeError at /admin/accounts/school/ 'School' object has no attribute 'username'
hello am just wondering why cant I return return f'{self.user.username} Profile' form this model class School(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200) region = models.CharField(max_length=200) district = models.CharField(max_length=200) code = models.CharField(max_length=20) logo = models.ImageField(default='default.jpg', upload_to='logos') def __str__(self): return f'{self.user.username} Profile' what should be the syntax here help -
django split data and apply search istartswith = query
I have a Project and I need to split the data in to words and apply searching. for example: my query is : 'bot' (typing 'bottle') but if I use meta_keywords__icontains = query the filter will also return queries with 'robot'. Here meta_keywords are keywords that can be used for searching. I won't be able to access data if the data in meta_keywords is 'water bottle' when I use meta_keywords__istartswith is there any way I can use in this case. I can simply create a model and for 'meta_keywords' and use the current data to assign values by splitting and saving as different data is the best way. I need some other ways to achieve it. -
what is the procedure for taking brand approval for django website?
I am making Django based news website which has both features API fetching as well as manual updating. I wanted to know that what is the procedure for taking brand approval for my website like having my brand registered and is it a costly method or cheap for free and where can I get it done?? -
How to retrieve the data corresponding to the link clicked in Django
I have database with a books = {Id, title, rating, page_count, author} In home.html I'm displaying the Title as link and when the user clicks it should redirect to a page with all the details. home.html {% for book in books %} <a href= "buy.html"> {{ book.Title }} </a> <p> Rated - {{ book.Rating }}</p> <p> {{ book.Authors }} </p> {% endfor %} Now when the user clicks on the Title it redirects to a new page buy.html and I want to display the complete details stored in my database. Can someone assist me here? -
Opencv integration with Django
I have a Opencv script that converts Videos on Django db to frame. I want to save the frame on the same folder with the video. I created a function upload_to that creates a folder to store the uploaded video. currently the generated frame is stored on the media directory not upload_to which looks like 'media/photo/name'. Opencv script import cv2 import os from .models import upload_to def video_to_frame(video): cap= cv2.VideoCapture(video) i=1 while(cap.isOpened()): ret, frame = cap.read() if ret == False: break if i%10 == 0: cv2.imwrite(os.path.join(upload_to,'new_image'+str(i)+'.jpg'),frame) i+=1 cap.release() cv2.destroyAllWindows() Model.py file from django.db import models from datetime import datetime import cv2 import tempfile from django.utils import timezone import os def upload_to(instance, filename): return os.path.join('photos', str(instance.name), filename) from .utils import video_to_frame class MyVideo(models.Model): name= models.CharField(max_length=500) date = models.DateTimeField(auto_now_add=True) videofile= models.FileField(upload_to=upload_to) def __str__(self): return self.name + ": " + str(self.videofile) def save(self, *args, **kwargs): tfile = tempfile.NamedTemporaryFile(delete=False) tfile.write(self.videofile.read()) vid = video_to_frame((tfile.name)) super(MyVideo, self).save(*args, **kwargs) -
Couldn't send email from django via sendgrid
Hope someone can help. couldn't send email from by django application via sendgrid. have created an account in sendgrid made changes as said in the documentation. tried almost everything from various blogs, but hard luck. settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_USE_TLS = True EMAIL_PORT = 465 EMAIL_HOST_USER = 'apikey' SENDGRID_API_KEY = os.environ.get('SENDGRID_API_KEY') EMAIL_HOST_PASSWORD = SENDGRID_API_KEY views.py from django.core.mail import send_mail from django.http import JsonResponse def sendEmail(request): try: subject = 'Test' message = 'Testing' from_email = <mail id> recipient_list = [<mail id>,] send_mail(subject, message, email_from, recipient_list) return JsonResponse({'message':'mail sent'}, status = 200) except Exception as e: return False -
django file field isn't showing up the first time when I load the page
I have a django html page that should show a upload button and a place where you can place your files. the first time when I load the page only the upload button is there. After I click on the button the choose your file button appears. Is there a possebility that the choose file always shows? HTML code <form action="{% url "result" %}" method="POST" enctype="multipart/form-data" action="/result/" class="form-horizontal"> {% csrf_token %} <div class="form-group"> <label for="name" class="col-md-3 col-sm-3 col-xs-12 control-label">File: </label> <p>{{ form }}</p> </div> <div class="form-group"> <div class="col-md-3 col-sm-3 col-xs-12 col-md-offset-3" style="margin-bottom:10px;"> <button class="btn btn-primary" type="submit"> <span class="glyphicon glyphicon-upload" style="margin-right:5px;"></span>Upload </button> </div> </div> </form> views.py @login_required def result(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): data = request.FILES['file'] handle_uploaded_file(data) data = pd.read_csv(data,header=0, sep=',') result = getPredictions(data) return HttpResponseRedirect(request, 'result.html', {'result': result}) else: form = UploadFileForm() return render(request, 'index.html', {'form': form}) -
How to search for the most occuring value in a one to many relationship django?
I have this one to Many relationship between pizza and restaurant. class Restaurant(Model): name = models.CharField(max_length=50) class Pizza(Model): restaurant = models.ForeignKey(Restaurent) name = models.CharFiedl(null=True, max_length=50) price = models.IntegerField(max_length=10, null= False) I would like to be able to search Restaurants for the most occurring price of their pizzas or mode https://en.wikipedia.org/wiki/Mode_(statistics). Django does not seem to have functionality to implement this easily. -
Django & Geopy : calcul distance btwn fixed position (post) and moving position (user.userprofile) position
I am looking for how to define a distance between two points. The first one is related to the post itself and does not change. It indicates the position of the post. The second would be linked to the user's position. The problem is that nothing is displayed. Do you have an idea? Thanks a lot for your help, {% if user.is_authenticated %}{% if user.userprofile.longitude %} {{ post.distance_post }}km {% else %}{% endif %} {% endif %} post/models.py class Cuisine(models.Model): ... latitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0') longitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0') def distance_post(self, request): post_situation = (self.longitude, self.latitude) user_situation = (self.request.user.userprofile.longitude, self.request.user.userprofile.latitude) return geodesic(post_situation, user_situation).km user/models.py class UserProfile(models.Model): ... latitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0') longitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0') -
Deploy Django in intranet / Django production tipps
I have some experience with tinkering around with Django to make things simply work but I lack experience in deployments. I am able to access my service in the LAN, however I am not sure if this is a good and secure way of doing it. Is Django suitable for small intranet applications? How can i prevent access from outside of the intranet? What are the risks running a standard Django project in a LAN by calling runserver 0.0.0.0 8000 on a windows machine? Are there options for SSL in LAN? Are there other problems or tipps to consider? -
Django test throwing an error on response status code 404
I'm following along with a lecture on django testing and this is one of the tests: def test_invalid_flight_page(self): max_id = Flight.objects.all().aggregate(Max("id"))["id__max"] c = Client() response = c.get(f"/flights/{max_id + 1}") self.assertEqual(response.status_code, 404) When I run manage.py tests it throws an error on this test, essentially saying there is no matching flight: Creating test database for alias 'default'... System check identified no issues (0 silenced). .......E.. ====================================================================== ERROR: test_invalid_flight_page (flights.tests.FlightTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\sarah\Desktop\airline\flights\tests.py", line 68, in test_invalid_flight_page response = c.get(f"/flights/{max_id + 1}") File "C:\Python\Python385\lib\site-packages\django\test\client.py", line 732, in get response = super().get(path, data=data, secure=secure, **extra) File "C:\Python\Python385\lib\site-packages\django\test\client.py", line 393, in get return self.generic('GET', path, secure=secure, **{ File "C:\Python\Python385\lib\site-packages\django\test\client.py", line 470, in generic return self.request(**r) File "C:\Python\Python385\lib\site-packages\django\test\client.py", line 709, in request self.check_exception(response) File "C:\Python\Python385\lib\site-packages\django\test\client.py", line 571, in check_exception raise exc_value File "C:\Python\Python385\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Python\Python385\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\sarah\Desktop\airline\flights\views.py", line 21, in flight flight = Flight.objects.get(pk=flight_id) File "C:\Python\Python385\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Python\Python385\lib\site-packages\django\db\models\query.py", line 429, in get raise self.model.DoesNotExist( flights.models.Flight.DoesNotExist: Flight matching query does not exist. ---------------------------------------------------------------------- Ran 10 tests in 0.120s FAILED (errors=1) Destroying test database for alias 'default'... But … -
Django: Filtered Queryset only displaying stale data
I am new to python/django and have been creating a web application that filters data displayed based on group. Everything works perfectly from a create, edit and update side if I am logged in as a user with 'admin' as their group however if I login to any of the other groups it fails to display recently inserted data. The below code filters my "tasks" page based on what group is assigned to the user and displays the correct data. @login_required(login_url='login') @allowed_users(allowed_roles=['admin', 'Systems', 'Energy', 'Support', 'Environmental', 'Security', 'Safety', 'Projects', 'MRO']) def tasks(request): tasks = Task.objects.all().order_by('task', '-status', '-submission_date').distinct('task') group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group == 'Systems': tasks = Task.objects.filter(team__name__contains = 'Systems').order_by('task', '-status', '-submission_date').distinct('task') if group == 'Energy': tasks = Task.objects.filter(team__name__contains = 'Energy').order_by('task', '-status', '-submission_date').distinct('task') if group == 'Support': tasks = Task.objects.filter(team__name__contains = 'Support').order_by('task', '-status', '-submission_date').distinct('task') if group == 'Environmental': tasks = Task.objects.filter(team__name__contains = 'Environmental').order_by('task', '-status', '-submission_date').distinct('task') if group == 'Security': tasks = Task.objects.filter(team__name__contains = 'Security').order_by('task', '-status', '-submission_date').distinct('task') if group == 'Safety': tasks = Task.objects.filter(team__name__contains = 'Safety').order_by('task', '-status', '-submission_date').distinct('task') if group == 'Projects': tasks = Task.objects.filter(team__name__contains = 'Projects').order_by('task', '-status', '-submission_date').distinct('task') if group == 'MRO': tasks = Task.objects.filter(team__name__contains = 'MRO').order_by('task', '-status', '-submission_date').distinct('task') myFilter = TaskFilter(request.GET, queryset=tasks) tasks = myFilter.qs … -
Not finding static files Django Project in Apache
I read many questions about this, but still no able to solve it. i would appreciate any help. I am following the great tutorial of Corey Schafer https://www.youtube.com/watch?v=Sa_kQheCnds to deploy my django app in Linode. But I can't serve the static files. I already did manage.py collectstatic and here is my configuration: Settings.py /etc/apache2/sites-available/komposair.conf I copy and paste the lines of the tutorial (changed neccessary lines) My folder configuration Permissions I also changed the owner and permission (www-data) as explain in the tutorial and they seem fine. Still when I load my site in the console I get (refering to the static files): ******/:1 Failed to load resource: the server responded with a status of 404 (Not Found) Templates In my templates this is how I serve the static files (they worked fine in development) {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Add font awesome --> <script src="https://kit.fontawesome.com/37e8b20514.js" crossorigin="anonymous"></script> <!-- Custom styles and js for this template --> <link href="{% static 'melody/simple-sidebar.css' %}/" rel="stylesheet"> <script src="{% static 'melody/utils.js' %}/"></script> My urls Apache Error Log I found this line... AH01276 Cannot serve directory /home/juancopi81/komposair/static/: No matching DirectoryIndex (index.php...) found, and server-generated directory index forbidden by Options directive -
Form Post malfunction on Django login
I am trying to implement a login section on the landing page of a Django login but it keeps sending the data to the wrong view and making it appear in the url. In http://127.0.0.1:8000/ I have a pop up with this form <form action="login" method="POST"> {% csrf_token %} <input type="text" name="username" placeholder="Username"> <input type="password" name="password" placeholder="Password"> <input type="submit" value="Login"> </form> in urls.py i have path('', views.index, name='index'), path('register/', views.register, name='register'), path('login/', views.loginPage, name='login'), path('news/', views.news, name='news'), path('profile/', views.profile, name='profile'), path('friends/', views.friends, name='friends') etc and the view for log in it def loginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.info(request, 'Servus'+ username) return redirect('profile') else: messages.info(request, 'Username or Password is incorrect!') So ideally it should log in the user and then send it over (create a GET request) to the profile view. However it does not do that. It opens renders the friends view and creates a url that looks like this: http://127.0.0.1:8000/friends/?csrfmiddlewaretoken=roLEhPRiXf6QeX1rhsiWQ0D67gSfc4PCxvyc7YyxnEIBRfV3bOUzPbyFJUG026ys&username=C*****&password=H****** (I added **** to hide the username and password) However I am able log the user in if I create a separate url for the login and change the form action … -
Using Token Authentication in django, but i need to get user session length?
I am using a otp based user login in DRF and generating a Token for user signup and otp is matched , now i want to calculate the session length of each user on the platform , how to do this in DRF. -
Is it safe to store Auth Tokens directly in Redux?
I am currently building a seller dashboard for a local ecommerce platform and using Django for my backend and React for my frontend. I have Django Rest Framework serving my backend API to the frontend so my question is, What is the safest way of storing the token served from Django Rest Framework in Redux so that I can use it to talk to the backend. Is it a security risk by storing the token as a normal variable in the current Redux state? Never worked with Token auth before so curious to know if there is any security risk with how I would go about building it. -
How to add another field in HTLM forms in django like admin TabularInline
In django admin after added TabularInline the admin page shows "Add another " button in a specific model's add form, When user click that it will add another field and input box to the HTML form I need that in normal template how to do that Thanks Advance, Vignesh Karthik -
How do I save FileField using model's pk in Django
I created an upload function that saves an uploaded file using the pk or id. But I get a None as a folder in the instance.id. I followed the instruction on the post and I discovered that if you are using the id, you need to make sure the model instance was saved before you upload the file. Otherwise, the id hasn’t been set at that point and can’t be used. How can get the id instead of None..? I want to save the uploaded file to "media/id/uploaded_file upload_to function def upload_to(instance, filename): print('ID', instance.pk) return os.path.join(str(instance.id), filename) My model.py class MyVideo(models.Model): videofile= models.FileField(upload_to=upload_to) name= models.CharField(max_length=500) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name + ": " + str(self.videofile) -
Serializer all models with one serializer
I'm new in django and during my studies i came across the issue of a unique serialization. Normally, I would create one serializer for each model created, but i want to create just one serializer for all models. In a dynamic way. Example: models.py class Group(Base): __tablename__ = 'groups' id = sa.Column(sa.Integer(), primary_key=True, autoincrement=True) name = sa.Column(sa.String()) class User(Base): __tablename__ = 'users' id = sa.Column(sa.Integer(), primary_key=True, autoincrement=True) name = sa.Column(sa.String()) fullname = sa.Column(sa.String()) password = sa.Column(sa.String()) _group_id = sa.Column('group_id', sa.Integer(), sa.ForeignKey('groups.id')) group = sa.orm.relationship(Group, backref='users') class Address(Base): __tablename__ = 'addresses' id = sa.Column(sa.Integer(), primary_key=True, autoincrement=True) email_address = sa.Column(sa.String(), nullable=False) _user_id = sa.Column(sa.Integer(), sa.ForeignKey('users.id')) user = sa.orm.relationship(User, backref='addresses') I try to do something like this: class GeneralSerializer(serializers.ModelSerializer): class Meta: model = None session = session fields = '__all__' But I'm getting a NoneType as an answer: sqlalchemy.exc.NoInspectionAvailable: No inspection system is available for object of type <class 'NoneType'> Which makes sense, considering the skeleton of the serializer. I know this question was asked before, but I found no solution in the previous topic and nowhere else. I will probably have to work with the serializer init, but I still have no idea how to do it. I don't want a ready … -
Correct way of saving objects with URLField
I have a model class KeyWord class KeyWord(models.Model): keyword = models.CharField(verbose_name="Topic",max_length=50) link = models.URLField(verbose_name = "Next Best Action", max_length=500,null=True) def __str__(self): return self.keyword If i create an object like this: KeyWord.objects.create(keyword="hello",link="world") Ideally an error be raised because i am assigning normal text to link field which is a URLField but object created successfully? Which field should i use or what should i do so that objects with valid links are saved? -
How can query a collection in mongodb using django and djongo
I have a django application with mongodb as a backend database and djongo as a connector. I created a collection in the database using mongodb compass and I want to query the data in that collection. Is it possible or I need to have the data in a django model