Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why my Model JSON/list attribute in Django sometimes misses data?
I'm building a Django project that has to do with generating math/science problems for teachers and students. The project works fine for some time but when I run it on the browser (with the views all set up) it sometimes get errors that I cant explain how they happen: Example: class Mymodel(models.Model): attribute = JSONField() #it is a list of strings ['a', 'b', 'c'] def myfunc(self): do something with (self.attribute) The problem is that every now and then, the program runs into an error mainly because when myfunc calls self.attribute it returns the list with items missing! like, in this case, it may return ['a', 'b']. I've never seen any error like this, so I don't know what to do. I obviously double checked if the attribute is really with all the variables I expeceted it to be, that's not the problem. Has anyone seen anything like this that could help? I strongly believe that it has something to do with how Django gets the data in the JSONField and parses it to a list or dict to work with that, but again I don't know what to do about it. -
Configuring Celery + AWS SQS to revoke tasks
I am running Celery+Kombu 4.4.6 on AWS SQS and want to revoke and terminate tasks. Reading through documentation and SO posts, the transport needs to allow broadcast messages. SQS does not do broadcast messages and Celery+Kombu needs to use SimpleDB for those. That option was turned off by default long way back in version 1.x. To enables it, support_fanout = True needs to be added to the transport options. But adding just that option is not working for me and I can't figure out what am I missing. Possible options are: SimpleDB - it is not clear to me how do I even enable SimpleDB. I do see documentation in AWS, but I do not see it as a separate service. Any additional config to be added? Looking briefly at the SQS code, seems like SimpleDB is the only option for this. Is that correct? Any other option to enable task revocation on SQS? In my app.celery I have: app = Celery('app', broker=''sqs://<Access key>:<secret key>@')), backend='cache+memcached://<host>:11211/')), ) And in my app.settings I have: CELERY_BROKER_URL='sqs://<access key>:<secret key>@')) CELERY_BROKER_TRANSPORT_OPTIONS = { 'region': '<region>', 'supports_fanout': True, } CELERY_DEFAULT_QUEUE = 'app' CELERY_DEFAULT_EXCHANGE = 'app' CELERY_DEFAULT_ROUTING_KEY = 'app' -
What is the best way to do ajax rendering for a long section?
I am currently dividing the template into sections and using ths in views.py if "x" in Form2.changed_data: template_photo = render_to_string("photo.html", context) success["template_photo"] = template_photo if formset_has_changed(FormSet1): template_intro1 = render_to_string("intro1.html", context) success["template_intro"] = template_intro if formset_has_changed(FormSet2): template_intro2 = render_to_string("intro2.html", context) success["template_subject_intro"] = template_subject_intro template_section = render_to_string("section.html", context) and sending it as a JSONresponse and replacing the innerHTML with js. The reason I am using this method is to prevent the whole form from being rendered again (such as prevent unchanged photos from being rendered again). However, this will quickly become messy and repetitive as I create more sections. Is there an alternative practice to this to update the page without replacing the entire innerHTML of the form/page? -
How to sort a list from queryset using Django
I want to sort a list converted from queryset. I've tried using sorted, but I'm getting an error This is my code: views.py @api_view(['GET']) def practiceAnswer_filter(request): # GET list of filtered practiceAnswer if request.method == 'GET': practiceAnswers = PracticeAnswer.objects.all() practice_id = request.GET.get('practice_id', None) if practice_id is not None: # filter practiceAnswer based on practice_id practiceAnswer_filtered = practiceAnswers.filter(practice_id__practice_id__icontains=practice_id) # convert queryset to list practiceAnswer_list = list(practiceAnswer_filtered) # shuffle to get random practiceAnswer shuffle(practiceAnswer_list) # splice list to limit practiceAnswer practiceAnswer_shuffled = practiceAnswer_list[:3] practiceAnswer_sort = practiceAnswer_shuffled dict(sorted(practiceAnswer_sort.items(), key=lambda item: item[1])) print(practiceAnswer_sort) practiceAnswers_serializer = PracticeAnswerSerializer(practiceAnswer_sort, many=True) return JsonResponse(practiceAnswers_serializer.data, safe=False) This is the original data from queryset : <QuerySet [<PracticeAnswer: 1>, <PracticeAnswer: 2>, <PracticeAnswer: 3>]> This is the converted data from queryset to list : [<PracticeAnswer: 1>, <PracticeAnswer: 2>, <PracticeAnswer: 3>] Actually with the original data and converted data I already got the sorted data but from the original data I still process it by filtering it based on practice_id and randomizing the data to get random data after that limiting / splice to display only 3 data. Without sorted the 3 data that appear are not sequential, I want the data to be sorted by the values 1, 2, 3 If I run … -
Django ZIP multiple images for download
I'm trying to zip several images in a ZIP file. Although It's a Django app, files are not stored in the same app. I want to fetch them from a url list. I get the following error: FileNotFoundError [Errno 2] No such file or directory: 'image1.jpg' def download_image(request): fotos = ['https://storage.googleapis.com/some/image1.jpg', 'https://storage.googleapis.com/some/image2.jpg'] f = StringIO() zip = ZipFile(f, 'w') for foto in fotos: url = urlopen(foto) filename = str(foto).split('/')[-1] zip.write(filename, url.read()) zip.close() response = HttpResponse(f.getvalue(), content_type="application/zip") response['Content-Disposition'] = 'attachment; filename=image-test.zip' return response I reviewed several posts and finaly followed this one how can I export multiple images using zipfile and urllib2 - django But I can't get this working. Any clues welcome. Thanks in advance. -
How to add 4-level domain for django
there are nginx and django server and a proplem to add endpoints like moscow.test.site.com or tokio.test.site.com When i use localhost then no problem but how to add domains of 4-level for my test.site.com? -
DatabaseError at boards, No exception message supplied
I am working on a Django project with MongoDB Database, but when I am trying to open boards that contain topics(join). I have this error! -
Should I use Python or Javascript to build a text-based adventure using Django?
I hope this doesn't come off like too strange a question, but I'm relatively new to Django specifically. I currently have a website going using Heroku and Django and I would like to post a bunch of mini-projects and such I make there. One of the ones I want to do is a text-based adventure. I'm relatively proficient in Python and Javascript individually and have built similar things in both, however I'm having trouble thinking how best to translate this into the Django framework. Currently on my website I have a bunch of pages just for things like articles and written pieces. All of that is working fine and I've even added a mini CMS to the backend and that all works alright. However most of that was either building stuff entirely in backend, or entirely in frontend and then just doing a data linkage. There's no real python code going on in the backend outside of constructing the views and models etc. If I was to build this in Javascript I would likely just hardcode a lot of the writing for a text-based game, likewise with Python, however I feel with Django and a linked Postgres DB there's potential … -
Django Heroku database reset after each push?
Forgive me if this is a obvious answer, but will my database be reset after each git push heroku master ? -
Deploying django on local server
I have just finished my Django app. Now I would like to run the app at the company I work for. Problem is, this is my first time doing so, so I need a helping hand. Can anyone point me in the right direction with a good tutorial? I wish to install only necessary tools, nothing extra. I think there is no need for safety because it would be only accessible from the company level. Should I just copy files from my PC and run it on virtual machine (Windows) or is there a better approach? Is it possible for everyone to connect to my server? -
Django: How to pre-enter data in a form?
I have got a quotation that I would like to convert in a project. If a quotation has been approved, it will be converted in a new project. I`ve got two models, one for the quotation and one for the project. To achieve this, I am thinking to add a button Create Project from Quotation. This button will create a new project based on the Project Model. Now, I am trying to find a way to pre-enter some data from the quotation in the new Project model entry. What should I add to my {% url 'projects:create_project' %} to pre-enter the project name and link it to the quotation? Many Thanks, -
Trying to add report issue feature on my django project but giving me error
i am trying to add report issue on my todo beginner project but gives me error let me explain İ want it to give and error message like if its already reported in my admin.thats the main idea when i first click on the report button it shows up the id of reported item on admin / reported area but when i reclick on the report button it gives me IntegrityError at /report/17 UNIQUE constraint failed: tasks_report.id views.py def report_view(request, pk): task = Task.objects.get(id=pk) reported = Report.objects.create(id=pk) return redirect('index') models.py class Report(models.Model): is_reported = models.BooleanField(default=False) urls.py path('report/<str:pk>', report_view, name="report"), admin.py admin.site.register(Report) -
query for model instances that are indirectly related
I've got 3 models. I'd like to write a query in django to find all reviews that are related to Carts that are related to jobs that are complete. Unfortunately, I can't figure out how to do this. class Review: cart = models.ForeignKey(Cart, on_delete=models.CASCADE, default=None) class Job: cart = models.ForeignKey(Cart, on_delete=models.CASCADE, default=None) complete = models.BooleanField(default=False) class Cart: name = models.CharField(max_length=500, null=True, blank=True) amount = models.IntegerField() Any help would be appreciated! -
Django db not saving changes
Django db not always saving changes, when I canhge one of model parametrs. Code below, look veiws.py on lines highlighted by comments, I try to append new_file.ID value to parent.files (ArrayField) and user parent.save() to save changes, but realy it not always works, have this problem when loading too much files at the same time. When amount of loading files not large it's always works... I'm using postgresql views.py fragment @csrf_exempt @sync_to_async def load(request): if request.method == 'POST': if request.user.is_authenticated: import os from .utility import alternative_filename, set_file_ID file = request.FILES['file'] path = request.POST['full_path'].split('/') parent = File.objects.get(ID = request.POST['parent_id']) if allowed(parent, request.user, moderators = True): filename = alternative_filename(f'{get_file_path(parent)}/{file.name}') if len(path) > 1: path.remove(path[0]) for element in path[:-1]: if not os.path.exists(f'{get_file_path(parent)}/{element}'): os.mkdir(f'{get_file_path(parent)}/{element}') new_parent = File(name = element, folder = True, parent_ID = parent.ID) set_file_ID(new_parent, request.user.username) parent.files.append(new_parent.ID) parent.save() else: new_parent = File.objects.get(parent_ID = parent.ID, name = element, deleted = False) parent = new_parent filename = alternative_filename(f'{get_file_path(parent)}/{file.name}') path_to_file = get_file_path(parent) with default_storage.open(f'{path_to_file}/{filename}', 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) new_file = File(name = filename, folder = False, parent_ID = parent.ID) set_file_ID(new_file, request.user.username) ############################################### parent.files.append(new_file.ID) parent.save() # this save not always working!!! ############################################### return JsonResponse({'message' : 'Created', 'new_ID' : new_file.ID}, status = 201) else: … -
Using AJAX to delete model data - Django
I have a javascript alert (It uses swal to style it, but it functions like a regular alert). I want to run SomeModel.objects.filter(id=id).delete() after the ok button is clicked. I did research online, and I came across many articles talking about using Ajax, but I can't really figure out how to implement it in my program. Can someone please help me? My JS is down bellow: swal({ title: "Accept Donation", text: "Are you sure you would like to accept the donation titled {{donation.title}}, which was posted on {{donation.date}} by {{donation.user}}?", icon: "info", buttons: true, }) .then((ok) => { if (ok) { swal("Donation successfully accepted, please contact {{donation.user}} at {{donation.phonenumber}}, for instructions as to when and where you should pick up the donation", { icon: "success", }); } }); } I have been struggling with this for a really long time, I am willing to buy whoever helps me a coffee. Thank you -
Why am I receiving a NoReverseError message when having two django paths that take string inputs? (I am working on CS50 Project 1.)
I am working on CS50 Project 1 dealing with Django. In urls.py I have two paths that take strings as input, but neither work, and I receive a NoReverseError message. urls.py code urlpatterns = [ path("", views.index, name="index"), path("edit_entry/<str:title>/", views.edit_entry, name = "edit_entry"), path("search/", views.search, name = "search"), path("wiki/<str:title>/", views.get_entry, name = "get_entry"), path("create_entry", views.create_entry, name = "create_entry") ] views.get_entry code def get_entry(request, title): exists = util.get_entry(title) if exists is None: return render(request, "encyclopedia/get_entry.html", { "entry": "Entry Does Not Exist" }) else: entry = markdown(util.get_entry(title)) return render(request, "encyclopedia/get_entry.html", { "entry": entry }) views.edit_entry code (edit_entry actually has some more work that needs to be done to it) def edit_entry(request, title): if request.method == "POST": form = NewEditEntryForm(request.POST) if form.is_valid(): title = form.cleaned_data["title"] content = form.cleaned_data["content"] util.save_entry(title, content) return HttpRespnseRedirect("/wiki/" + title) else: return render(request, "encyclopedia/edit_entry.html",{ "form": NewEditEntryForm() }) The error message NoReverseMatch at /wiki/Css/ Reverse for 'edit_entry' with keyword arguments '{'title': ''}' not found. 1 pattern(s) tried: ['edit_entry/(?P<title>[^/]+)/$'] Your help would greatly be appreciated. Thank you! -
how to save data from telegram session - django
I have a telegram bot that sends a link to let the user authentificate with twitch, obviously when twitch send a response only gives me information about the twitch user that logged in, how can i get information like who is the telegram user that clicked the link? I asked a similar question here but now i realize that i didn't understand what to do (anyway probabily the answer i received is more useful to you). views.py @csrf_exempt def telegramBot(request): #function that handles telegram messages request.session['telegramID'] = "telegramID" return telegramBotFunction(request) #return a http response #the user is redirected here after login with twitch, how can i get the telegram id? def verify(request): telegramID = request.session['telegramID'] #ERROR! print("telegramID", telegramID) return gestioneVerificaAuth(request) #return HttpResponse("<h2> Twitch user is subscribed/or not to streamer X <h2>) this gives an error because doesnt find the key ['telegramID'], how can i save the telegramID? Any help or also a small hint is appreciated -
Trying to update Django model with dynamic variable
I am trying to update a Django model with dynamic data, like so: MyModel.objects.filter(pk=id).update(key=None) key here is a string variable, based on the key from some array. However when I try to run this, I get this: django.core.exceptions.FieldDoesNotExist: MyModel has no field named 'key' Which makes sense, it is looking for a field key. How do I tell it I want to use the actual value of the string variable for the key, rather than key? -
How should i structure my Django apps for a learning management system
I'm creating a learning management system in django(python). What's the best way for me to structure my apps and how many apps should I have?? I haven't started writing codes yet and i don't need anyone to tell me to go to my settings folder. All I need is from creating a project, how many apps do I need to create and what would be their function I just want to design a mockup where I understand what every aspect of the website. I would also like my apps to be structured in a way that I can reuse them. All opinions matter. -
Django Custom Queryset Using Listview if Parameters Exist in URL
I have a listview for my blog: #views.py class BlogListView(ListView): model = Blog template_name = 'blog/index.html' context_object_name = 'blogs' ordering = ['-date_posted'] paginate_by = 5 #urls.py path('', BlogListView.as_view(), name='blog-index'), In my model I have different type of blogs, such as video blog or text blog. my model is like this: class Blog(models.Model): TYPE = ( ('Video', 'Video'), ('Text', 'Text'), ) type = models.CharField(max_length=10, choices=TYPE, default='Text') Now I want to use request.GET.get('type') to query different types. For example if I go to the url, 127.0.0.1:8000/?type=video I want only blog that are the type video to show. Is it possible to do this with only this listview, or do I have to create others. I need help to make this feature. -
Django Timezone Middleware Problems
I am trying to work with the Django Timezone Middleware which I took from the offical documentation, but it doesn't seem to work. I have a middleware.py file like this: import pytz from django.utils import timezone class TimezoneMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): tzname = request.session.get('django_timezone') print('DJANGO TIMEZONE', tzname) if tzname: timezone.activate(pytz.timezone(tzname)) else: timezone.deactivate() return self.get_response(request) Where I output the "tzname" to the console, it is set to None which must be the problem, but why isn't it set? My settings file has the following: USE_TZ = True TIME_ZONE = "UTC" MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'myproject.middleware.TimezoneMiddleware', ] My template looks like this: {% load tz %} {% get_current_timezone as TIME_ZONE %} {{ TIME_ZONE }} {% localtime on %} <p>{{ room.open_date }}</p> {% endlocaltime %} The result is that {{ room.open_date }} will show in UTC. {{ TIME_ZONE }} displays 'UTC'. I have tried without the TIME_ZONE setting in settings. I believe I have implemented it according to the documentation, but am obviously missing something. My Django version is Django version 3.2.5. Please can someone help. My goal is to display the dates in the timezone that the browser has. -
Attribute Error When Clicking Model in Admin Section of Django
I'm using Django and I'm getting the error AttributeError at /admin/network/post/ 'Post' object has no attribute 'user' The strange thing is this error happens when I'm looking at the admin section, and clicking 'Posts.' I only have models for users and posts. Not sure how to fix this error because so far I've never gotten an error like this when clicking it in the admin section of the site: http://127.0.0.1:8000/admin/ I think the issue is in my model because the view for creating a post works totally fine. models.py class User(AbstractUser): pass class Post(models.Model): text = models.TextField(max_length=500, blank=True, null=True) username = models.ForeignKey('User', on_delete=models.CASCADE, related_name='author', null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) like = models.ManyToManyField( User, blank=True, related_name="liked_user") def __str__(self): return self.user.username class Follow(models.Model): target = models.ForeignKey('User', on_delete=models.CASCADE, related_name='followers') follower = models.ForeignKey('User', on_delete=models.CASCADE, related_name='targets') views.py def make_post(request): if request.method == "GET": form_for_post = {'form': PostForm()} return render(request, "network/make_post.html", form_for_post) else: form = PostForm(request.POST) if form.is_valid(): text = form.cleaned_data['text'] new_post = Post.objects.create( text=text, username=request.user, ) return render(request, "network/make_post.html", { "new_post": new_post, }) -
how to show two models data in one template - django
I need to get two models data in one template. If I loop without union this two models in one tuple or list, I get too much looped info as you know, so I need your help there. This is what I tried, but it did not work... @login_required def my_hotels(request): hotels_info = AddHotelStep1.objects.all() hotels_info_2 = AddHotelStep2.objects.all() info = dict() info['hotels_info'] = hotels_info info['hotels_info_2'] = hotels_info_2 context = {'info':info,} return render(request, 'myhotels.html', context) This is my template: {% for hotel in info %} {% if user.is_authenticated and hotel.customer == user %} {{hotel.hotel_name}} {% with ''|center:hotel.star as range %} {% for i in range %} <span class="fa fa-star checked"></span> {% endfor %} {% endwith %} {{hotel.hotel_type}} {{hotel.short_description}} {% endif %} {% endfor %} This is my models: class AddHotelStep1(models.Model): customer = models.ForeignKey(Account, on_delete=models.CASCADE) hotel_name = models.CharField(max_length=50) short_description = models.TextField(max_length=250) long_description = models.TextField(max_length=2000) HOTEL_STAR = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5') ) star = models.TextField(max_length=1, default=5, choices=HOTEL_STAR, null=True) picture = models.ImageField(upload_to='images/%Y/%m/%d/', default="images/default.jpg", blank=True) class AddHotelStep2(models.Model): hotel_name_2 = models.ForeignKey(AddHotelStep1, on_delete=models.CASCADE) HOTEL_TYPE = ( ('Single', 'Single'), ('Double', 'Double'), ) hotel_type = models.TextField(max_length=10, choices=HOTEL_TYPE) I would get any advice to solve it. -
How to create models dropdown menu in djngo
i created two model name categories and subcategories by which if i create a category name merch so under that i can create sub categories name t shirt, hoddies, shirt so i linked categories with foreign key in subcategories so i want to render a dropdown menu in which on top categories will show up and under that all the sub categories related to categories but i am unable to achieve that i tried this my models.py class Categories(models.Model): name = models.CharField(max_length=100, blank=False) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Subcategories(models.Model): categories = models.ForeignKey(Categories, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=False) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name and my views.py class home(View): def get(self, request,): category_list = Categories.objects.all() return render (request, 'home.html', {'category_list': category_list }) and my html <ul class="navbar-nav m-auto"> {% for category in category_list %} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle category" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> {{ category.name }} </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item text-white" href="#"></a></li> </ul> </li> {% endfor %} my urls.py path('',home.as_view(),name='home' ), what it does it load the categories name but unable to subcategories name under the dropdown menu here is the pic for you better understanding -
PostgreSQL models efficiency to store asset prices - Django
I want to store prices of assets in different currencies. I'm wondering which one of these 2 way below (using Django models) is the most efficient for my PostgreSQL database. 1st way: class CurrentPrice(models.Model): usd = models.FloatField() eur = models.FloatField() aud = models.FloatField() # ... class AthChangePercentage(models.Model): usd = models.FloatField() eur = models.FloatField() aud = models.FloatField() # ... class MarketCap(models.Model): usd = models.FloatField() eur = models.FloatField() aud = models.FloatField() # ... Here you can see I use table rows to add different currencies price. 2nd way: class Currency(models.Model): name = models.CharField(max_length=100) symbol = models.CharField(max_length=100) class CurrentPrice(models.Model): currency = models.ForeignKey(Currency) price = models.FloatField() #... class AthChangePercentage(models.Model): currency = models.ForeignKey(Currency) ath_change_percentage = models.FloatField() #... class MarketCap(models.Model): currency = models.ForeignKey(Currency) market_cap = models.FloatField() #... I cropped the classes because in reality I have around 50 different currencies to handle. Of course there will be multiple assets too. Which one do you think is the fastest, efficient and less power consuming? Or is there any better way to do this ?