Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I add Mayan EDMS to my existing Django web app?
I need a document management library to add to my existing web application. Can I add Mayan EDMS as a Django Application to my existing Django Web Application? I can't see any documentations regarding it online. -
Django - Is there a weekly calendar widget similar to when2meet.com?
I'm trying to create an application that allows a user to set a weekly schedule of when they would be available to meet. Once these set weekly schedules have been made, it would then be set to unavailable once a customer's proposal to meet is approved by the user. -
Django. Model not showing up in template
I'm making my first Django project, and I added a model in the template, but, when I'm running it, I don't see anything. but when I inspect the page, I see an h2 tag for each entry in the model. models.py from django.db import models from django.utils import timezone from django.urls import reverse class MyDate(models.Model): english_date = models.DateField(auto_now=False) hebrew_date = models.CharField(max_length=20) def __str__(self): return self.hebrew_date views.py from django.views.generic import (TemplateView,ListView,DetailView,CreateView,UpdateView,DeleteView) from luach.models import MyDate class HomePage(TemplateView): template_name = 'new.html' class MyDateListView(ListView): model = MyDate context_object_name = 'mydate' template {% extends 'luach/base.html' %} {% block content %} <div class="jumbotron"> {% for mydate in mydate %} <h2>Hi{{ MyDate.hebrew_date }}</h2> {% empty %} <h2>Sorry, no dates in this list.</h2> {% endfor %} </div> {% endblock %} -
React put method not updating the user from Django
I have a Django as backend and updating the user from postman is working fine. But when I update it via React Frontend, it replies with a success message just as in Postman, but the data was not updated. This is the update function to update: const updateData = (e) => { e.preventDefault(); const csrftoken = getCookie("csrf"); const cookies = new Cookies(); const url = "http://localhost:8000/usercontrol/update"; setIsLoading(true); fetch(url, { method: "PUT", headers: { "Content-Type": "application/x-www-form-urlencoded", Authorization: "Token " + cookies.get("token"), "X-CSRFToken": csrftoken, }, body: JSON.stringify({ email: userinfo.email, username: userinfo.username, first_name: userinfo.first_name, last_name: userinfo.last_name, }), }).then((response) => console.log("THE RESPONSE: ", response.json())); setIsLoading(false); }; This is what it prints out in the console Since I am partially following CodingWithMitch for Django user creation with rest framework is similar to his. Furthermore, since there is no error outputting and is working fine in Postman, I have no idea what is wrong with it. -
unresolved import 'rest_framework' after installing djangorestframework
I saw similar posts created before, but nothing helped me in the end. I am using Python 3.7.7 and my IDE is VSC. I installed pip install djangorestframework (both in my virtualenv and outside of it) Added 'rest_framework', to INSTALLED_APPS. Now, to used djangorestframework, I created a file serializer with from rest_framework import serializers Now, rest_framework becomes underlined with the message unresolved import 'rest_framework'. The whole app still works, there is no error in the console. What would you advise me to do? Thanks! -
Key error request in get_export_data lib django-import-export
I used this function for some time and for some reason I started getting the error: Key error request like a picture This is my code:(Error in line: data = e.get_export_data(XLSX(), queryset)) def _export_data(queryset, model, filename_prefix, resource_class): e = ExportMixin() e.resource_class = resource_class e.model = model data = e.get_export_data(XLSX(), queryset) content_type_ = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' response = HttpResponse(data, content_type=content_type_) out_format = 'attachment; filename="{0}-{1}.xlsx"'.format( slugify(filename_prefix), filename_suffix) response['Content-Disposition'] = out_format return response Obs: My lib version is 2.0.2 -
How to list all foreign keys in django inline admin?
I have two models: class PublishingRestriction(models.Model): id = models.AutoField(primary_key=True) restriction_name = models.CharField(max_length=255, null=False) def __str__(self): return self.restriction_name class Meta: managed = False class ProductRestriction(models.Model): product = models.ForeignKey(Product, null=False, db_column='product_id') id = models.AutoField(primary_key=True) restriction_type = models.ForeignKey( PublishingRestriction, null=False, related_name='restrictions', db_column='restriction_type_id', verbose_name='Restriction type', ) is_restricted = models.BooleanField(default=False, verbose_name='Restriction') reason = models.CharField(max_length=255, verbose_name="Restriction explanation", blank=True) class Meta: unique_together = ('product', 'restriction_type') managed = False And inline admin (inside ModelAdmin for Product): class ProductRestrictionInline(admin.TabularInline): model = ProductRestriction extra = 1 can_delete = False verbose_name_plural = 'Other publishing restrictions' verbose_name = 'publishing restriction' fields = ('restriction_type', 'is_restricted', 'reason') def has_add_permission(self, request): return True I want to display a list of all restriction_type (which are foreign keys) instead of having user add a new row in inline (all restriction types need to be listed in advance - even if ProductRestriction doesn't exist for given Product yet. Is there a vanilla way of achieving it? -
Django - How to see all permissions that wrap a view using custom decorator
I am writing tests for a system in an attempt to ensure that all permissions associated with the view are accurate and accessible to users that actually have the permission associated with them. We have had a few instances where misspellings made it so the view was inaccessible, so this is what I am trying to test. My admin users always have the correct permissions associated with them so naturally the easiest solution to ensure that each view will load for an admin would be to ensure that the permission decorator's permissions for each view are valid permissions stored in the database, however, I cannot seem to find a way to get a URL, resolve it, and then see what permissions are actually associated with the view. For example, here is a simple view: @permissions_required('prospects.view_prospect', 'prospects.change_prospects') def prospects(request, client_url): return render(request, 'prospects/index.html', {}) And here is the decorator @permissions_required def permissions_required(*perms, raise_error=False): """ Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary. """ def check_perms(user): allowed = all([user.has_perm(perm) for perm in perms]) if not allowed and raise_error: raise PermissionDenied return allowed return user_passes_test(check_perms) I would like to know that … -
Axes with customized django rest framework and simpleJWT
I am a beginner at Django and was building a login system. I wanted to use axes with django rest framework and simpleJWT. According to the documentation for Django-Axes: Modern versions of Django REST Framework after 3.7.0 work normally with Axes out-of-the-box and require no customization in DRF. Now I have built a Custom User for my project who gets authenticated using my own custom authentication backend. For creating the Access and the Refresh tokens I have localhost:8000/api/loginend point which creates both the tokens and stores them as HTTPOnly cookie. The login view is like this : @api_view(['POST']) @permission_classes([AllowAny]) @ensure_csrf_cookie def login_view(request): # print("captcha token = ", request.POST.get('g-recaptcha-response')) Account = get_user_model() EmailId = request.data.get('EmailId') password = request.data.get('password') response = Response() if (EmailId is None) or (password is None): raise exceptions.AuthenticationFailed('username and password required') # get the user with the credentials provided user = Account.objects.filter(EmailId=EmailId).first() if not check_user_validity(user, password): # locking the user raise exceptions.AuthenticationFailed('The credentials are invalid') else: print('user is valid') # get the token values tokenvals = get_jwt_tokens(user) response.set_cookie(key='refreshtoken', value=tokenvals['refresh_token'], httponly=True) response.set_cookie(key="accesstoken", value=tokenvals['access_token']) response.data = { 'access_token': tokenvals['access_token'], 'id': user.id } return response I can refresh the access token using localhost:8000/api/Refresh endpoint. get_jwt_token(user) returns a dictionary with both access … -
Django Q filter foreign key
I'm trying to create a search that takes input from two fields and searches using both. I know how to filter for non foreign key but trying to filter the foreign key gives the error "Related Field got invalid lookup: country" I want jobs to return the results of filtering both query and country. How can I best achieve this? model: class Job(models.Model): title = models.CharField(max_length=50) ... country = models.ForeignKey( Country, blank=True, null=True, help_text="Select if you're hiring within a specific " "country", on_delete=models.PROTECT ) view: def jobs_search(request): form = SearchForm(request.GET) if form.is_valid(): cd = form.cleaned_data jobs = Job.objects.filter(site_id=get_current_site(request).id) \ .filter(paid_at__isnull=False) \ .filter(expired_at__isnull=True) \ .filter( Q(title__icontains=cd['query'], ) | Q(description__icontains=cd['query']) & Q(country__country__icontains=cd['country']) ) \ .order_by('-paid_at') meta_desc = 'Search Results' title = 'Search Results' context = {'meta_desc': meta_desc, 'title': title, 'form': form, 'jobs': jobs} return render(request, 'job_board/jobs_index.html', context) -
Sending Emails to University Domains
Hello I have a django project where users can sign up and then they get a confirmation e-mail. Everthing works fine they are getting the confirmation and can log in afterwards except when they enter a University email. Which has a .edu domain. Then they are not getting any email. However when I send manuelly from gmail they are becoming the email. Do you know how can I solve this issue. EDIT Here are my Email settings EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = '*********@gmail.com' EMAIL_HOST_PASSWORD = '******' DEFAULT_FROM_EMAIL = '*******' EMAIL_PORT = 587 This is the template which the User should get {% autoescape off %} Merhaba {{ user.username }}, Hesabınızı aktifleştirmek için aşağıdaki bağlantıya tıklayın. http://{{ domain }}{% url 'account:activate' uidb64=uid token=token %} {% endautoescape %} I also see that the email was sent under the sent folder but nothing comes to the university mail -
How to display jinja2 template (j2 file) in HTML page with correct format?
I'm able to display jija2 template on HTML page, but the output format is not correct. current output is: Your first name is Tom Your last name is Hanks Expected output is: Your first name is Tom Your last name is Hanks Views.py from django.shortcuts import render from django import forms from jinja2 import Environment, FileSystemLoader class DbNames(forms.Form): first_name = forms.CharField(label="First Name") last_name = forms.CharField(label="Last Name") def index(request): return render(request, "emps/index.html") def form_gen(request): form = DbNames() if request.method == "POST": form = DbNames(request.POST) if form.is_valid(): file_loader = FileSystemLoader('emps/templates/emps') env = Environment(loader=file_loader) template = env.get_template('hello_world.j2') output = template.render(form.cleaned_data) return render(request, "emps/output.html", { "form_data": output }) else: print('ERROR') return render(request, "emps/users.html", { "form": form }) result.j2 Your first name is {{first_name}} Your last name is {{last_name}} -
Reverse for 'update_cart' not found. 'update_cart' is not a valid view function or pattern name
I am new in django and i am developing one application in that on click i am trying to add product in cart.To select product i am using "{%url 'update_cart' product1.slug%}"> in my template,I am including my code here. This is model models.py class cart(models.Model): product=models.ManyToManyField(products,blank=True) total=models.DecimalField(max_digits=100,decimal_places=2,default=0.00) def __unicode__(self): return "cart id: %s" %(self.id) This is views views.py def cartpage(request): c_data=cart.objects.all()[0] return render(request,'cart/cart.html',{'c_data':c_data}) def update_cart(request,slug): c_data = cart.objects.all()[0] try: product1=products.objects.get(slug=slug) except products.DoesNotExist: pass except: pass if not product1 in c_data.product.all(): c_data.product.add(product1) else: c_data.product.remove(product1) return HttpResponseRedirect(reverse("cart")) This is urls urls.py path('cart/',views.cartpage,name='cart'), path('cart/<slug:slug>',views.update_cart,name='update_cart') I have created cart model and registered it in admin...its working properly even in my cart.html page is also working,but if i try to add product on click in cart page its giving me error. please help -
Django starts putting a slash in front of my static url relative path in 3.1
I had this code that worked ok in 3.0.8 <script src="{% static 'js/main.js' %}"></script> with the value in settings: STATIC_URL = ( "static/" # /static/ for django web development, static/ for django-bakery build ) when building with bakery it works only if I supply the relative path. But since 3.1, as per their release notes: The STATIC_URL and MEDIA_URL settings set to relative paths are now prefixed by the server-provided value of SCRIPT_NAME (or / if not set). This change should not affect settings set to valid URLs or absolute paths. (https://docs.djangoproject.com/en/3.1/releases/3.1/#backwards-incompatible-3-1) it puts a / in front of my static url and the build fails. Any ideas how to avoid it? I use django bakery to bake the site into a single file, no server. -
Custom template for PasswordResetConfirmView
I am wanting to create a template for a user to enter new password and confirm password after opening the password reset link. Currently it is leading to a page with title django administration. This is my urls.py: path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), I am wanting to know what name should I use for the input fields of new password and confirm password. I searched through the internet and found out many people were using django forms which I am not doing so I wasnt able to find what the name attribute should have in input tag for passwordresetconfirmview. -
Can not restore postgreSQL dump file in AWS
I tried to restore PostgreSQL database from dump file in AWS but an error occurred. it said pg_restore: [archiver] unsupported version (1.14) in file header What should I do? -
Display products in listview by category in the category page(Django)
I am creating an ecommerce website in Django where I will have specific categories of product.Each category will be displayed on its own page in a listview. So I am looking for a template tag to display the product by category in my database in the specific category's page this is the Product model class Product(models.Model): name = models.CharField(max_length=200, verbose_name=('name')) price = models.FloatField() category = models.CharField(max_length=200, null=True, verbose_name=('category') ) available = models.BooleanField(default=False,null=True, blank=True, verbose_name=('available')) image = models.ImageField(null=True, blank=True) class Meta: verbose_name = _('produit') verbose_name_plural = _('produits') def __str__(self): return self.name The shoes category page template {% for product in products %} <div class="col-lg-4"> <img class="thumbnail" src="{{product.imageURL}}"> <div class="box-element product"> <h6><strong>{{product.name}}</strong></h6> <hr> <button data-product="{{product.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-cart">Ajout panier</button> <a class="btn btn-outline-success" href="">Voir</a> <h4 style="display: inline-block; float: right;"><strong>{{product.price}}€</strong></h4> </div> </div> {% endfor %} </div> -
How to return multiple custom filters in a function based view
So I have written three custom filters, from which I need two in my view to display them on my webpage. This is my filters.py class ProductFilter(django_filters.FilterSet): class Meta: model = Product fields = ['title'] class TagFilter(django_filters.CharFilter): field_class = TagField def __init__(self, *args, **kwargs): kwargs.setdefault('lookup_expr', 'in') super().__init__(*args, **kwargs) class MyTagFilter(django_filters.FilterSet): tags = TagFilter(field_name='tags__name') class Meta: model = Product fields = ['tags'] and my view looks this at the moment: def product_list(request): qs = Product.objects.all() product_filter = ProductFilter(request.GET, queryset=qs) tag_filter = MyTagFilter(request.GET, queryset=qs) return render(request, 'cart/product-list.html', {'filter': product_filter}) I tried to make a dictionary out of the two filters and return them in the render method, but this didn't work and they don't show up in my template, which looks like this <div class="row"> <div class="col-sm-12"> <form method="get"> {{ filter.form|crispy }} <button class="btn btn-sm amphibian-button-primary btn-block element-shadow img-audio">Submit</button> </form> </div> Can anybody guide me into the right direction? Thanks a lot! -
Django channels, how to start consuming after connecting
I'm trying to understand the flow of a consumer in Django Channels. I've written the following consumer which performs a small check on a query set and returns a result every minute. I've been able to establish connection with the WebSocket, but I don't understand how later I start consuming it, again, I need it to run the check every 60 seconds, so using sleep somehow? consumer: class CameraOnlineConsumer(JsonWebsocketConsumer): def connect(self): self.farm_name = '1' self.farm_group_name = 'farm_%s' % self.farm_name # Join farm group async_to_sync(self.channel_layer.group_add)( self.farm_group_name, self.channel_name ) # TODO: Once working, add Auth # accept connection self.accept() def camera(self, event): result = self.check_events() # Get updated camera status async_to_sync(self.channel_layer.group_send)( self.farm_group_name, # send result to group { 'type': 'check_events', 'message': result } ) @database_sync_to_async def get_events(self): return PastureEvent.objects.filter(result=8, farm_id=self.farm_name, processed=False).order_by('-time_stamp')[ :2] @database_sync_to_async def update_event(self, query_set): PastureEvent.objects.select_for_update().filter(id=query_set[1].id).update(processed=True) def check_events(self): minute_delta = timedelta(seconds=60) query_set = self.get_events() if not query_set: result = {'camera status': CameraOffline.default_detail, } return result elif len(query_set) == 1: # means that no new events has been recorded since last check. result = {'camera status': CameraOnline.default_detail, 'first time_stamp': str(query_set[0].time_stamp)} return result elif len(query_set) >= 2: # two relevant events received. difference = query_set[0].time_stamp - query_set[1].time_stamp if difference <= minute_delta: if query_set[1]: … -
Django personalized url
I need to use sub-domains (i think) on Django. I have many "room" on my project and i need to build url with name of room. Example : If i have a room named "microsoft" and my domain is http://toto.fr i want to have a final url like : "http://microsoft.toto.fr" to go in room of microsoft. I can have few room then few differents url. How its possible to have this ? Django Sub-Domains can do this ? Thanks you ! -
Generic detail view must be called with either an object pk or a slug in the URLconf
Django is giving me the following error when I try to access /domains/{domain}/{host}: Generic detail view HostDetailPageView must be called with either an object pk or a slug in the URLconf. It appears that DetailView is expecting something different than what I am providing. urls.py urlpatterns = [ path('domains/', DomainsPageView.as_view()), path('domains/<str:domain>', DomainHostsPageView.as_view()), path('domains/<str:domain>/<str:host>', HostDetailPageView.as_view()), path('', TemplateView.as_view(template_name="hosts/index.html")) ] views.py class HostDetailPageView(DetailView): template_name = 'hosts/hostdetail.html' model = Host # Populates list of enabled domains in the context def get_queryset(self): qs = super().get_queryset() filtered = qs.filter(name=self.kwargs['host']) if not filtered.exists(): raise Http404("Host does not exist") # filter by a variable captured from url, for example return filtered.first() def get_context_data(self, **kwargs): return super().get_context_data(**kwargs) -
Sending data from Django websocket channels to client using threading module
I have client react app, and django as server, i have implemented WebsocketConsumer using channels and tried to connect from client and server, it did connected successfully, once connection established i would like to create a Thread in inside connect method of **WebsocketConsumer ** and send data to cliend every after 1 second, if client disconnected kill or stop thread. below is my current implementaion Websocket Connection created successfully once connection established, creating thread to send data to client every after 1 sec import json from channels.generic.websocket import WebsocketConsumer from threading import Thread, Event import threading from time import sleep myThread = threading.Thread() thread_stop_event = Event() class ChatConsumer(WebsocketConsumer): def connect(self): print("connected==========") self.accept() # this send could able to send the messahe to client self.send(text_data=json.dumps({ 'message': {'data': 1} })) global myThread if not myThread.isAlive(): print("Starting Thread") dataThread = DataThread() dataThread.start() def disconnect(self, close_code): pass def receive(self, text_data): print(text_data, "Message from client========") #Thread creation class DataThread(Thread): def __init__(self): print("__init__") self.delay = 1 super(DataThread, self).__init__() self.count = 0 def dataGenerator(self): print("Initialising") global myThread try: while not thread_stop_event.isSet(): print("inside while") self.count = self.count + 1 # AttributeError: 'DataThread' object has no attribute 'send' self.send( {"counter": self.count}) # sleep(self.delay) # print(self.count) except KeyboardInterrupt: print("Keyboard Interrupt") … -
why this paypal-HTML code is not working?
Though I copy pasted from this link ( https://developer.paypal.com/docs/business/checkout/advanced-card-payments/#step-1-enable-your-business-account-for-advanced-credit-and-debit-card-payments ). But card_field is not working as well as it's not showing paypal-button-container. -
How to make a correct get queryset with a list in Django to get values
I have a list of languages. For example languages = ['Russian', 'English', 'German', 'Italian', 'French'] And I need to get the id of each language. I'm trying to do it the following way: languages = ['Russian', 'English', 'German', 'Italian', 'French'] languages_to_save = [] for l in languages: lang_id = Language.objects.get(lang = l) languages_to_save.append(lang_id) But I have an Error: Language matching query does not exist. Though if I change the line to any lanugage in the list, it works correctly. For example: lang_id = Language.objects.get(lang = 'German') Can anyone help with this? -
XMLHttpRequest.send(data) not delivering data to Django view function
Using pure Javascript, my goal is to recreate jQuery's .autocomplete() function for displaying a list of suggestions as a user types input into the search bar. I have written code that listens for "keyup/change/paste/input" events on the input element, i.e search bar. As the user types, I wish to use an XMLHttpRequest GET (or POST) request which will deliver the user's input so far (and information about the search context -- not relevant) to a view function which will in turn filter a Model for objects containing the user's input so far and return those objects in a JSONResponse list to the XMLHttpRequest so that I can display the suggestions on the webpage. I tried to use both GET and POST requests but the data I wished to send to the view function using XMLHttpRequest.send(data) never seemed to deliver to the view function thus inhibiting my progress. In all attempts, printing request.POST (or request.GET) gave empty an QueryDict: <QueryDict: {}> Below are some code snippets: \\ The below JS code is run on once the page is ready, i.e fully loaded addListenerMulti(query, "propertychange change click keyup input paste", function () { // check if value has changed... if (query.value != …