Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django CBV - in CreateView how do I save to a FileField after the object is created?
I have a Django model that looks like this (some fields removed for brevity). Notably, the FileField is renaming the file using the ID of the object as the name to avoid collisions. class Product(models.Model): name = models.CharField(max_length=255, db_index=True) ... storage_path = 'foo/' image = models.FileField(default="foo/default.png", upload_to=upload_path, blank=True, null=True) def upload_path(instance, filename): """ We don't care what filename the user gave us, use the ID. """ _, ext = os.path.splitext(filename) if hasattr(ext, 'lower'): ext = ext.lower() path = getattr(instance, 'storage_path', 'UNCATEGORIZED') return "{}/{}{}".format(path, instance.id, ext) When using a CreateView however, I can't simply include the image field because when the form is being saved (and the file is being uploaded) the object isn't created yet, so the ID is None. So I end up saving None.png everytime. I have a working solution, but it seems to not be very elegant. class ProductCreate(CreateView): model = Product fields = ['name', 'image'] def dispatch(self, request, *args, **kwargs): # We need to save the image after the object is saved because we # use the ID in the image filename self.image_file = request.FILES.pop('image', None) if isinstance(self.image_file, list) and len(self.image_file) > 0: self.image_file = self.image_file[0] return super().dispatch(request, *args, **kwargs) def form_valid(self, form): ret = super().form_valid(form) … -
Display recent public tweets of a user upon entering his/her twitter handle
I am new to django and I am trying to create an application which takes a twitter user handle as input and and displays the recent tweets.I was able to write a python code for the problem using tweepy but I am not able to implement the same using django.I wrote the HTML code for the search box and the code for displaying the results.I am having problems rendering the templates using views. Template- index.html <form method = "GET" action ="{% url 'tweets:search' %}"> <input name = "q" placeholder = "search..."> <button class = "btn btn-success" type = "submit">Search</button> </form> please help me out in writing views and results.html template to display results. -
Django admin terrible performance get_form queryset filter when adding order_by
I'm encountering some terrible performance issues when trying to filter a forms queryset. I'm trying to filter a Model where a relationship already exists. The code is successful. But my queryset is not ordered. The moment I change to form.base_fields['sharepoint_mandate'].queryset = Sharepoint_Mandate.objects.filter(mandate_mapping_2__isnull=True).order_by('product_name') the query now takes 25 seconds Please help models.py class Mandate_Mapping_2(Trackable): mandate_mapping_id = models.AutoField(primary_key=True) sharepoint_mandate = models.ForeignKey(Sharepoint_Mandate, on_delete=models.CASCADE) sharepoint_product = models.ForeignKey(Sharepoint_Product, on_delete=models.CASCADE) admin.py @admin.register(Mandate_Mapping_2) class ChampMandateMapping2Admin(admin.ModelAdmin): list_display = ['sharepoint_mandate', 'sharepoint_product', 'approved'] def get_form(self, request, obj=None, **kwargs): form = super(ChampMandateMapping2Admin, self).get_form(request, obj, **kwargs) if 'change' in kwargs: if not kwargs['change']: form.base_fields['sharepoint_mandate'].queryset = Sharepoint_Mandate.objects.filter(mandate_mapping_2__isnull=True) return form def get_queryset(self, request): return super().get_queryset(request).select_related( 'sharepoint_product', 'sharepoint_mandate', ) -
Display an icon according to the file type
I want to show an icon for my attachment (according to file type). def __str__(self): return format_html('<a href="%s"><img src="%s" width="300" height="300" /></a></br>' % (self.attach_file.url,icon/file/path,)) for this I have to keep file icons. is there any better way to acquire the icons in django? -
Call a class instance and pass to celery polling task
I'm unable to call a class instance of APIClient and return the logged in object and pass to a celery task for long polling. My task will not work unless the api clients session_token has been set. Each time I call APIClient I create a new instance which subsequently logs me into the API. The problem is I will get blocked for too many login attempts. I need to return a logged in Instance of APIClient that I can use to poll get_balance function. Can this be done with global or instance variables and how to I pass to get_balance? What would the solution be to also create a new "logged in" instance of APIClient every 6 hours? from __future__ import absolute_import, unicode_literals from matchbook import APIClient from celery import shared_task from .secrets import username, password def get_client(): api = APIClient(username, password) if api.session_token is None: api.login() session_token = api.session_token user_id = api.user_id api.set_session_token(session_token,user_id) try: api.account.get_account(True) except: session_token = None return api def set_client(api): if api.session_token is not None: print('session token set',api.session_token) return api @shared_task #runs every 5 seconds def get_balance(api): api = APIClient(username,password) r = api.account.get_account(balance_only=True) print(r) -
Copying class variables and renaming them through metaclass
Can you copy a set of class variables through inheritance, but renamed the variables through a metaclass or decorator? I attempted to do this and the __new__ method wasn't even hit. Also, wouldn't this result in MRO resolution errors if trying to use both base classes in a mixed base model if you wanted inheritance of both field sets. e.g. - class Base(models.Model): field = ... field2 = ... @prefix("new") class Derivative(Base): pass # Results in new_field, new_field2, ... print(Derivative.__dict__) # Should show the new_field prefixes... For the MRO issue: class MROProblem(Base, Derivative): pass Yes, I actually have a use case for the field renames.... To ensure clashing prevention without ton of code repetition. -
Form not submitting due to datetime field
I added a datetimefield to my form that creates a lesson. It was working perfectly before, but now with the datetimefield added, the form donsn't pass as valid and create the object anymore. I believe the issue is somewhere in my datetimefield model variable, but I am unsure what the exact issue is. I would appreciate any help with this. models.py lesson_date_time = models.DateTimeField(blank=True, auto_now=False, auto_now_add=False) forms.py lesson_date_time = forms.DateTimeField(widget=forms.DateTimeInput(attrs={'class' : 'form-control', 'type':'datetime-local', 'required' : 'True'})) -
Display different content for logged in user [duplicate]
This question already has an answer here: How to make generic ListView only show user's listing? 1 answer I would like to filter my CBV for the current logged in user. So for all of the context I would like the user to see only what he posted Views.py class DashboardListView(LoginRequiredMixin,ListView): model = Links template_name = 'dashboard/home.html' context_object_name ='links_list' paginate_by = 5 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['dashboard_list']= Dashboard.objects.filter()[:5] context['todo_list']= Todo.objects.all().order_by('-pk')[:6] context['PasswordUsername_list']= PasswordUsername.objects.all()[:6] return context Thanks ! -
what database to use mysql or sqllite within django project
I recently started learning django's framework to use within a web application project. most of the tutorials im watching are all using the default database sqlite3. So i have been doing some research on the differences between the 2 so i know that sqlite is a simplified version of mysql in short. Yet all the specific mysql django tutorials are a few years old at the least which makes me feel as if this is more of the old way to do things rather than the current. I'm wondering what the best database would be to use for my case and how i would create items in that database using django or would it follow the same process as creating items in a sqlite database. I appreciate this isn't the clearest question and hard to give recommendations without knowing in depth what i'm creating, however any pointers, links to helpful resources or some kind soul that is willing to have a convo with me about it as i find it hard getting across what im asking for in this format -
Django: Could not parse the remainder: '"{%' from '"{%'
I'm using Django and I'm getting an "Error during template rendering": "Could not parse the remainder: '"{%' from '"{%' ". Here is the line of code causing the problem: {% with memberName="Java" memberPhoto="{% static 'sbs/images/avatar.jpg' %}" memberYear=80 memberBio="Lorem ipsum dalas dolores blabla" %} {% include "sbs/_member.html" %} {% endwith %} It is happening because of the image, but how could i put the image as a variable here without getting this error? Thanks in advance! -
Clear Filter with django-filter and django-tables2 (CBV)
Taken from another thread which didn't detail the 'Class Based View' example. Check and clear filters with django-filter What would the CBV of the following code look like: def product_list(request): f = ProductFilter(request.GET, queryset=Product.objects.all()) has_filter = any(field in request.GET for field in set(f.get_fields())) return render(request, 'my_app/template.html', { 'filter': f, 'has_filter': has_filter }) I have tried numerous iterations added to my CBV code: from django_filters.views import FilterView from django_tables2.views import SingleTableMixin class FilteredPersonListView(SingleTableMixin, FilterView): table_class = PersonTable model = Person template_name = 'template.html' filterset_class = PersonFilter But cannot get the table to render once included. Any help greatly appreciated. Dan -
How do you stop a StreamingHttpResponse in django when the client disconnects?
My django server serves a video feed, as a jpeg stream, one frame at a time. It looks like this: class VideoCamera(): def __init__(self): # code def get_frame(self): # code return frame def gen(camera): while True: yield camera.get_frame() def view_cam(request): return StreamingHttpResponse(gen(VideoCamera()), content_type="multipart/x-mixed-replace;boundary=frame") It's a live camera feed, so there's no end to the stream. I need it to be interrupted when the client disconnects, but so far, I can't figure out how to detect that a client disconnected. I tried adding this to my VideoCamera class: def __del__(self): print("__del__") and when the client disconnects, it does fire, pretty much immediately, but for some strange reason, what it does is create a new instance of VideoCamera(), and then immediately fire its __del__ method - it doesn't actually fire my main instance's __del__ method, so my instance keeps running indefinitely, eating up CPU. Am I missing something? -
How can I use the ModelChoiceField in a list with the same values in the OPTION and VALUE OPTION e select?
How can I use the ModelChoiceField in a list with the same values in the OPTION and VALUE OPTION e select? I need queryset to return to select the same values for the list and VALUE of the options Model class Produto(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) nome = models.CharField(max_length=255) referencia = models.CharField(max_length=50) def __str__(self): return self.nome + ' - ' + self.referencia Form class FormItem(forms.Form): produto = forms.ModelChoiceField(queryset=None, label='Produto', widget=forms.Select(attrs={'placeholder': 'Produto', 'class': 'input select2'})) def __init__(self, *args, **kwargs): super(FormFaturaItem, self).__init__(*args, **kwargs) self.fields['produto'].queryset = Produto.objects.all() Form result <select> <option value="dd3e2aff-924d-4945-9929-3d37b81b3ebb">KIT MATERNIDADE - 9049</option> </select> Expected result <select> <option value="KIT MATERNIDADE - 9049">KIT MATERNIDADE - 9049</option> </select> -
easy_thumbnails generating thumbnail for variable but not iterator
I have easy_thumbnails setup and working correctly, as tested by passing it a valid file path via a local variable. This is the code I am using in my template: {% load thumbnail %} {% for instance in prods %} {% with testloc="images/test.jpg" %} {% thumbnail testloc 250x250 crop="autocrop" upscale as thumb %} <img src="{{ thumb.url }}" width="250" height="250"> {% endwith %} {% endfor %} As per the easy_thumbnails documentation, the image string is relative to your default storage (usually the MEDIA_ROOT setting) Indeed, within my MEDIA_DIR, I have a directory called images, and within that a valid jpeg file called test.jpg With my template set to pass testloc as the image string to thumbnail, everything works as it should, and my thumbnail is generated and displayed. The problem is when I try to use the iterator to display thumbnails for each image returned via the view. No matter what I try, I get an error that The source file does not appear to be an image The code I am using is {% load thumbnail %} {% for instance in prods %} {% with testloc="images/test.jpg" %} {% thumbnail instance.image_path 250x250 crop="autocrop" upscale as thumb %} <img src="{{ thumb.url }}" … -
I wan't to have both public and private access to same Django REST API
I want to have both public and private access to /api/listings so that I can have read-only access on my frontend on all listings publicly. I also want to read, update and delete own listings on an authenticated user which I already know how to do (commented out, I know I need to change the permission to "AllowAuthenticated"). Do I have to create a second API and how can I do that since the public API is already taking the /api/listings URI, thanks # api.py class ListingViewSet(viewsets.ModelViewSet): permission_classes = [ permissions.AllowAny, ] serializer_class = ListingSerializer # This is how I can publicly access the api queryset = Listing.objects.all() # This is how I can have private access # def get_queryset(self): # return self.request.user.listings.all() # def perform_create(self, serializer): # serializer.save(owner=self.request.user) # serializers.py class ListingSerializer(serializers.ModelSerializer): class Meta: model = Listing fields = '__all__' -
entering emoji fails in django + mysql even with utf8mb4_unicode_ci
I'm trying to insert an emoji into my title column in my django + MySQL app. I already went into PhpMyAdmin and I did the following: changed the charset of the collumn to utf8mb4_unicode_ci inserted an emoji But when I open this object in the django admin, the emoji is missing: And if I try to enter the emoji and save, I get this exception: MySQLdb._exceptions.OperationalError: (1366, "Incorrect string value: '\\\\xF0\\\\x9F\\\\x92\\\\xA9' for column 'title' at row 1") What am I missing? -
Django custom creation manager logic for temporal database
I am trying to develop a Django application that has built-in logic around temporal states for objects. The desire is to be able to have a singular object representing a resource, while having attributes of that resource be able to change over time. For example, a desired use case is to query the owner of a resource at any given time (last year, yesterday, tomorrow, next year, ...). Here is what I am working with... class Resource(models.Model): id = models.AutoField(primary_key=True) class ResourceState(models.Model): id = models.AutoField(primary_key=True) # Link the resource this state is applied to resource = models.ForeignKey(Resource, related_name='states', on_delete=models.CASCADE) # Track when this state is ACTIVE on a resource start_dt = models.DateTimeField() end_dt = models.DateTimeField() # Temporal fields, can change between ResourceStates owner = models.CharField(max_length=100) description = models.TextField(max_length=500) I feel like I am going to have to create a custom interface to interact with this state. Some example use cases (interface is completely up in the air)... # Get all of the states that were ever active on resource 1 (this is already possible) Resource.objects.get(id=1).states.objects.all() # Get the owner of resource 1 from the state that was active yesterday, this is non-standard behavior Resource.objects.get(id=1).states.at(YESTERDAY).owner # Create a new state for … -
I'm trying to setup a django web server but it does not work
Hello guys Ihave days trying to setup a django web server on Windows 8.1 everything is installed correctly wsgi with the correct versión, apache Windows with update and Python 3.6 when I try to Access apache log show me this error: [Tue Feb 19 15:40:53.622597 2019] [wsgi:error] [pid 4716:tid 1104] [client 192.168.1.229:50746] mod_wsgi (pid=4716): Failed to exec Python script file 'C:/uno/proyecto/proyecto/wsgi.py'. [Tue Feb 19 15:40:53.622597 2019] [wsgi:error] [pid 4716:tid 1104] [client 192.168.1.229:50746] mod_wsgi (pid=4716): Exception occurred processing WSGI script 'C:/uno/proyecto/proyecto/wsgi.py'. [Tue Feb 19 15:40:53.623600 2019] [wsgi:error] [pid 4716:tid 1104] [client 192.168.1.229:50746] Traceback (most recent call last):\r [Tue Feb 19 15:40:53.623600 2019] [wsgi:error] [pid 4716:tid 1104] [client 192.168.1.229:50746] File "C:/uno/proyecto/proyecto/wsgi.py", line 12, in <module>\r [Tue Feb 19 15:40:53.623600 2019] [wsgi:error] [pid 4716:tid 1104] [client 192.168.1.229:50746] from django.core.wsgi import get_wsgi_application\r [Tue Feb 19 15:40:53.623600 2019] [wsgi:error] [pid 4716:tid 1104] [client 192.168.1.229:50746] ModuleNotFoundError: No module named 'django'\r My virtualenv is called uno and the Project is called proyecto I do not know why is happening i have an other machine and it Works fine with this configuration. httpd.conf LoadFile "c:/users/srv/appdata/local/programs/python/python36/python36.dll" LoadModule wsgi_module "c:/users/srv/appdata/local/programs/python/python36/lib/site-packages/mod_wsgi/server/mod_wsgi.cp36-win_amd64.pyd" WSGIPythonHome "c:/users/srv/appdata/local/programs/python/python36" WSGIScriptAlias / "C:\uno\proyecto\proyecto\wsgi.py" WSGIPythonPath "C:\uno\proyecto" <Directory "C:\uno\proyecto"> <Files wsgi.py> Require all granted </Files> </Directory> Any idea ? -
Django ORM Accessing related many-to-many objects through queryset
In my Django app, I have the following two models for events which can be given an arbitrary number of tags. class Tag(models.Model): # ... class Event(models.Model): # ... tags = models.ManyToManyField("Tag") I also have a page where a user should be able to select a number of tags and then view all events associated with that tag. Given a list of tag IDs, can I use the Django ORM to get a list of (distinct) events associated with at least one of the given tags? If not, I also tried achieving this with the following raw SQL event.objects.raw(""" SELECT * FROM app_name_event_tags t WHERE t.tag_id IN %s """, selected_tag_ids) There are two problems with this: 1) The events returned won't be distinct 2) My syntax for the placeholder for the list selected_tag_ids is incorrect -
Sort View Alphabetically with Django View
I have a view that returns a model called Solution. def index(request): things = Solution.objects.all() return render(request, 'home.html', { 'things': things, }) How would I go about having this sorted alphabetically? I saw that there is this option: Main.objects.order_by('name') How could I fit that into my current view? -
Django: re-render form on POST without refreshing page
Does anyone know how to re-render a django form upon POST, without refreshing the page? I've got my form in a modal popup. -
Form clean method not returning as valid
I created a clean form function to check if the user's form input of lesson_instrument and lesson_level, match the user object values of instrument1 and level1. The form is intended to pass if lesson_instrument == instrument1, and level1 >= lesson_level. However, the form always appears to fail, even when the logic should pass. I am also wondering if in the clean function is the right place to perform this logic or if it should be done in the view. Any help in making the form valid would be appreciated. forms.py def clean(self): cleaned_data = super(LessonForm, self).clean() # Check that the user is allowed to teach that instrument and level lesson_instrument = self.cleaned_data.get("lesson_instrument") lesson_level = self.cleaned_data.get("lesson_level") if lesson_instrument == self.request.user.instrument1: level1 = self.request.user.level1 if lesson_level == "Beginner": lesson_level = 1 if level1 == 'Beginner': level1 = 1 if level1 < lesson_level: raise forms.ValidationError("Teacher not authorized to teach at that level") if level1 != 'Beginner': raise forms.ValidationError("Instrument level is not beginner") if level1 == 'Advanced': level1 = 2 if level1 < lesson_level: raise forms.ValidationError("Teacher not authorized to teach at that level") if level1 != 'Advanced': raise forms.ValidationError("Instrument level is not advanced") if level1 == 'Intermediate': level1 = 3 if level1 < lesson_level: … -
Any good up to date existing Django auction projects?
I'm learning Django and am interested in developing an auction site. Can anyone recommend any existing Django based auction projects that I can use and modify or install and play around with? Or alternately a solid marketplace type project that could be modified for auction purposes? I've found some Django auctions on GitHub etc, but most look out of date or not very developed. -
Why the string sent by POST method is wrongly parsed in Django backend?
The following code works well in Jupyter Notebook: string = "NUM,AIRLINE_ARR_ICAO,WAKE,SIBT,SOBT,PLANNED_TURNAROUND,DISTANCE_FROM_ORIGIN,DISTANCE_TO_TARGET\n1,VLG,M,2016-01-01 04:05:00,2016-01-01 14:10:00,45,2000,2000\n2,VLG,M,2016-01-01 04:05:00,2016-01-01 14:10:00,45,2000,2000\n3,VLG,M,2016-01-01 04:05:00,2016-01-01 14:10:00,45,2000,2000\n" llist = np.array(string.splitlines()) new = [] for i in range(0,len(arr)): line = arr[i].split(",") new.append(line) pd.DataFrame(new[1:],columns=new[0]) But when I integrate it in Django app, it incorrectly parses the inout string csvData. The csvData is sent using POST method from React.js app to Django backend: '&csvData='+JSON.stringify(this.state.csvData) from the front-end. This is how I read csvData in Django (very similar to the code that I tested in Jupiter Notebook) csvData = str(request.GET.get('csvData')) print("CSV", csvData) arr = np.array(csvData.splitlines()) new = [] for i in range(0,len(arr)): line = arr[i].split(",") new.append(line) X = pd.DataFrame(new[1:],columns=new[0]) print("X",X.head()) The line print("CSV", csvData) prints the string that I used in Jupyter Notebook!!! Result: X Empty DataFrame Columns: ["NUM,...,2000, 2000\n14, VLG, ...] [0 rows x 148 columns] The version of Numpy is the same. I use the same machine for both cases. -
Passing parameter from AJAX to DJANGO
I want to pass a parameter from javascript into the django views using window.location. In this case the variable 'query' which is the string 'hi'. How would I go about doing this? Below is what isn't working :) yet everything works fine when I try without a parameter. Help? views.py def error(request, query): print(query) return render(request, 'error.html') html $(document).ready(function(){ $("#butt").click(function(){ $.ajax({ type: "get", url: 'profile', datatype:'json', data: { 'profname': 'jilsmith', }, success: function(data) { if(data.status == 0){ alert("error page"); var query = "hi"; window.location = data.url(query); } if(data.status == 1){ alert("profile page"); window.location = data.profile } } }); }); });