Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django multiple file upload without using AJAX & jQuery
Since Django doesn't allow dynamic multiple file upload, I got to know that I have to use AJAX & jQuery to make this happen in my Content Management System for apparel images. But I being basically a backend guy, don't want to mess up with the existing working application by trying to incorporate front-end libraries in the code (I had tried this tutorial https://simpleisbetterthancomplex.com/tutorial/2016/11/22/django-multiple-file-upload-using-ajax.html but it just messes up the code). After reading documentation several times and searching heavily, I found this on quora. http://qr.ae/TUICrh This is just brilliant because I don't have to figure out the front-end libraries and can do the multiple upload using only Django/python code. But I don't know how to integrate this with my code. I will attach my code here. Please help me with the code specifics. models.py def file_rename(instance, filename): if instance.category.name == 'Jeans': prefix = 'string-1' count = Count.objects.get(pk=1) elif instance.category.name == 'Kurti': prefix = 'string-2' count = Count.objects.get(pk=2) ext = filename.split('.')[-1] ZSN = prefix + str(count.jeans_count + 1) filename = '{}.{}'.format(ZSN, ext) return os.path.join('images', filename) class Images(models.Model): design_id = models.CharField(max_length=128) file = models.ImageField(upload_to=file_rename) cost_price = models.FloatField() category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=False) fabric = models.ForeignKey(Fabric, on_delete=models.CASCADE, blank=False) manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE, blank=False) … -
How to lock a select query in Django so that other workers in celery wont access that record?
I have a table with lots of entries to process. we are using celery to run the background tasks. There are chances of processing same record by the celery worker. What can we do to stop fetching a record which is in processing state. we are doing background jobs for processing images from the table. -
Django get_object_or_404 throws exception when getting by date
my code is like that: ``` def post_detail(request, year, month, day, slug): print(month, type(month)) post = get_object_or_404(Post, slug=slug, status='published', published__year=year ) print(post.published.month, type(post.published.month)) return render(request, 'blog/post/detail.html', {'post': post}) ``` The output, when I'm calling that view: 7 <class 'int'> 7 <class 'int'> This shows, that the month is 7 (int), however when I modify it like: ``` def post_detail(request, year, month, day, slug): print(month, type(month)) post = get_object_or_404(Post,## Heading ## slug=slug, status='published', published__year=year, published__month=month ) print(post.published.month, type(post.published.month)) return render(request, 'blog/post/detail.html', {'post': post}) ``` I now get 404 from get_object_or_404. Weird thing, I have the same code on my local machine and it works. That one is on the server. My model is like: ``` class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Roboczy'), ('published', 'Opublikowany'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='published') author = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) body = models.TextField() published = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() active = PublishedManager() def get_absolute_url(self): date = timezone.localdate(self.published) return reverse('blog:post_detail', args=[date.year, date.strftime('%m'), date.strftime('%d'), self.slug]) class Meta: ordering = ('-published',) def __str__(self): return f'{self.title} by {self.author.username.title()}' ``` I did makemigrations and migrate, somebody knows what could be happening here? -
Meaning of isolated Virtualenv in Django and what is scope of Django local copy that I installed on my system
I am new to django and I am more interested in how it works,I want to know more about it's lib,configuration files,database linking etc. Can anyone suggest me good websites or tutorials? Also I want to know meaning of Virtual env in django. While installing Django we create a directory and create a virtual environment and in we install Django in active env, But virtualenv create isolated Python environments. What does isolated env means? I went through the definition of Virtualenv(according to this website : https://virtualenv.pypa.io/en/stable/) But I am confused, if I have installed Django in a active env in a directory,it supposed to work within that directory (as I installed in active Virtualenv and it is isolated) and have to install Django every time I create a project, But we don't install Django every time we create a new project. So what is scope of Django local copy that I installed on my system. -
Group by on_related() queryset
I've look at this How to query as GROUP BY in django? but I can't seem to get it to work. I have a queryset which brings in 4 related tables. I would like to return values from the 'top table' and group them together. Columns to group on are: area_easting(E), area_northing(N), context_number(C), sample_number(S) example current data output E |N |C |S |material 99|526|101|1 ... |seed 99|526|101|1 ... |grain 99|526|101|1 ... |pip 99|526|101|2 ... |seed 99|526|101|2 ... |grain 99|526|101|2 ... |pip I only want to return the E|N|C|S once but still be able to list each material associated with it. Is this possible without having to create another def? #views.py def botany(request): botany = FractionMaterialsPresent.objects.select_related() template = 'botany/test.html' return render(request, template, {'botany': botany}) #models.py class Botany(models.Model): botany_id = models.AutoField(primary_key=True) sample_id = models.IntegerField(blank=True, null=True) area_easting = models.IntegerField(blank=True, null=True) area_northing = models.IntegerField(blank=True, null=True) context_number = models.IntegerField(blank=True, null=True) sample_number = models.IntegerField(blank=True, null=True) entry_date = models.DateTimeField(auto_now_add=True) analysis_date = models.DateTimeField(auto_now=True) analyst = models.CharField(max_length=200, default='') notes = models.CharField(max_length=600, default='') class Fraction(models.Model): fraction_id = models.AutoField(primary_key=True) botany_id = models.ForeignKey(Botany, db_column='botany_id', on_delete = models.PROTECT) proportion_analysed = models.DecimalField(max_digits=5, decimal_places=3) soil_volume = models.DecimalField(max_digits=15, decimal_places=4) sample_volume = models.DecimalField(max_digits=15, decimal_places=4) sample_weight = models.DecimalField(max_digits=15, decimal_places=4) class FractionMaterialsPresent(models.Model): material_id = models.AutoField(primary_key=True) fraction_id = models.ForeignKey(Fraction, db_column='fraction_id', … -
How to query and structure models that share a common foreign key in Django
I have 2 models that share a Foreign Key in two different apps, that I need to query from. within the "accounts" app I have the following models: class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) profile_image = models.ImageField(upload_to='images/', null=True, default=None) import teams.models as tm class TeamStarred(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) team = models.ForeignKey(tm.Team, on_delete=models.CASCADE, default=None) date_began_following = models.DateField() and within the "teams" app I have the following models: class Team(models.Model): name = models.CharField(max_length=100, default=None) class TeamUpdate(models.Model): team = models.ForeignKey(Team, on_delete=models.CASCADE, default=None) member = models.ForeignKey(User, on_delete=models.PROTECT, default=None) date = models.DateTimeField(auto_now_add=True) In the view of a 3rd app: import teams.models as tm import accounts.models as am def home(request): if request.user.is_authenticated: From TeamUpdate I need the top 3 ordered by descending date where team is in (TeamStarred where user == request.user) as well as the profile_image of the member in these selected TeamUpdates. So far I have tried: team_updates = tm.TeamUpdate.objects.filter(team__in = am.TeamStarred.objects.filter(user=request.user).values('team')) which retrieves all of the updates and member_update = am.UserProfile.objects.filter(user__in = team_updates.values('member')) which retrieves all of the UserProfiles (containing the members' profile_images). This doesn't seem like the correct way to do this and it's difficult to match the correct profile_image to the right member when both are passed … -
Django Paginator - I create a function in a class inherting from Paginator and why I can't use this function in front-end
I'm a newbie to Django, I would like to use pager_num_range in front end for displaying the page number,but front end can't recognize pager_num_range, I don't know why. back-end code: class CustomPaginator(Paginator): def init(self,*args,**kwargs): super(CustomPaginator, self).init(*args, **kwargs) def pager_num_range(self): return range(1,2) def index1(request): current_page = request.GET.get('p') paginator = Paginator(USER_LIST, 10) try: posts = paginator.page(current_page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) return render(request,'index1.html',{'posts':posts}) front-end code: <ul> {% for row in posts.object_list %} <li>{{ row.name }}-{{ row.age }}</li> {% endfor %} </ul> {% if posts.has_previous %} <a href="/index1.html?p={{ posts.previous_page_number }}">Last Page</a> {% else %} <a href="#">Next Page</a> {% endif %} {% for i in posts.paginator.pager_num_range %} {% endfor %} {% if posts.has_next %} <a href="/index1.html?p={{ posts.next_page_number }}">Next Page</a> {% endif %} <span> {{ posts.number }}/{{ posts.paginator.num_pages }} </span> </body> -
Python Paho MQTT how to auto reconnect after Postgresql Closed connection or something else
My MQTT subscribe generally is fine, but when something exception in server, My MQTT will not working, like out of momeory then server kill postgresql or some task, and postgresql into the recovery mode, that will let mine MQTT's PostgreSQL connection fail( Connection Close) in spite of Postgresql service is back, My MQTT still connection fail(or close). so, Is there anyway can auto reconnect? import threading import paho.mqtt.client as paho_mqtt def t1(): client = paho_mqtt.Client(client_id="*****") client.on_connect = on_connect client.on_message = on_message client.username_pw_set("****", "****") client.connect("******", ***, **) client.loop_forever() def on_connect(client, userdata, flags, rc): client.subscribe(topic="********", qos=1) print('subcriptions') print(userdata) print(flags) print(rc) thread1 = threading.Thread(target=t1) thread1.start() time.sleep(10) thread1.join() -
How to use Fileupload in django?
Im new in django , When im learning django from documentation .i tried to make api using serializers and Function Based views .the this shows type object 'Questions' has no attribute 'objects' Models.py class Questions: title=models.CharField(max_length=40) description=models.TextField(max_length=50) status=models.CharField(default='inactive',max_length=30) created_by=models.ForeignKey(User,null=True,blank=True,on_delete=models.CASCADE) 2.SErializers.py from rest_framework import serializers from demoapp.models import Questions class QuestionSerializer(serializers.ModelSerializer): class Meta: model=Questions fields=( 'id', 'title', 'description', 'created_by', ) urls.py from django.urls import path from demoapp.views import * urlpatterns = [ path('poll', demoapp), ] And Error is: enter image description here -
How to use "group by and select the max one" in django
I have a table in mysql, like: id, dirId, filename 1, 1, jone 2, 1, jack 3, 2, jack 4, 3, ella I want to get the biggest dir_id(and filename) with the same filename. we can use group by in mysql, what to use in django. -
Declare "mul key" field in python. (django framework)
I have a column which should be mul key, but I could'nt find out how I can do that. here's the code: class table(models.Model): field2 = Models.int(max_length=9, null= False, default = 0) -
How to get django logs behind uwsgi?
I am using uWSGI + Django, and I am using fluent.handler.FluentHandler as one of log handlers to send logs to fluentd. On my local machine, I can get Django logs correctly with runserver. When I run Django with uWSGI, I can only see request logs from uWSGI, no logs was sent to log handlers in Django. Anyone can help about how to make log handlers receive Django logs? -
Django view with get context not working
Have a quick question. Trying to use a relational model in one DetailView. However, no matter what I try the data does not display. I've tried a few versions of template tags to no avail. html {% for parts in errorcodes.relatedparts_list %}{{ parts.name }} </div>{% endfor %} views.py class ErrorCodeView(DetailView): context_object_name = 'error_code_details' model = models.ErrorCodes template_name = 'error_code_details.html' def get_context_data(self, **kwargs): # xxx will be available in the template as the related objects context = super(ErrorCodeView, self).get_context_data(**kwargs) context['relatedparts'] = RelatedParts.objects.filter(name=self.get_object()) return context models.py class ErrorCodes(models.Model): name = models.CharField(max_length=256) description = models.CharField(max_length=400) instructions = models.CharField(max_length=256) PartsNeeded = models.CharField(max_length=120, default='') usercomments = models.CharField(max_length=400, default='', blank=True) relpic = models.ImageField(upload_to='media/',blank=True) relpictwo = models.ImageField(upload_to='media/',blank=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("errorcodes:errorcodeview",kwargs={'name':self.name}) class RelatedParts(models.Model): name = models.CharField(max_length=256) related_error_code = models.ForeignKey(ErrorCodes, on_delete=models.PROTECT) def __str__(self): return self.name -
django model attribute error. object has no attribute save
I have the following model: class SavedRFP(models.Model): name = models.CharField(max_length=200) user = models.ForeignKey(STUser, on_delete=models.CASCADE) eventpurpose = models.ForeignKey(EventPurpose, on_delete=models.SET_NULL, blank=True, null=True) datevalue = models.DateField() datename = models.CharField(max_length=50, blank=True, null=True) dateflex = models.BooleanField(default=False) startime = models.TimeField() startimeflex = models.BooleanField(default=False) endtime = models.TimeField() endtimeflex = models.BooleanField(default=False) headcount = models.IntegerField() eventdetails = models.CharField(max_length=1000) when I attempt to save the model from models import SavedRFP savedrfp = SavedRFP(user=request.user, eventpurpose=eventpurposepk, **data) savedrfp.save() AttributeError: 'SavedRFP' object has no attribute 'save' never had this before anyone have any experience with this? -
Unable to store multiple images in django database
I am working on a hotel booking site , in which i give the user a option to upload their hotel in the site, In that i am interested in user to upload multiple images with out any particular limit, i wrote the model , the user successfully uploading the images but i am unable to store it in the database . I got struck on this issue, i have searched everything on the web from the past one week , still not yet resolved, please help me on this issue . Here is my model hotel_rating_choices = ( ('1','1'), ('2','2'), ('3','3'), ('4','4'), ('5','5'), ('6','6'), ('7','7'), ) class Hotel(models.Model): Hotel_Name = models.CharField(max_length=50) location = models.CharField(max_length=20) no_of_rooms = models.IntegerField() rating = models.CharField(max_length=1, choices=hotel_rating_choices, default=3) hotel_img = models.FileField(upload_to='hotel_images/') uploaded_at = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) def __str__(self): return self.Hotel_Name Here is my form class add_hotel(forms.ModelForm): class Meta: model = Hotel fields = ('Hotel_Name', 'location', 'rating','no_of_rooms', 'user','hotel_img', ) # exclude = ['id'] widgets = { 'hotel_img' : forms.ClearableFileInput(attrs={'multiple': True}) } Here is my view class BasicUploadView(CreateView): template_name = 'photos/basic_upload/index.html' model = Hotel form_class = add_hotel success_url = reverse_lazy('home') def get(self, request, *args, **kwargs): form = add_hotel return render( self.request, template_name = self.template_name, … -
How to add object fields into a python dictionary
I have a Queryset and there are 2 data that i want to collect from the object's field. Now i want to make them into a dict where the key will the the category and the amount will be the value. data = {} for spend in spendings: data[spend.category] = spend.amount I ended up with the data below, which is incorrect because the amount is being updated rather than added. What should i do? {'Medical': Decimal('20.00'), 'Food': Decimal('3.00'), 'Transport': Decimal('20.00')} I wish to end up with the result below in the case where i have 2 medical spending where each spending cost $100 and 5 food spending where each cost $10 {'Medical': Decimal('200.00'), 'Food': Decimal('50.00'), 'Transport': Decimal('20.00')} -
django - If logic in template
Is something like this possible in template? {% if request.path == url 'posts:post_detail' pk=instance.id %} If not, how can I achieve this result being true. I want to this to be true when user is looking at a specific post post/1 -
Django - foreign key - invalid literal for int() with base 10: '123453-11-32'
First of all, I think the error is incurred because Django is expecting integer, but instead a string is passed. The problem is, I don't know why and where Django is expecting integer. Error Message ValueError at /well_list/123453-11-32/contextual/bha/1 invalid literal for int() with base 10: '123453-11-32' models.py class WellInfo(models.Model): api = models.CharField(max_length=100, primary_key=True) well_name = models.CharField(max_length=100) class BHA_List(models.Model): well = models.ForeignKey(WellInfo, 'CASCADE', related_name='bha_list') bha_number = models.CharField(max_length=100) app/urls.py app_name = 'contextual' urlpatterns = [ re_path(r'^$', base_views.ContextualMain_DetailView.as_view(), name='main'), re_path(r'^bha/(?P<pk_alt>[-\w]+)$', base_views.BHA_UpdateView.as_view(), name='bha'), ] project/urls.py urlpatterns = [ path('well_list/', include([ re_path(r'^$', views.WellList_ListView.as_view(), name='well_list'), re_path(r'^create/$', views.AddWell_CreateView.as_view(), name='create'), re_path(r'^(?P<pk>[-\w]+)/contextual/', include('contextual.urls')), ])) ] context_processors.py def add_context_to_base(request): print('context_processor was called') try: api = resolve(request.path_info).kwargs['pk'] default_page_1 = '1' return {'api': api, 'default_page_1': default_page_1} except KeyError: return {} The reason I added context_processor is because the string in url 123453-11-32 was injected into base.html using context_processor. I'm not sure if this is the source of error. But I don't think this was the source of error, because it did not print context_processor was called on the console. And finally, this is my views.py that gives me the error: views.py class BHA_UpdateView(UpdateView): template_name = 'bha_test.html' context_object_name = 'bha' model = models.BHA_List fields = '__all__' success_url = reverse_lazy('well_list') But if I change … -
Mongodb model not recognizing defined fields/not updated when I try to rename
(Sorry if the question is terribly worded) I'm having trouble adding objects to a collection in Mongodb. I have a Django app, and it seems when I initially migrated, three of the fields did not 'migrate' to the DB. Here is my models.py file: class Children(models.Model): child_name: models.CharField(max_length=200) child_type: models.CharField(max_length=200) children_subtype: models.CharField(max_length=200) starttime = models.DateTimeField() endtime = models.DateTimeField() duration = models.DurationField() result = models.CharField(max_length=200) Build = models.ForeignKey(Build, related_name='children', on_delete=models.CASCADE) def __str__(self): return self.child_name When I try to access the model in the python shell, I immediately get this error: from dibuilds.models import Children Children.objects.all() Error: Traceback (most recent call last): File "", line 1, in File "/Users/chesoni/Documents/tests/buildtest/myvenv/lib/python3.6/site-packages/django/db/models/query.py", line 251, in repr return '<%s %r>' % (self.class.name, data) File "/Users/chesoni/Documents/tests/buildtest/myvenv/lib/python3.6/site-packages/django/db/models/base.py", line 513, in repr return '<%s: %s>' % (self.class.name, self) File "/Users/chesoni/Documents/tests/buildtest/buildapptwo/dibuilds/models.py", line 38, in str # return self.children_name AttributeError: 'Children' object has no attribute 'child_name' Now when I try to update, I cannot add the fields 'child_name', 'child_type', 'child_subtype' to the objects. I've tried changing the name to 'children...' in the model, and adding an object without the fields to the collection in mongodb (which works) then adding the desired fields in using mongodb's gui (compass) (which doesn't work) Can … -
JSONResponse giving CSRF verifiication failed in HTTPS on AWS
I recently added HTTPS to my site. I've not released to production but am using a real domain for testing before rerouting to the final domain. Before transitioning to HTTPS I was able to set session data to the server via the view call 'SetCitySession' and it would fine and still works fine in a pre-HTTPS environment I am still running. On HTTPS it is not running however. I have had various errors in my attempt to configure it properly but my persistent error is the '403 - CSRF token missing or incorrect'. I don't understand why though. In my pre-HTTPS environment the code is managing to access the cookie just fine and they exist, verified by the checking the request headers in DevTools yet in the HTTPS environment the token is there but not being retrieved by AJAX for use in the request. I've looked at the docs, tried everything like @csrf_protect, @csrf_exempt etc nothing changes. In the javascript below, its a bit bloated casuse I was trying everything, I offer two ways for Ajax to retrieve the cookie. I ONLY actually used one at a time but left both in now for reference sake and so you would … -
Django and Flask websites work like PHP?
Does Django and or Flask websites work in real time or works like php? I'm new in this language and I would love to know more about it. PS: Before downvote or delete my question, please leave a message and be constructive I will appreciate a lot, and I will correct what is wrong with pleasure. -
Django: How would you constantly check an API even when web app is not loaded?
My website needs to send an email to users even when the web app is not running. I have an API and each time I receive data I need to send my users an email. I need to be guided to the right direction. Thanks in advance. -
from basic python app to django web service
I have an app that uses multiprocessing and Queue features for my demands, and I want to rewrite this one to start using Django ORM and frontend frameworks in future. Currently I have four Queues, 5 child and 1 parent processes. Last one's connected to longpoll server and puts received data into queue, then "subparent", which plays the role of parser, gets the data and forwards to other childs. There are a lot of problems, such as pipe errors while using shared connections to db and etc, I could try challenging all of them but instead I decided to move on. At the moment I'm noticed that I'm supposed to use celery with tasks.py, but I haven't seen any examples of apps which would seem a solution for me. How can I rewrite something like this: while True: ... = request.get(...) ...processing the data... for use with celery, except my idea about usage of @periodic_task with (about to be always working) intervals is correct? Or, if I could keep using my current architecture with only rewritten for Django ORM database related calls, how do I integrate my current app to django? -
Django how to use generic view with UUID instead of PK
I'm trying to access a url that's like 127.0.0.1:8000/posti/qNwEXBxXQdGI4KlQfoHWOA However I can't resolve that smalluuid. This is the error: NoReverseMatch at /posti/ Reverse for 'detail' with arguments '(SmallUUID('qNwEXBxXQdGI4KlQfoHWOA'),)' not found. 1 pattern(s) tried: ['posti/(?P[0-9a-fA-F-]+)/$'] Django has issues trying to resolve it in another view that has a string like this: from . import views from django.conf.urls import url app_name = 'posti' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<slug>[0-9a-fA-F-]+)/$', views.DetailView.as_view(), name='detail'), My DetailView is this one: class DetailView(generic.DetailView): model = Post template_name = 'posti/detail.html' slug_field = 'uuid' def get_queryset(self): """ Excludes any questions that aren't published yet. """ return Post.objects.all() I tried rewriting get_object but it didn't do anything. I don't understand if the regex is wrong or if my view has something wrong. -
Django inline message user for tabular inline
How do you display a message to user in the tabular inline formset ON LOAD which depends on the value of a particular formset instance attribute.