Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django expire reservation
Hello I'm writing a simple app for reserving and buying the tickets in in cinema, one of the task is to reserve a ticket for some time (ex. 1 hour) its then in pending status and can be paid withing this period. Do you have any recommendation how to achieve expiration time? I have a field in Model storing the date that can be used. -
Is it required to compare social access token with Social Email ID in Social Auth?
When using Social Auth, Email ID is auto validate with Social(Google, FB) account. But I want to develop api for social auth.Mobile developer are using GOOGLE/FB SDK and provide me email. Issue: Is Social access token require, so comparing it with email ID received and then process the data if social access token received from social auth matched with Email? -
Django - Join on specific column
I have a model, let's call it Notification. A notification has a from_user, and a to_user among other fields which are not important right now. class Notification(models.Model): from_user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='from_user' ) to_user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='to_user' ) read = models.BooleanField(default=False) ... What I want to achieve is, in theory, very simple, but I can not get it to work. I would like to get the count of unread notifications for every user. The following Django ORM expression: User.objects.annotate( notification_count=Count('notification', filter=(Q(notification__read=False))) ).values('notification_count') Produces the following SQL: SELECT COUNT("notification"."id") FILTER (WHERE "notification"."read" = False) AS "notification_count" FROM "account" LEFT OUTER JOIN "notification" ON ("account"."id" = "notification"."from_user_id") GROUP BY "account"."id" ORDER BY "account"."member_since" DESC But this is not what I want. I want the LEFT_OUTER_JOIN to be done on the to_user column, not the from_user column. How can I achieve this using the Django ORM? -
How to create SaaS application with Python and Django 2019
Can you give me some examples of saas applications (free code), I'm already in the devepment phase but I don't have a clear model data to work with de multi tenancy -
Using pagination with django-filters
I want to add the pagination alongside with django-filters in the template. What should I write in pagination and how should I loop over my list of filtered vehicles? I've written the pagination in the HTML template, but it doesn't work with filtered results. When I go to the next page, I get all the vehicles (not filtered) again and again. class VehicleFilter(django_filters.FilterSet): model = django_filters.CharFilter(lookup_expr='icontains') year = django_filters.RangeFilter() mileage = django_filters.RangeFilter() price = django_filters.RangeFilter() class Meta: model = Vehicle fields = ['brand', 'model', 'year', 'mileage', 'price', ] def search(request): vehicle_list = Vehicle.objects.all() vehicle_filter = VehicleFilter(request.GET, queryset=vehicle_list) paginator = Paginator(vehicle_filter.qs, 1) page = request.GET.get('page') try: vehicles = paginator.page(page) except PageNotAnInteger: vehicles = paginator.page(1) except EmptyPage: vehicles = paginator.page(paginator.num_pages) return render(request, 'sale/vehicle_list.html', { 'vehicles': vehicles, 'page': page, 'vehicle_filter': vehicle_filter, }) <div class="pagination"> {% if vehicles.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ vehicles.previous_page_number }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}">previous</a> {% endif %} <a href="#" class="active">Page {{ vehicles.number }} of {{ vehicles.paginator.num_pages }}</a> {% if vehicles.has_next %} <a href="?page={{ vehicles.next_page_number }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}">next</a> <a href="?page={{ vehicles.paginator.num_pages }}{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}">last &raquo;</a> {% endif %} </div> Could you help me with the pagination … -
How to create Django model from MySQL table on-fly?
I have a DB with tables created on the fly. (via the 'pandas' module: ds.to_mysql ('BACTH_INPUT_XXX') I plan to use a dynamic model to display tables using 'django-datatables-views'.) How to create a Django model on the fly? I find: def create_batch_input_model(batch_id): name = "BatchInput{}".format(batch_id) fields = { 'first_name': models.CharField(max_length=255), 'last_name': models.CharField(max_length=255), } model = create_model(name, fields, app_label='dynamic', module='core.batchs',) return model How to populate model fields from MySQL table? -
Prefetch related with a filter that contains a field of the original model
If I have Model A with a ForeignKey to Model B, how can I prefetch Model A from Model B using some criteria in Model B? This is something what I would want (OuterRef obviously only works in a SubQuery, but this is basically the functionality I need): class ModelA(models.Model): somecriteria = models.CharField() class ModelB(models.Model): somerelation = models.ForeignKey(ModelA) someattribute = models.CharField() qs = ModelA.objects.all() qs = qs.prefetch_related( Prefetch( 'modelb_set', queryset=ModelB.objects.filter(someattribute=OuterRef('somecriteria')), to_attr='some_attr' ), ) The query is supposed to do the following (in less queries): for obj in qs: # Change this to new_qs = obj.some_attr if prefetch is working. newqs = obj.modelb_set.filter(someattribute=obj.somecriteria) if newqs.exists(): # Do something -
Use of if condition in get_absolute_url
I've developed a solution for put offline a post if it is a draft or a scheduled post. Now, that I want do is allow to see this type of post only if the user is_staff, then I try to use this: models.py class BlogPost(models.Model): title = models.CharField(max_length=70) slug_post = models.SlugField(max_length=70) publishing_date = models.DateTimeField() draft = models.BooleanField(default=False) category = models.ForeignKey(..) def __str__(self): return self.title @property def is_future(self): if self.publishing_date > datetime.datetime.now(): return True return False @property def is_draft(self): if self.draft == True: return True return False def get_absolute_url(self): if self.is_draft or self.is_future: return reverse("adminblogpost_preview", kwargs={"slug_post": self.slug_post}) else: return reverse("single_blogpost", kwargs={ "slug_post": self.slug_post, "slug_category": self.category.slug_category, }) decorators.py def staff_only(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='login'): actual_decorator = user_passes_test( lambda u: u.is_active and u.is_staff, login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator views.py def singlePost(request, slug_post, slug_category): category = get_object_or_404(BlogCategory, slug_category=slug_category) blogpost = get_object_or_404(BlogPost, slug_post=slug_post, draft=False, publishing_date__lte=timezone.now()) category_blogpost = BlogPost.objects.filter(category=category) context = { "category": category, "blogpost": blogpost, "category_blogpost": category_blogpost } return render(request, "blog/reading/single_post.html", context) @staff_only def singleOfflinePost(request, slug_post): status = BlogPost.objects.filter(draft=True, publishing_date__gte=timezone.now()) blogpost = get_object_or_404(status, slug_post=slug_post) context = {"blogpost": blogpost} return render(request, "blog/reading/single_post.html", context) urls.py path("<slug:slug_category>/<slug:slug_post>/", views.singlePost, name='single_blogpost'), path("preview/", views.singleOfflinePost, name='adminblogpost_preview'), If I use this solution I see this error message: NoReverseMatch at /backend/blog-posts/ Reverse … -
NoReverseMatch with arguments '(",)' in Django
I keep getting the NoReverseMatch error although I have checked numerous times to see if I have entered the code as instructed, and it seems I did, yet the webpage won't load properly. Because I have a few files and I don't know which one has the error (it should be urls.py but I just don't see where the error is located) I will post a link to my GitHub repository where I have uploaded all relevant files and a screenshot of the error message I've been getting. Sorry for not posting any code but I think it would make it very messy posting all the code here. Also, I saw a lot of similar questions but none of them solved my problem and none of them are with these exact arguments. GitHub repo: https://github.com/DjoleRkc/Python-Crash-Course-error-p.435.git -
Authenticate an API call correctly with requests and sessions
I want to call my own API in a custom view I wrote. Normally I use JWT authentication with my API calls. In this specific view though, I'd like to use a different authentication. I want to enable logged in users to make a successful get call (without a token). Not logged in users should not be able to make that call. I tried this with Basic Authentication and Session Authentication but don't really get it tow work. Here is my view that makes the API call: def visualize_buildings(request, id): passed_id = id endpoint = 'linktomyendpoint' + str(passed_id) response = requests.get(endpoint) building_group_data = response.json() # print(building_group_data) if 'buildings' in building_group_data: building_data = building_group_data['buildings'] context = {'building' : building_data} return render(request, 'building_group_visualize_api.html', context) else: return HttpResponseNotFound("Ups. We are sorry but no Building Group was found with that id") Here my API view: class BuildingGroupRetrieveAPIView(RetrieveAPIView): authentication_classes = [JSONWebTokenAuthentication, SessionAuthentication, BasicAuthentication] serializer_class = BuildingGroupSerializer queryset = BuildingGroup.objects.all() The view works with if I send a token in the headers. But how can I use Session Authentication with that? I tried getting username and password from the request and then pass it to the API call. But that doesn't work because I can't decode … -
Failed to Build mysqlclient ,Wheel cannot build. pip install mysqlclient not working
The problem have been faced by many including myself. You cannot use the command pip install mysqlclient directly for the latest build for python 3.7.4 or any 3.7.X . It is mentioned on the PyPI website that new wheels are not given the latest release of mysqlclient. -
3rd party private API key get from the user on the client end and stored in db - how to make it safe?
I am working on a django+react project that requires 3rd party private API key. My idea is, that user provides the private key once logged in to my app and the key is stored in the django's db and using it requires the user to be authenticated an authorized. I would make the API calls using the private key on the server side. However, I am wondering if I should extra secure the process of providing the key on the client side - ex. if the key can be stolen when being provided by the user as an input and before it gets stored in the db, where is should be safe as I understand. What steps should I take, to make the api key providing process safe? -
How to update Django variable passed through context using Ajax
I've spent quite some time trying to solve this, I've seen a bunch of solutions but I just can't seem to wrap my ahead around this. So basically, I have this view in which I pass an array I want to display in the template and an index (arr in the view), which is the index of the array that I currently want to display. Meaning that when I first load the page the index will be 0 and I will display the first element of said array. Then, I wanted to update this index variable (by clicking the X button) so I can display the next elements (2, 3 and 4) of the array without reloading the page. I figured I can do this using an Ajax Query however, I can't get seem to get the value to update in the template. Thank you in advance! results.js (function () { //automatically called as soon as the javascript is loaded window.addEventListener('load', main); }()); function update_display_counter(e, display_counter){ const $csrf_token = $('input[name="csrfmiddlewaretoken"]').attr('value'); display_counter++; $("#arr_counter").val(display_counter); $.ajax({ headers: { 'X-CSRFToken': $csrf_token }, url: "/establishments/results/", dataType: "json", type: "POST", data: { 'arr_counter': display_counter, }, success: function (json) { console.log(json) }, }); return display_counter; } function … -
In Django REST Framework, how to set default fields for a form which the value is taken from the GET request's parameter?
Disclaimer: Same code with In Django REST Framework, how to get the "query parameter" sent by the previous page's hidden input?, but it this a different question here. I have an html page for listing the model "Descriptions", and at the end of it there's a button to go to the Description creation page, while sending the "character_id" that is intended to be a default initial value for the new Description: <!--The code for listing the Descriptions--> <form action="{% url 'polls:description_detail_create_from_character' %}"> <input type="hidden" value="{{ serializer.context.character_id }}" name="character_id"> <input type="submit" value="New Description"/> </form> On the browser, if I click "New Description", it will bring me to: http://localhost:8000/polls/description_detail_create_from_character/?character_id=3 As for this create View, I can get this "character_id" by context.get('request').GET.get('character_id', ''), however I am not sure is it possible to access this value when I later POST this create page as I want the field "character" to default to the 'character_id'. The problem is, as how serializers.HiddenField(default=serializers.CreateOnlyDefault(...)) works, it will only try to assign the value when POSTing, but when POSTing where can I find this character_id=3? Does it mean I have to hide this "query parameter" character_id=3 somewhere in the html when processing GET, and when late POST have the … -
How to update multiple tables in Django?
I'm new to Django, Please help. Need to update multiple tables in dJago? Tried this: obj, created = Person.objects.update_or_create( first_name='John', last_name='Lennon', defaults={'first_name': 'Bob'}, ) -
Django: prevent manual values on AutoField?
Using the default django's id attribute, inserting id=x in created objects is allowed. Problem is, this breaks the auto-incrementing sequence for subsequent inserts (at least, on postgres, where I use it). Is there a way to forbid explicitly passing an id value to created objects? -
How to use django for tranfering webform data to database?
I have already created a web project using html. But I was using formspree for getting data from webform to mail. Now I want to implement the same for only the form and all the other links should work fine I have tried single form page. But I have used html links. I have problems in linking only(*) the form to django. All other pages should work fine As I started with project I didn't have future scope. Anything in which I can do to just I should be able to see the data of the form in the django-admin panel. -
How to show the payment which is assigned to user in html page of django?
I have assigned some random numbers as a balance to every user who sign up but I am not able to show them in html page. How to do it? Maybe I have made some mistakes in python files also. I have added those balance(numbers) in my database. So please let me know. models.py class Payment(models.Model): payment_numbers = models.CharField(max_length=100) owner = models.ForeignKey(User, on_delete=models.CASCADE) views.py def payment(request): receiving1 = Payment.objects.filter(owner=request.user) for field in receiving1: field.payment_numbers context = { 'receiving1': receiving1 } return render(request, 'index.html', context) HTML page {% for numbers1 in receiving1 %} <li style="float: right;">Your Balance: Rs. {{numbers1.payment_numbers}}</li> {% endfor %} Python Shell >>> from users.models import Payment >>> Payment.objects.all() <QuerySet [<Payment: Payment object (1)>, <Payment: Payment object (2)>]> -
Celery\Luigi transaction problems
I am building a django webapp using Luigi framework and Celery. Luigi is used for running a complex pipeline with different workers. Celery allows me to run asynchronous processes, so when I run the pipeline I can still navigate the application. I m using Django ORM to comunicate with a PostgreSQL database. The queries are run from the pipeline (many workers) and the webapp views. Sometimes I get random error like: 'no results to fetch', 'pop from empty list', 'error with status PGRES_TUPLES_OK and no message from the libpq', 'Save with update_fields did not affect any rows.' So I tried to use transaction atomic each time I am running a query. with transaction.atomic(): self.analysis_obj = Analysis.objects.select_for_update().get(pk=self.analysis_id) However I get the same errors. Any idea to deal with this problem? Many thanks. -
How do i run redis in background of deployed website just like i run redis server manually when on local host?
I have been using redis server on my windows for websocket programming in my chat project django. Now, the time of deployment has arrived and i do not know how to run the server on the deployed website. -
How to change browse button upload ImageField to drag drop upload on Django Admin
Currently I have inline list of photos like this : I wish to change the browse button as drag drop upload, does anyone can help to make it ? here is my current code : model.py class PlacePhoto(models.Model): name = models.CharField(max_length=30, blank=True, null=True, default="") original_photo = models.ImageField( 'photo', upload_to='place') photo = ImageSpecField( source='original_photo') thumbnail = ImageSpecField( source='original_photo') place = models.ForeignKey('Place', on_delete=models.CASCADE, related_name='place_photos') admin.py class PlacePhotoInline(admin.TabularInline): model = PlacePhoto extra = 1 fields = ('name', 'display_image', 'original_photo',) readonly_fields = ('display_image',) def display_image(self, obj): return mark_safe(f'<img src="{obj.original_photo.url}"' f' width="{300}" height={200} />') -
Does django's `save()` create or update?
The documentation just says To save an object back to the database, call save() That does not make it clear. Exprimenting, I found that if I include an id, it updates existing entry, while, if I don't, it creates a new row. Does the documentation specify what happens? -
Django localization form not swtiching
I am unable to switch languages using the example form provided in the Django docs. Translations are working if I manually change the URL language prefix. Settings.py LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale'), ] # Middleware 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', # Context Processors 'django.template.context_processors.i18n', urls.py urlpatterns = [ # Set language path('i18n/', include('django.conf.urls.i18n')), # Admin path('admin/', admin.site.urls), ] urlpatterns += i18n_patterns( path('test/', node_views.test), prefix_default_language=True, )+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) HTML {% load i18n %} {% trans "This is a test" %} <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="Go"> </form> The default form returns a 302 response to the same URL I am currently on without changing the language. The {{ redirect_to }} value in the form input does not contain a value, maybe this should be populated with something? I am … -
Send Angular PUT request to Django using Django CSRF
I am trying to update an entry into the django sqlite database using a put request. I am getting lots of 'forbidden' and '403' errors. I think this is because I can't find a way to attach the CSRF token from django. I have seen some previous answers on here but they are from much older versions of Angular and I can't figure how to edit them to work with my code. (saying to put them in the module.config() block which I can't find). Component HTML: <button class="btn btn-warning shadow-sm" (click)="update(project)">Update</button> Component TS: update(project: Project) { this.projectService.updateProject(project).subscribe(); } Service TS: updateProject(project: Project) { var httpudpdate: any = this.http.put('/ph/projects/'+project.id, project) return httpudpdate } I want the entry to be updated in the django but I am just getting errors, forbidden and 403. -
Cannot login django admin page in chrome
Unable to login in django admin page on chrome only. In previously work just fine. login with other browser like Safari and Firefox work like a charm. Can anybody please help me