Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - For loop gives results for only one item
I have the following ListView: class SongList(generic.ListView): model = models.Song template_name = 'videos/song_list.html' context_object_name = 'song_list' Where I am overwriting get_context_data: def get_context_data(self, **kwargs): context = super(generic.ListView, self).get_context_data(**kwargs) And now I want to perform some operations on every song in order to display it on my template, so I do: for song in context['song_list']: song = models.Song.objects.get(title=song) lyrics_list = models.Song.objects.get(title=song).lyrics_as_list() import pymorphy2 morph = pymorphy2.MorphAnalyzer() lyrics_list_lemma = [] for word in set(lyrics_list): parsed_word = morph.parse(word)[0] result = { 'word_original': word, 'word_normalized': parsed_word.normal_form, } lyrics_list_lemma.append(result) context['lyrics_lemma'] = lyrics_list_lemma context['count'] = len([k for d in lyrics_list_lemma for k in d.keys() if k == 'word_normalized']) return context I get the correct values for lyrics_list_lemma and count, but only for one song. Shouldn't I be getting it for all the songs, since it falls under the for loop? -
TypeError at /register/new_reg/ register() got an unexpected keyword argument 'name'
i was just checking this code please help me in finding this error def register(request): if request.method == 'POST': name = request.POST.get('name') phone = request.POST.get('phone') register(name=name,phone=phone).save() return render(request, 'reg.html') models ------- from django.db import models # Create your models here. class register(models.Model): name = models.CharField(max_length=200) phone = models.CharField(max_length=200) please resolve this issue please help me to find whats wrong with it and thanks in advance -
How to modify upload function in django-ckeditor?
I am using django-ckeditor and want to restrict some file extension or restrict some size of files in it. How can i tweek or modify the default upload mechanism in this? Any help is appreciated. Thanks in advance -
how to reduce Django package size?
my architecture is Django, Zappa, AWS lambda(+ api gateway, cloudwatch, more....). I know that maximum size of a function code package for lambda is 50 MB. but now my package is 47MB.. how to diet my package? i need some skills. -
Is it possible to display several objects using a detail view?
I'm very new to Django, and posting here so please excuse my ignorance and code formatting (got messed up when I pasted). I created a very basic list and detail view where I have two models, I pass the ID from an object in model1 into the detail view and return all model2 objects, where "execid" matchs model1s ID. However, there will be several objects in model2 that match the ID passed from model1. I get the error "get() returned more than one Exec -- it returned 2!" Which I've understood to mean that a detail view cannot pass more than one object in. My views: class tradeListView(ListView): def get_queryset(self): return Trade.objects.filter(username=self.request.user) template_name = 'dashboard/trade_list.html' context_object_name = "trade" class execDetailView(DetailView): template_name = "dashboard/exec_list.html" def get_queryset(self): return Exec.objects.filter(username=self.request.user) def get_object(self): id_ = self.kwargs.get("id") return get_object_or_404(Exec, execid=id_) my models: class Trade(models.Model): exittime = models.DateTimeField(auto_now=False, auto_now_add=False, db_column='exittime') entrytime = models.DateTimeField(auto_now=False, auto_now_add=False, db_column='entrytime') duration = models.BigIntegerField(db_column='duration') ticker = models.CharField(max_length=100, db_column='ticker') direction = models.CharField(max_length=100, db_column='direction') quantity = models.IntegerField(db_column='quantity', default=None) entry = models.DecimalField(decimal_places=2, max_digits=100, db_column='entry') exit = models.DecimalField(decimal_places=2, max_digits=100, db_column='exit') cost = models.DecimalField(decimal_places=2, max_digits=100, db_column='cost', default=0) percent = models.DecimalField(decimal_places=3, max_digits=100, db_column='percent', default=0) profit = models.DecimalField(decimal_places=2, max_digits=100, db_column='profit') username = models.CharField(max_length=100, db_column='username') def get_absolute_url(self): return reverse('execdetail', kwargs={'pk': … -
Crashed by app and tried to re-load it, however getting new weird Django Requests error
My Django app was running before. My system crashed and I reloaded the app from Github. Currently, my Django app has package 'requests', however, it can't seem to recognize this requests line in my settings file settings.py MIDDLEWARE = [ ... 'request.middleware.RequestMiddleware', ] Here is the error that I get: ModuleNotFoundError: No module named 'request.middleware' -
How to use Django modelformset_factory() to sve multiple forms properly. I get the error "form not valid"
I am using modelformset_factory() to make updates to multiples rows for a model based on user input. I create the form and send the data to views, but upon calling my form myForm(request.POST) I get an error:form not valid. For some reason, the submitted form data is not recognized when I pass request.POST to the new form instance. I did verify that request.POST contains the various forms with correct input data. def foo(request): forms = modelformset_factory( model=MyModel, form=MyForm, ) forms = forms(queryset=MyModel.objects.filter(name__startswith="A")) ... if request.POST: formset = MyForm(request.POST) if formset.is_valid(): formset.save() else: print(formset.errors) How do I save a model formset properly? I have many forms that would be submitted at once. -
Django excel file upload function
I'm watching a youtube tutorial on how to upload excel files to your Django admin. I'm successfully uploading my excel files to my Django admin, but currently, I have to manually assign values to date_created and timestamp. I want the function to automatically assign them values once the file has been uploaded.I have done some search, but couldn't find any solution. models.py class Order(models.Model): item = models.CharField(max_length=30) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=30) address = models.CharField(max_length=100) date_created = models.DateTimeField('date_created', default=timezone.now(), blank=False, null=True) timestamp = models.DateTimeField(default=timezone.now(), blank=False, null=True) admin.py class IngredientsAdmin(ImportExportModelAdmin): list_display = ('item', 'user', 'name','address','date_created','timestamp') if request.method == 'POST': ingredients_resource = IngredientsReource() order = Order.objects.all() order.date_updated = timezone.now() dataset = Dataset() new_ingredients = request.FILES.get('myfile', None) if new_ingredients is None: messages.info(request, 'Please upload a file.') return render(request, 'upload.html') if not new_ingredients.name.endswith('xlsx'): messages.info(request, 'wrong format') return render(request, 'upload.html') imported_data = dataset.load(new_ingredients.read(),format='xlsx') for data in imported_data: value = Order( data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7] ) value.save() return render(request, 'upload.html') -
can i change my url() to path() in urls.py
i use path() in urls.py, but i want to know what is the code if i change it to url() i already try but i got error this is my url.py code path('activate/<uidb64>/<token>', views.VerificationView.as_view(), name="activate"), path('request-reset-link', views.RequestPasswordResetEmail.as_view(), name="request-password"), path('set-new-password/<uidb64>/<token>', views.CompletePasswordReset.as_view(), name="reset-user-password"), -
Django admin site adding "city object" instead of "City"
I'm trying to create a basic weather forecast site on Django and this error arises. I successfully made a "Cities" section but when adding any city name, "City Object 1" is added. This then creates errors when reading JSON from the API key. from django.db import models class City(models.Model): name = models.CharField(max_length=25) def _str_(self): #show the actual city name on the dashboard return self.name class Meta: #show the plural of city as cities instead of citys verbose_name_plural = 'cities' admin.py from django.contrib import admin from .models import City admin.site.register(City) -
AJAX form submission in Django
I keep receiving 'Not Ajax' as a response during my form submission. I have to be missing something small but I cannot see it... class VideoLikeView(View): def post(self, request): if request.is_ajax(): message = 'Ajax' else: message = 'Not Ajax' return HttpResponse(message) The AJAX code looks like this: $(function () { $("#like-form").submit(function (event) { $.ajax({ type: "POST", url: form.attr('action'), headers: {'X-CSRFToken': '{{ csrf_token }}'}, data: {'pk': $(this).attr('value'), success: function(response) { alert('Video liked'); }, error: function(rs, e) { alert(rs.responseText); } } }); }); }); And my HTML: <form id="like-form" action="{% url 'video-like' %}" method="post"> {% csrf_token %} <input name="like" type="hidden" value="{{ video.id }}"> <button type="submit"> <span class="video-options ml-auto fas fa-heart fa-2x m-2"></span> </button> </form> One question to add to this; how can I use an <input> in my form without using a <button>? I would like to use fontawesome icons but it seems I have to use a button to get the form to submit. -
Django Error of established connection was aborted by the software in your host machine
Problem after running my Django project on the local server I'm getting such error shown below. Please help me to solve the problem. Traceback (most recent call last): File "C:\Python38\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Python38\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Python38\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Python38\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Python38\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Python38\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine``` -
Is it okay to use `with` statement in opening the default storage in django?
I have researched about the with statement when handling files. According to what I have researched, with automatically closes opened files. This: file = open('file_path', 'w') file.write('hello world !') file.close() is the same as this: with open('file_path', 'w') as file: file.write('hello world !') My question is, can I use with in this django situation: (Assuming that input_file is already declared) output_file = default_storage.open(media_path, "w") output_file.write(input_file.read()) output_file.close() So basically, is this the same as that django situation? with default_storage.open(media_path, "w") as output_file: output_file.write(input_file.read()) -
Django Page not found, The current path, didn't match any of these
I have created a new template in my app menus.html The index path is working fine but when I added a new template that path is not working. Below is my url code in app urlpatterns = [ path('', views.index, name='index'), # url(r'^resto/menus/$', views.menus, name='menus') path('menu/', views.menus, name='menus'), ] The path specified in first line is working fine. I want to add a new view to the path (views.menus) Below is my urls.py from main app urlpatterns = [ path('admin/', admin.site.urls), path('resto/', include('resto.urls')) ] My menus.html file def menus(request): return HttpResponse("Test") I tried restarting the server but not worked, I am accessing this url http://localhost:8000/menus/ -
How to run compiled vue project in django
Previously, I know how to run Vue and Django (jinja2 template) together. by handling the custom delimiters, e.g delimiters: ['[[', ']]']. But for some reason, my supervisor just need to run the compiled vue project inside my existing django project. As we can see, the vue has npm run serve or yarn run serve to run it. Does django can handle this case? If yes, what I should do? In this case, we doesn't direct use the web server like nginx, apache, etc to run. -
Django rest framework: name 'Serializer' not defined
I have two models which have one to many relationship and I want to serialize the related fields on both ends. The models: class Mechanic(models.Model): name = models.CharField('Name', max_length=256) status = models.CharField('Status', choices=constants.MECHANIC_STATUS, default=constants.MECHANIC_STATUS[0][0], max_length=64) current_lat = models.CharField('Current Latitude', max_length=64) current_lng = models.CharField('Current Longitude', max_length=64) def __str__(self): return self.name class Service(models.Model): type = models.CharField('Service Type', choices=constants.SERVICE_TYPES, default=constants.SERVICE_TYPES[0][0], max_length=64) mechanic = models.ForeignKey(Mechanic, on_delete=models.CASCADE, related_name='services') vehicle_type = models.CharField('Vehicle Type', choices=constants.VEHICLE_TYPES, default=constants.VEHICLE_TYPES[0][0], max_length=64) charges = models.IntegerField('Charges') def __str__(self): return "{}, {}".format(self.mechanic, self.type) The serializers: class ServiceSerializer(serializers.ModelSerializer): mechanic = MechanicSerializer(read_only=True) # Throws an error class Meta: model = Service fields = ('id', 'type', 'mechanic', 'vehicle_type', 'charges') class MechanicSerializer(serializers.ModelSerializer): services = ServiceSerializer(many=True, read_only=True) class Meta: model = Mechanic fields = ('id', 'name', 'status', 'services', 'current_lat', 'current_lng') read_only_fields = ('id',) How do I approach this problem? I understand that I've created a cyclic dependency because both serializers depend on each other. Is there a better way to do it? -
Where is and how to edit the default Django homepage
Created a test demo project as below, how to edit the default Django homepage (or create my own homepage) that still using the same homepage url http://127.0.0.1:8000/? Note: I don't want to create a new app and put the homepage under the new app, because that could change the homepage url from http://127.0.0.1:8000/ to http://127.0.0.1:8000/new_app. -
In Python/Django, how do I configure default test settings?
I'm using Python 3.8 and Django 3. I have the following directory structure ... - manage.py + tests - __init__.py - factories.py - test_models.py - test_serializers.py + directory - test_settings.py I launch my tests using python manage.py test --settings=directory.test_settings Below are teh contents of my "test_settings.py" file ... from .settings import * class DisableMigrations(object): # ref: https://stackoverflow.com/a/28560805/12578202 def __contains__(self, item): return True def __getitem__(self, item): return None How do I configure my test settings file above to be default so that I can run tests simply by doing python manage.py test -
How can I do parallel tests in Django with Elasticsearch-dsl?
Has anyone gotten parallel tests to work in Django with Elasticsearch? If so, can you share what configuration changes were required to make it happen? I've tried just about everything I can think of to make it work including the solution outlined here. Taking inspiration from how Django itself does the parallel DB's, I currently have created a custom new ParallelTestSuite that overrides the init_worker to iterate through each index/doctype and change the index names roughly as follows: _worker_id = 0 def _elastic_search_init_worker(counter): global _worker_id with counter.get_lock(): counter.value += 1 _worker_id = counter.value for alias in connections: connection = connections[alias] settings_dict = connection.creation.get_test_db_clone_settings(_worker_id) # connection.settings_dict must be updated in place for changes to be # reflected in django.db.connections. If the following line assigned # connection.settings_dict = settings_dict, new threads would connect # to the default database instead of the appropriate clone. connection.settings_dict.update(settings_dict) connection.close() ### Everything above this is from the Django version of this function ### # Update index names in doctypes for doc in registry.get_documents(): doc._doc_type.index += f"_{_worker_id}" # Update index names for indexes and create new indexes for index in registry.get_indices(): index._name += f"_{_worker_id}" index.delete(ignore=[404]) index.create() print(f"Started thread # {_worker_id}") This seems to generally work, however, there's some … -
Django: When to put code in serializers.py or views.py
I am kind of confused about when should I put code in serializers.py or views.py. My understanding is that serializers.py is where data is manipulated + converted between front and backend. But so far, my understanding is that only the validation function and maybe a Meta class need to be in serializers.py. I feel like I can just manipulate the database directly in views.py. Like, I can just import the model in views.py and then do datModel.objects.create() or datModel.objects.get().someAttribute = somethingNew. -
How to write a Post method to update the quantity of items in Cart
I need help writing a post method for a template to update items with variations in Order Summary Page. The following problem is happening when I update quantity in Order Summary: Example (the sequence is important): Added Item 1 to cart with a size Small. Added another Item 1 to cart with size Medium So now in the Order Summary, I have a table with the following Item 1 Size: Small Quantity: 1 Item 1 Size: Medium Quantity: 1 Now if I want to change the quantity of Item 1 Size: Medium, the very first item select is the one which is updated: Item 1 Size: Small Quantity: 2 Item 1 Size: Medium Quantity: 1 I have tried 2 different templates but they are not working properly they are reflecting in a different item which was initially selected. My goal is the update the quantity of items using Order_Item id instead of Order_Item slug as it is causing confusion and reflecting to the fist item selected with different variations. I will demonstrate below my 2 trials which failed to fix this issue: Here is the models.py class Item(models.Model): title = models.CharField(max_length=100) ------------------------------------------------------------------------- updated = models.DateTimeField(auto_now_add=False, auto_now=True) active = models.BooleanField(default=True) def … -
Heroku doesn't collect static on Django but tell that it does
Command heroku run python manage.py collectstatic return me something like 163 static files copied to '/app/live-static-files/static-root', 509 post-processed. Here are my settings: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "live-static-files", "static-root") STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, "live-static-files", "media-root") DISABLE_COLLECTSTATIC = 0 Through heroku run bash i go /app/live-static-files/static-root and see it's empty (the folder exists as it's in repo with .gitkeep) and server gives 500 error on all requests. Now with heroku run bash i try python manage.py collectstatic and it works! But after heroku restart it's empty again. Why Heroku tell that it copied statics, even tell the right path of the statics folder but in fact doesn't do that? Why it actually doesn't do that? -
GAE files blocked due to mimetype/unknown url handler type for js files with multiple .'s
I've been hung up on deploying my React/Django app to GAE for the last two days and I think I've isolated the issue, but I've been unable to come up with a solution that works. When I first deployed I was running into issues with mimetypes with each of my JS and CSS files embedded in my index.html being blocked with error messages like these leading me to believe it found the files but didn't handle them correctly: (file) was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). My understanding from browsing SO and doing research was that GAE was treating these as html files and not executing them properly. I started playing with the .yaml to enforce mime types due to some settings I saw in the references for GAE and now I can't deploy and get error message: ERROR: (gcloud.app.deploy) An error occurred while parsing file: [(mysite)\app.yaml] Unknown url handler type. <URLMap static_files=None upload=None application_readable=None static_dir=None mime_type=text/css expiration=None require_matching_file=None http_headers=None position=None api_endpoint=None redirect_http_response_code=None url=/static/css\.css login=optional auth_fail_action=redirect secure=default script=None > in "(mysite)/app.yaml", line 8, column 1 I've been playing around with the files in the browser and I've found that I get 404 errors when I try to … -
Use javascript variable in django template tag
So I have this: msgerChat.append(` <div class="${side_append}" class="msg"> <div class="msg-img" style="background-image: url({{ ${chatDataMsg.username}.profile.avatar.url }})"></div> Someone tell me that this is incorrect, but is there a way to use the chatDataMsg.username in that? -
Celery - working with task return values at views.py
I want to get the value of a celery task result, the value of the actual return statement of my task and not the task_id itself! I don't understand how to accomplish this assuming the following example: views.py def call_my_task(request) user = User.objects.get(pk=request.user.pk) example_form = ExampleForm(data=request.POST) if example_form.is_valid(): my_input = str(example_form.data.get("user_input")) check_input = validate_input.apply_async(kwargs={"my_input": my_input}) check_input.get(timeout=30, interval=1) tasks.py @celery_app.task(name="Check example input", ignore_result=False) def validate_input(my_input): check = subprocess.Popen("some cmd" + ' ' + my_input, shell=True, stdout=subprocess.PIPE).communicate()[0].decode('utf-8').strip() return check Doing it like so always gives me the task_id at my views.py and does not tell me the value of "return check" The command called at the celery task can only return true or false and exactly this true or false value (as str) Is what I want to have to work further at my views.py with. Can smb. help me out?