Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
zipfile arcname ZIPs whole server
I am having a situation in ensuring that when I create a zip file it does not have the whole directory of the file when it is unzipped. Having done some research there is a lot of content about using arcname in zip.write, however any solution I try results in the whole server being zipped! I have tried adding arcname = os.path.basename(file) and other possible solutions with no luck. This is my code below: all_order_files = glob.glob("/directory/"+str(order_submission.id)+"-*") zip = zipfile.ZipFile("/directory/" + str(order_submission.id) + '-Order-Summary.zip', 'w') for file in all_order_files: zip.write(file) zip.close() -
All-auth allow new user to proceed without registering
I'm currently using django-all-auth to handle user authentication on a site I'm making. Currently, all new users, no matter what the url is, are forced to sign-up with email. Is there a setting I can tick to enable users to browse the website without registering then be redirected to sign-up when hitting more advanced features (using something like LogInRequiredMixin)? -
Custom corpus not loading in chatterbot django app
I am trying to build a django app with chatterbot using the chatterbot django integration from this example code. I want to use a custom corpus that is the chatterbot.corpus.bangla . My settings.py has the following: # ChatterBot settings CHATTERBOT = { 'name': 'Django ChatterBot Example', 'django_app_name': 'django_chatterbot', 'trainer': 'chatterbot.trainers.ChatterBotCorpusTrainer', 'training_data': ['chatterbot.corpus.bangla'] } But when testing the chatbot I don't get replies from this corpus. The first replies are just echo of the given input, which means the chatbot is currently untrained I have run both python manage.py migrate django_chatterbot and python manage.py migrate and restarted the server. But still the same problem. How do I ensure that chatterbot uses this corpus I stated? Thanks. -
If views catches error, reload page and display error
I don't know if this is possible with Django or not, but here's my question. I have a form where users submit some stuff, and I want to know if I can catch an error in my views and then reload the page using the original template and throw the error in there, so the user can see it? I have some code that returns the error I want to display, but is it possible to redirect to the original template of my view and insert this error code into there IF the form fails? Bear in mind that roundup isnt value a user submits, but a value that is calculated from some other python code. if roundup >= 1: return HttpResponse("Price too low!") -
Django 1.11 - Use search with unaccent extension
Problem We need to use Django search with the unaccent extension. So far I installed the extension with a migration and added 'django.contrib.postgres' to installed apps. After I wrote some code to query the databe. I don't know why but I keep getting this error and I can't find any information about what it means. Error text search configuration "unaccent" does not exist at character 701 Migration from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('team', '0006_team_team_image'), ] operations = [ UnaccentExtension() ] Code from django.contrib.postgres.search import SearchVector, SearchQuery sv = SearchVector('first_name', 'last_name', 'email') parsed_body = json.loads(request.body.decode('utf-8')) query = parsed_body['query'] users = User.objects.annotate(search = sv).filter(search = SearchQuery(query, config = 'unaccent')) response = { 'users': [{'full_name': u.get_full_name(), 'email': u.email, 'pk': u.pk} for u in users] } -
Is it possible to assign the field type dynamically - Django Form?
Is it possible to assign the field type dynamically - Django Form? field_type = 'CharField' field = forms.{field_type}(label='Field') -
Twilio 12100 Error in Browser to Phone Call
Context: Twilio Browser-to-Phone calling API What I am trying to achieve: On click of the 'call customer' button, get a new page to pop up containing the calling functionality (i.e., the status bar, the 'answer call' button and the 'hang up' button) and then the call should connect. What is happening: The new page does pop up and the call ringing starts: but after a while I get the 'Sorry, an application error occurred' message. On inspecting the error in the debugger I found that I have been getting "Error-12100" messages. Every time I correct one, another error comes up pointing to a flaw in the some part of the code (of the template being rendered). The errors include messages such as "The element type \"link\" must be terminated by the matching end-tag \"</link>\". " 'the entity \"copy\" was referenced, but not declared.' "Attribute name \"disabled\" associated with an element type \"button\" must be followed by the ' = ' character. " "The element type \"meta\" must be terminated by the matching end-tag \"\ <meta> \". " "DOCTYPE is disallowed when the feature \"http://apache.org/xml/features/disallow-doctype-decl\" set to true. " and so on, even though this code is almost identical to the … -
Django app cannot link html files to static css files
I generated a page using the Bootstrap Studio 4, and I want to load this page from Django framework. If I double click the html file it loads in the browser successfully. However, when I render the html file from django, it cannot link it with the static files (css, js). I have placed all my Bootstrap files under STATICFILES_DIRS. When I load the page, the Django server prints the following [24/Mar/2019 22:56:59] "GET /modeling/show_polls/ HTTP/1.1" 200 1456 [24/Mar/2019 22:56:59] "GET /static/bootstrap.min.css HTTP/1.1" 200 140376 [24/Mar/2019 22:56:59] "GET /static/font-awesome.min.css HTTP/1.1" 200 30960 [24/Mar/2019 22:56:59] "GET /static/Contact-Form-Clean.css HTTP/1.1" 200 1495 [24/Mar/2019 22:56:59] "GET /static/jquery.min.js HTTP/1.1" 200 86658 [24/Mar/2019 22:56:59] "GET /static/styles.css HTTP/1.1" 200 0 [24/Mar/2019 22:56:59] "GET /static/Navigation-Clean.css HTTP/1.1" 200 1788 [24/Mar/2019 22:56:59] "GET /static/Features-Blue.css HTTP/1.1" 200 1135 [24/Mar/2019 22:56:59] "GET /static/bootstrap.min.js HTTP/1.1" 200 70808 So, I assume that it finds the files. However, the browser renders only the pure html without css/bootstrap. This is the html code: {% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static '/bootstrap.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/font-awesome.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/Contact-Form-Clean.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/Features-Blue.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/Navigation-Clean.css' %}"> <link rel="stylesheet" type="text/css" href="{% … -
django 2: Filter models by every day of current month
I got a simple models like this: class CurrentMonthRegisterPage(models.Manager): """This manager class filter with current month.""" current_date = datetime.now().date() def get_queryset(self): return super(CurrentMonthRegisterPage, self).get_queryset().filter( detail_hour__month=self.current_date.month, detail_hour__year=self.current_date.year) class RegisterPage(models.Model): OTHERS = '4' EXTRA_TIME = '3' EARLIER = '2' ON_TIME = '1' LATE = '0' ABSENT = '-' STATUS_LIST = ( (LATE, _("Late")), (ON_TIME, _("On time")), (EARLIER, _("Earlier")), (EXTRA_TIME, _("Extra time")), (OTHERS, _("ND")), (ABSENT, _("Absent")), ) detail_hour = models.DateTimeField(_('Date and hour'), auto_now_add=True) details_mouvement = models.TextField(_("Déscription"), blank=True) state = models.CharField(_("Statut"), max_length=1, choices=STATUS_LIST, default=ABSENT) objects = RecentManager() c_month = CurrentMonthRegisterPage() Now i want to get a number of every state of every day of current month Example: Current month is March How to get a number of state==LATE of every day of march ? I want to get something like this: queryset = [{'late':[1,1,3,5,....31], 'other_state': [1,2,...], ...}] Please help ? -
django eager loading one-to-many relationships
Simple question, I've searched and can't figure this out... How do I setup eager loading in django? class Album(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) title = models.CharField(max_length=255) description = models.CharField(max_length=255, blank=True) class Photo(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) name = models.CharField(max_length=255) photo = models.ImageField(upload_to='photos/%Y/%m/%d/') albums = Album.objects.filter(user=request.user).all() for album in albums: photos = album.photo_set.all() for photo in photos: print(photo.name) print(photo.photo) I now want to retrieve all albums and all photos, with a single call to the DB. albums = Album.objects.filter(user=request.user).all() I've looked at select_related() and prefetch_related() but these looks to be for the reverse (getting the album object at the same time as the photo objects, when querying against the photo object) -
Django AppRegistryNotReady:models arent loaded yet- reverse Foreign Key query between two apps
I am trying to create a ratings app for a news aggregation site, but I think either my implementation of the apps or the foreignkey queries from ratings to articles is wrong. I keep getting raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. when migrating. The idea is that each user's individual rating of an article is handled by ArticleRating, and then each article would have an average score handled by OverallArticleRating I think the issue goes down to one of 3 things: 1. the user ratings should be implemented as a model in the articles app, then referenced by the OverallRatings model. 2. my foreign key queryset syntax is incorrect. I have tried using article.articlerating_set for the queryset of ArticleRating objects, but that only returns attribute not defined. 3. I need to reference the article object associated with each rating object differently. from django.db import models from users.models import User from Articles.models import Article class AbstractRating(models.Model): score = models.IntegerField() def __str__(self): return str(self.score) class Meta: abstract = True ordering= ['-score'] class ArticleRating(AbstractRating): article = models.ForeignKey(Article, on_delete=models.CASCADE) rater = models.ForeignKey(User, on_delete=models.CASCADE) class OverallArticleRating(AbstractRating): article = models.ForeignKey(Article, on_delete=models.CASCADE) def getArticleAverageScore(art): sumUserScore = 0 averageUserScore = 0 ratingSet = ArticleRating.objects.filter(article=art) … -
Is it possible to build an online judge using Python Django Framework?
I have started learning Django Framework for a while. My final year project is to build an online judge for the campus students. Now I am confused about a lot of things, especially the compiler and integrating it to the site. Can anyone give me a proper guideline? I know it is a stupid question but trust me I have googled and all I found was scattered information. Thank you -
Django - authentication, registration with email confirmation (2019)
I was looking to create a authentication, registration, password reset and email confirmation using Django. Workflow: Displays form to enter username, email address, password, sends verification email, to email to be verified. user is inactive until link verification is complete. option to reset password through this page I found this question posted in 2011 Django - authentication, registration with email confirmation Summary: django-allauth, last commit 25 days ago django-registration, last comitt 4 months ago any others? Questions: Since it is 2019 I thought to ask again and see what people recommend and use in 2019? which do recommend and why? (easy of use, documentation, industry standard, involved community? etc.. ) thanks for the help -
django admin override filter_horizontal
I'm aiming to make an "advanced" filter_horizontal, one with more filters, but I can't seem to find the widget to override. I know it uses the related_widget_wrapper.html, but if I want to add functionalities to it in a clear way, what is the widget to override. For now my backup solution is to do a full javascript solution to prepend it with a dropdown on form load (created from javascript) and make ajax calls to modify the filter...but this seems as an overkill. -
Querying Django database with Jquery and Ajax
I have a POST request that passes data to my database when the form is submitted. home.html <script type="text/javascript"> $(document).ready(function(){ var postForm = $(".form-post") //POSTING DATA INTO DATABASE postForm.submit(function(event){ event.preventDefault(); var thisForm =$(this) var actionEndPoint = thisForm.attr("action"); var httpMethod = thisForm.attr("method"); var formData = thisForm.serialize(); $.ajax({ url: actionEndPoint, method: httpMethod, data: formData, success:function(data){ console.log(data) $(".form-post")[0].reset(); //I WANT TO PASS THE NEWLY ADDED DATA TO DISPLAY WITHOUT REFRESH $.ajax({ type: 'GET', url: '{% url "postInfo" %}', dataType : 'json', success: function(cdata){ $.each(cdata, function(id,posts){ $('#cb').append('<li>' +posts['fields'].title+ ' ' +posts['fields'].body+ '</li>'); }); } }); }, error:function(errData){ } }) }) }) </script> As it is now it shows multiple of the same posts every time I add a post. This is my views views.py def postInfo(request): # GET REQUEST if request.method == 'GET' and request.is_ajax(): mytitle = Post.objects.all().order_by('-date_posted') response = serializers.serialize("json", mytitle) return HttpResponse(response, content_type='application/json') } def posting(request): # POST REQUEST if request.method == 'POST' and request.is_ajax(): title = request.POST.get('postTitle') content = request.POST.get('postContent') post = Post() post.title = title post.body = content post.author = request.user post.save() return HttpResponse('') models.py class Post(models.Model): title = models.CharField(max_length=50) body = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title How can I make it so … -
Uploading different files on the web and rendering thumbnail preview
I am trying to render thumbnails for different files when uploaded on to the webpage, ( say, if i upload a word document or a pdf, it should render a thumbnail preview of that file, ex-google drive). I tried using ImageMagick but unable to get the results, Need help. thanks -
Django how to get two models in relation?
At my django application users are able to buy specific posted elements. To later-on display a content_preview or the full content of a post i created a "helper_model" -> Post_Paid_Sell_Tut to check if a user has paid for the post or not. My target is that i can later on display the peview or full content accordingly to the paid or unpaid status but i dont clearly understand how to get those two models in relations at my views.py i created the following two models for this: class Post_Paid_Sell_Tut(models.Model): paying_user = models.ForeignKey(User, on_delete=models.CASCADE) post_sell_tut = models.ForeignKey(Post_Sell_Tut, on_delete=models.CASCADE) status = StatusField(default='unpaid') STATUS = Choices('unpaid', 'paid') paid_date = models.DateField(auto_now_add=True) .... class Post_Sell_Tut(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=40) content_preview = models.TextField(verbose_name="Tut Content Preview", max_length=500) content = EncryptedTextField(verbose_name="Tut Content", max_length=10000) ..... now i want to understand how i can bring those two models in relations at my views.py. In the end the user will see a form with only a Buy button and some Text. after he hits the button the status should get changed from unpaid to paid for the paying user. my current views.py def post_sell_tut_buy(request, pk): post = get_object_or_404(Post_Sell_Tut, pk=pk) if request.user == post.author: messages.error(request, 'You cant buy your … -
Django - how to display usermembership status in profile view
I am a student and currently studying Django. I am working on a project now where I already have a model for user membership. How can I make the user membership status displayed in the user profile page? Here's the membership model: class Membership(models.Model): membership_type = models.CharField(max_length=50) price = models.IntegerField(default=100) description = models.CharField(max_length=200) def __str__(self): return self.membership_type class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) membership = models.ForeignKey(Membership, on_delete=models.CASCADE, null=True) reference = models.CharField(max_length=50, null=True) def __str__(self): return self.user.email Here's the profile views.py: def profile(request): ```some update profile post code here``` context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) -
can't able to access css file from html templates
i can load my templates but can't load css...while i see, view source code in browser and access css file from there it show the error "Page not found (404)" 'css\index.css' could not be found i have tried all the things from doc but i don't know where im missing settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES_DIR = os.path.join(BASE_DIR, "templates") INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'parking', 'DIRS': [TEMPLATES_DIR, ], STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] app urls.py from django.urls import path from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns +=staticfiles_urlpatterns() urlpatterns = [ path('', views.index) ] urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('parking.urls')) ] -
Nested for loop over objects that returns unique key value pair dict
Maybe a title is confusing but here is my problem. I go through django model objects with nested for loop as below. In the end I want to have dictionary which has unique key value pairs. Below code works but I don't feel that it's really efficient. settings = [] for feature in features: for setting in feature.settings.all(): settings.append({"name": setting.name, "active": setting.active}) return [dict(t) for t in {tuple(setting.items()) for setting in settings}] so before return I am having something like this: [{'name': 'x', 'active': False}, {'name': 'y', 'active': True}, {'name': 'x', 'active': False}] but when I return I remove duplicates in the list and return below. [{'name': 'x', 'active': False}, {'name': 'y', 'active': True}] -
how to write decorator function inside a permission class
I want my API to be accessed by everyone but all privileges to be given to faculty. decorators.py def faculty_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='login'): actual_decorator = user_passes_test( lambda u: u.is_active and (u.is_faculty or u.is_admin), login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator view.py class ProfileView(viewsets.ModelViewSet): queryset = Profile.objects.all() serializer_class = ProfileSerializer def get_permissions(self): if self.action == 'list': permission_classes = [] else: permission_classes = [faculty_required] return [permission() for permission in permission_classes] So above I have written inside permission_classes about [faculty_required] It's showing error. What will be the right way to write facuty_required so that only faculty can do anything including get. -
Is there a way to create more options than 'choices' in Wagtail Form Builder
I'm writing a new web page which should work also as enrollment platform to certain events. I would like to add options['prices'] on the side of options['choices'] in multiselect field. Now there is a field for choices where choiceas are separated with comma, i want another to enter price difference from a default value depending on the choice (floats, though handling these can be done elsewhere) like "1, 2.5, -1, 0" . In the end of form it should count sum of default value and all possible selections. I have tried to modify wagtail.contrib.contrib.forms.FormBuilder.create_multiselect_field without success. Is there a way to add this kind of functionality, basically just one additional options input? -
Optimize Django Rest ORM queries
I a react front-end, django backend (used as REST back). I've inherited the app, and it loads all the user data using many Models and Serializes. It loads very slow. It uses a filter to query for a single member, then passes that to a Serializer: found_account = Accounts.objects.get(id='customer_id') AccountDetailsSerializer(member, context={'request': request}).data Then there are so many various nested Serializers: AccountDetailsSerializers(serializers.ModelSerializer): Invoices = InvoiceSerializer(many=True) Orders = OrderSerializer(many=True) .... From looking at the log, looks like the ORM issues so many queries, it's crazy, for some endpoints we end up with like 50 - 60 queries. Should I attempt to look into using select_related and prefetch or would you skip all of that and just try to write one sql query to do multiple joins and fetch all the data at once as json? How can I define the prefetch / select_related when I pass in a single object (result of get), and not a queryset to the serializer? Some db entities don't have links between them, meaning not fk or manytomany relationships, just hold a field that has an id to another, but the relationship is not enforced in the database? Will this be an issue for me? Does it … -
How to change Imagefield representation in the admin panel from default "XXXobject some ID" to a parent's field data name?
I have 2 models: parrent model BoatModel and child model BoatImage connected via ForeignKey. (boats contains images, one to many) I would like to ask any way how to change child model's representative name in Admin panel from the default "object" name to a parent's model "boat_name" field. Child model has only 1 ImageField and does not have name, or title fields. In another words in admin panel each image object should carry a name of the connected boat_name field of the boat model.Or any other meaningful option of representation child model in admin panel... Thank you Tried list_display, but it doesn't work. __STR__ obviously doesn't work as well. #ADMIN from django.contrib import admin from .models import * class BoatsAdmin(admin.ModelAdmin): list_display = ("boat_name", "boat_length", "boat_mast_type", "boat_keel_type", ) list_display_links = ("boat_name",) search_fields = ("boat_name",) admin.site.register(BoatModel, BoatsAdmin) admin.site.register(BoatImage, ) # MODELS from django.db import models class BoatModel(models.Model): SLOOP = "SL" KETCH = "KE" YAWL = "YA" CAT_KETCH = "CK" CHOICES = ( (SLOOP, "Sloop"), (KETCH, "Ketch"), (YAWL, "Yawl"), (CAT_KETCH, "Cat Ketch"), ) boat_name = models.CharField(max_length=50, unique=True, verbose_name="Boat model", help_text="Please input boat model") boat_length = models.FloatField(null=False, blank=False, verbose_name="Boat water-line length", help_text="Please input boat water-line length") boat_description = models.TextField(blank=True, verbose_name="Boat description", help_text="Please describe the … -
Django NameError: request is not defined
I am trying to add search functionality into my website. But I cannot seem to find a video that is using class based views. Views: class IndexView(ListView): model = Post # queryset = Post.objects.filter(live=True) template_name = "public/index.html" def get_queryset(self): query = request.GET.get("q") if query: queryset_list = queryset_list.filter(title_icontains=query) def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['queryset'] = Post.objects.filter(live=True) context['category'] = Category.objects.all() return context HTML: <form method='GET' action=''> <p class="text-muted">Keywords:</p> <input type="text" name='q' class="homebanner-search" placeholder="Enter your keywords"> <input type="submit" value="search"> </form> When I try and run the server I get a 'NameError: name 'request' is not defined. I feel like there are some more things I need to add but I am not sure what else I need to do to get this working.