Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sub inline_formset django
I'm creating a Web site to enter the prices of differents products of differents product places(restaurant, Supermarket, Drug Store) A user can enter many product places A product place can have many products A product place(like restaurants) can have many menus So I have three models : 1. The first is "ProductPlace" that has as foreignKey the website user model ("User") The second is "Product" that has as foreignKey the "ProductPlace" model The Third is "Menu"(like restaurant menu) that has also as foreignkey the "ProductPlace" model I created formsets associated to these three models in the "forms.py" file. #forms.py from django import forms from .models import * from django.forms.models import inlineformset_factory, modelformset_factory from django.contrib.auth import get_user_model User = get_user_model() class ProductPlaceForm(forms.ModelForm): name = forms.CharField(label='Nom', widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Nom du point de vente' })) num_road = forms.IntegerField(label='Numero', widget=forms.NumberInput( attrs={'class': 'form-control', 'placeholder': 'Numero de la rue'})) name_road = forms.CharField(label='Nom de la rue', widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Nom de la Rue' })) postal_code = forms.IntegerField(label='Code Postal', widget=forms.NumberInput( attrs={'class': 'form-control', 'placeholder': 'Code Postal'})) city = forms.CharField(label='Ville', widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Ville' })) country = forms.CharField(label='Pays', widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Pays' })) class Meta: model = ProductPlace fields=['name', 'num_road', 'name_road', 'postal_code', 'city', 'country'] ProductPlaceFormSet … -
JPEG image with filename patern DSC*.JPG are not rendered
I am using django 2.2 to upload imaged files. Files are uploaded correctly in MEDIA_ROOT. Most images are rendered as expected. Except for the ones with filename like "DSC*.jpg" which were not rendered even though the image tag as seen in inspect correctly pointing to actual files in the media directory. Anyone experienced this problem before? I would really appreciatred it if anyone could shed some light into this problem. There were no error messages. The images just weren't rendered. I am at a lost and ready to implement a clean_filename method for these DSC* files, or change the filename before saving. But only if it is absolutely necessary. pax -
MySQL display data with Django
I'm a beginner at Django and Python. I'm trying to query a MySQL database. Entering the data from the admin section works fine. Queering the database doesn't give an error, but it doesn't work. I tried querying from shell, and it worked perfectly. However, querying from the code section doesn't. The models.py looks like this: class Courses(models.Model): course_title = models.CharField(max_length=200) course_image = models.ImageField(upload_to='course_images/') course_duration = models.TimeField() def __str__(self): return self.course_title The views.py looks like this; from django.shortcuts import render from .models import Courses def homepage(request): cos = Courses.objects.all() context={ 'courses': cos } return render(request, "main/home.html", context) The home.html looks like this: {% for cos in courses %} {{cos}} {% endfor %} I tried using Courses.objects.all and also Courses.objects.all() but it still won't work. I really need some assistance. -
Get all users with userGroups
I am trying to write a method which can return all the users from django defaultDb. The following would result in giving me all the users: User.objects.all() Now, I want to add usergroups to each of the user as part of my response. I know I can parse every user and get usergroup like: user.groups.values_list('name',flat=True) But I feel this is very expensive operation as it involves n read from Db for n users. Is there any other better way to do this? -
Django (DRF): filter inside of page when using pagination
I need to perform some not so trivial filtering on the database objects, including splitting the QuerySet into two parts, manipulating one of them, and then returning them as a list. This is the starting point: def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if not page: # I need to filter on the objects returned by `page` The thing is, because I don't want to iterate over all instances, I don't want to use queryset (which is the list of objects before we apply the pagination). On the other hand, page, while it does contain only the instances that we do want to iterate on, isn't a queryset but a list, so we can't use filter() on it. Here's what I came up with for now, but this feels hacky, and __in is known not to scale to well: if page is not None: post_ids_in_page = [x.id for x in page] # now we have the relevant post ids q = Post.objects.filter(id__in=post_ids_in_page) # get the queryset # now filter other_posts = q.filter(scopes__isnull=True) member_posts = q.filter(scopes__isnull=False) # we later perform some additional manipulation on one of these querysets # on a per-object/per-user basis, hence the need to … -
Django annotate multiple objects based on multiple fields on a M2M relationship
I want to efficiently annotate Model A objects based on some fields on model B which has a M2M to A. I tried this but it's not correct: a_qs = A.objects.filter(id__in=ids) ordered_qs = a_qs.order_by('-b__created_timestamp') oldest_qs = Subquery(ordered_qs.values('b__name')[:1]) result = list(a_qs.annotate(name=oldest_qs)) This annotates every A with the same oldest name of B across all B's related to A, but I want the oldest B among those Bs associated to each A. -
Django and a custom subscription payment gateway - how to get started?
I want to create a simple subscription payment system for my personal project (single price + trial). I decided to use Django. Unfortunately, everything I find is about Stripe and I don't know how to get started. I live in a country that Stripe doesn't support so I need to use something else. How can I implement a custom gateway? Payment gateway I decided to use is a little different than Stripe. Every time I want to get the payment I need to run a script that is sending a request to the gateway's API (it is basing on ID from previous payments). I choose the period (so I think I need to run scheduled tasks) and the payment amount. I think that I can write a single task, ran every day, which could look for database records with expired licenses. Also, I want to offer a trial period for my clients and I need to have a possibility to check the license status by API, but I think I can somehow figure it out with a basic plan of the subscription system -
How to import multiple images to a Django app
I have a simple model with a title and an asset field. asset is a FileField. This is not something user facing, it's only available through the Admin and I can import the images there, one by one. But there's hundreds of them and I'm looking for a way to do bulk import/upload with the title being the filename without the extension. Is something like this available in Django? -
On hover include more detail about object PVIZ
I am using the genentech/pviz github to display proteins and peptides. I have gotten a nice graphic and have used a hover feature in the css portion to change the color of the rectangle when hovered over. However, I want to display additionally information about the peptide and or protein when hovering over it as well. g.feature.psms.normal:hover rect.feature { fill: black; } seqEntry.addFeatures(fts.map(function(ft) { return { //we could also use te categoryType property, for height purpose, but not grouping purpose category : 'psms', type : ft[2], //This would be "normal" in most cases start : ft[0], end : ft[1], text : '', } })); I am not sure how to display information because I cannot find any good documentation. How would I be able to display text when hovering over the peptide rectangles? -
Flutter Chat Application, Check for changes in the API (Django-Rest-Framework)
I have built a chatt App using Django And Flutter, so I do a get request to get the information, also a post request from any user in the chat room to send new information(chats). My Question is how do I detect changes in the api? Is it possible to update let's say every 10 seconds, also have a pull to refresh, and just call a new get request on those? Also just Make a get request right after the post request so you can se your own messages? -
Django filter does not exclude results of negative look ahead regex
I'm working on a Django app where the database is currently being searched using regular expressions. The returned results seem to be correct, except for when I search with negative look ahead (I would like to be able to exclude some results through filtering with a regex). For example, the database has a column with many entries of 'None', and I would like to exclude those results when the database is searched. I tried the regex ^(?!None).*$ in an online regex tester, and it passes my tests ('None' strings are not matched, every other string is). However, when the results are returned with Django, the 'None' rows are not excluded. The backend for the DB is SQLite, which according to here should allow anything re allows, but I have not had success. Here is the filter() call I am using for the regular expression: previousFilters.filter(models.Q(myColumn__regex = r'('+input_expression+')')) Does Django allow the exclusion of results through a negative look ahead in a regular expression? -
How to optimize lazy loading of related object, if we already have its instance?
I like how Django ORM lazy loads related objects in the queryset, but I guess it's quite unpredictable as it is. The queryset API doesn't keep the related objects when they are used to make a queryset, thereby fetching them again when accessed later. Suppose I have a ModelA instance (say instance_a) which is a foreign key (say for_a) of some N instances of ModelB. Now I want to perform query on ModelB which has the given ModelA instance as the foreign key. Django ORM provides two ways: Using .filter() on ModelB: b_qs = ModelB.objects.filter(for_a=instance_a) for instance_b in b_qs: instance_b.for_a # <-- fetches the same row for ModelA again Results in 1 + N queries here. Using reverse relations on ModelA instance: b_qs = instance_a.for_a_set.all() for instance_b in b_qs: instance_b.for_a # <-- this uses the instance_a from memory Results in 1 query only here. While the second way can be used to achieve the result, it's not part of the standard API and not useable for every scenario. For example, if I have instances of 2 foreign keys of ModelB (say, ModelA and ModelC) and I want to get related objects to both of them. Something like the following works: … -
CSRF 403 error after clearing a form with javascript
I have a form displayed in html that a user can enter information into that I build a graph out of. After clearing the form and trying to resubmit the POST request, i get a 403 error "Forbidden (403),CSRF verification failed. Request aborted." I am using js from here: http://javascript-coder.com/javascript-form/javascript-reset-form.phtml. My code runs the rest of the time (my initial use of the form). But i always get the error after I clear the form. Any ideas? -
Celery Task on different servers starting simultaneously
I have Django Celery running on two different servers independently accessing a common database on another server. I notice that celery beat starting the same task simultaneously on two server when the job get submitted by the users. This creates a race condition and updates the database twice. How to prevent this by holding the task in one server while another similar task has started in another server? -
Django Table created with wrong columns
I am trying to get the columns required for a table from a Model. It works fine. But when I change the Model data from where the columns are taken, server needs to be restarted for it to take effect. tables.py: class InventoryTable(tables.Table): ip_addr = tables.Column(linkify=("detailed_view", (tables.A("ip_addr"), ))) class Meta: a = Inventory_views.objects.get(view_name="default") activeList = [] for field in a._meta.fields: if field.name != "default" and (getattr(a, field.name) == True): activeList.append(field.name) activeTuple = tuple(activeList) model = Inventory_basic template_name = 'django_tables2/bootstrap.html' fields = (activeTuple) views.py: def inventory_v2(request): if 'search_query' in request.GET: form = searchForm(request.GET) if form.is_valid(): search_query = form.cleaned_data.get('search_query') table = InventoryTable(Inventory_basic.objects.filter(ip_addr__icontains=search_query)) RequestConfig(request).configure(table) return render(request, 'jd_inventory_v2.html', {'table': table, 'form': form}) else: form = searchForm() table = InventoryTable(Inventory_basic.objects.filter(ip_addr__icontains="NULL")) RequestConfig(request).configure(table) return render(request, 'inventory_v2.html', {'table': table, 'form': form}) models.py: class Inventory_views(models.Model): view_name = models.CharField(max_length=25,default="NA", verbose_name='View Name') hw_serialno = models.BooleanField(default=True, verbose_name='Hardware SN') location = models.BooleanField(default=True, verbose_name='Location') ip_addr = models.BooleanField(default=True, verbose_name='IP Address') -
How to make a queryset in clas based view django-tables2?
I'm working on a django project where I want to show a table of user entries and have a buttons with some modals action.when i used function based view the context isn't callable or accessible ( check my previous question that this issue is causing This and This ). so my idea is that i can use a CBV and define a object_context_name where i can call objects but it's not clear to me how to make a queryset inside the CBV of a table,should i define it like normal CBV or what ? and is there a better approach ? -
How to validate image content?
I want to make a service with Django where I let users to upload images with particular subject. How can I validate these images if I want to filter out images with inappropriate content? -
Does Django support transactions out of the box?
I have a set of functionalities that are leveraging the the Django management/commands modules to run a bunch of cron jobs that would update the model. However I also need these to execute as all-or-none transactions. Does Django provide a way to define transactions? -
Problem sending photos to django api (onFailure Fail)
I'm trying to send photos to api but the only problem I understand is the false part of onFailure I checked the import and naming issue, there are no problems. but I couldn't figure it out. I worked for an average of 9 hours a day for a week, but I could not solve it. ************* START ANDORİD CODE ******************* -- main activity -- private void uploadServer(){ Retrofit retrofit = new Retrofit.Builder() .baseUrl(uploadApi.DJANGO_SITE) .addConverterFactory(GsonConverterFactory.create()) .build(); uploadApi uploadapi =retrofit.create(uploadApi.class); TextView txtupload = (TextView) findViewById(R.id.txtupload); File imageFile = new File(imageUri.toString()); RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),imageFile); MultipartBody.Part multiPartBody = MultipartBody.Part .createFormData("Image Create Api",imageFile.getName(),requestBody); Call<RequestBody> calls = uploadapi.uploaded(multiPartBody); calls.enqueue(new Callback<RequestBody>() { @Override public void onResponse( Call<RequestBody> calls, Response<RequestBody> response) { Log.d("like",response.toString()); } @Override public void onFailure(@NotNull Call<RequestBody> calls, Throwable t) { Log.d("false","FALSE"); } }); } } -- ## uploadApi ## -- public interface uploadApi { String DJANGO_SITE = "http://sabcanuy.pythonanywhere.com/"; @Multipart @POST("image/") Call<RequestBody> uploaded(@Part MultipartBody.Part multiPartBody); } ************* AND ANDORİD SERVER CLİENT CODE ******************* **************** START PYTHON/DJANGO CODE SERVER SİDE CODE ******************* **************** NOTE ******************* The server-side code is running healthy in the manual. fulfilling its duty **************** NOTE ******************* ********** view.py ********** class ImageCreateAPIView(CreateAPIView): serializer_class = imageSerializer queryset = Myimage.objects.all() and view code ******* serializer.py********** … -
Python Requests library post interpreted by Django as GET for some reason
I'm trying to make a post request to our app's api for some regression testing, but for some reason when I make the request like so through requests, it's logged and interpreted as a GET request. CODE: requests.post(f'{HTTP_PROTOCOL}://{APP_HOST}/api/route/', headers={'Authorization': 'Bearer ' + access_token}, json=DATA) LOG: [Thu Jul 11 19:17:30 2019] GET /api/route/ => generated 2 bytes in 64 msecs (HTTP/1.1 200) 5 headers in 162 bytes (1 switches on core 1) When I make the request through Postman, however, the request works totally fine and comes back with the created object in JSON, and in the logs it's recorded as a POST. The backend is currently written in Django, using Django Rest Framework for the REST API. Here is the Route in our urls.py file: url(r"^api/route/$", DataListView.as_view()) And I know that the DataListView works, because Postman works totally fine with it. I've had similar problems where it wouldn't work because I was posting to a route without the slash, and that's not the case here. I know I'm posting to the route with the trailing slash, as you can see for yourselves. QUESTION: How do I get this to work? And why would it be working in Postman, but not … -
How to search a bar using regular expressions on one or more models
I want to create a search bar with regular expressions on models please how to get there? -
How to update fieldfile with replacing it in actual directory in stead only in database
I am using UpdateView for a model including FileFields, but when I tried to update files, it only changes the database instead database and actual directory. For example: if I have the three files in my media root(media/uploads/id), when I use UpdateView to replace one of them, the database works fine, but there will be four files in my media root that includes the new file without deleting the old one. def upload_to(instance, filename): return 'uploads/{id}/{fn}'.format(id=instance.pk,fn=filename) class Mechanism(models.Model): """ A chemical kinetic mechanism, from Chemkin or Cantera """ ck_mechanism_file = models.FileField(upload_to=upload_to, max_length=100, blank=True, null=True, verbose_name="Chemkin mechanism file") ck_thermo_file = models.FileField(upload_to=upload_to, max_length=100, blank=True, null=True, verbose_name="Chemkin thermo file") ck_transport_file = models.FileField(upload_to=upload_to, max_length=100, blank=True, null=True, verbose_name="Chemkin transport file") ck_surface_file = models.FileField(upload_to=upload_to, max_length=100, blank=True, null=True, verbose_name="Chemkin surface file") ct_mechanism_file = models.FileField(upload_to=upload_to, max_length=100, blank=True, null=True, verbose_name='Cantera yaml file') ct_conversion_errors = models.TextField(verbose_name='Errors from the ck2yaml conversion') timestamps = models.DateTimeField(auto_now_add=True) class MechanismObjectMixin(object): model = Mechanism def get_object(self): pk = self.kwargs.get('pk') obj = None if pk is not None: obj = get_object_or_404(self.model, pk=pk) return obj class MechanismUpdateView(MechanismObjectMixin, View): template_name="file_update.html" def get(self, request, id=id, *args, **kwargs): context = {} obj = self.get_object() if obj is not None: form = ChemkinUpload(instance=obj) context['object'] = obj context['form'] = form return render(request, self.template_name, … -
Getting error while using MS SQL Server database at the back end of django application
I am trying to use local MS SQL Server database as a default database in django application. I have declared database in setting.py file as below: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'Test', 'USER': 'sa', 'PASSWORD': 'P@ssw0rd1234', 'HOST': 'DAL1281', 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', 'host_is_server': True }, }, } While running the server I am getting below error: django.db.utils.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 13 for SQL Server]TCP Provider: No connection could be made because the target machine actively refused it.\r\n (10061) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 13 for SQL Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 13 for SQL Server]Invalid connection string attribute (0); [08001] [Microsoft][ODBC Driver 13 for SQL Server]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (10061)') I am able to connect to database using SQL Server Management Studio. Alos I have checked TCP/IP protocol is enabled in SQL Server Configuration Manager. -
find drivers and number of rides with some conditions
I should write a code to find all drivers(id) and number of trips (n) for those drivers with this Conditions: n: number of trips that in those trips car's model is x or grater AND trip duration is more than t seconds. My Models: class Rider(models.Model): account = GenericRelation(Account, related_query_name='riders') rating = models.FloatField() x = models.FloatField() y = models.FloatField() class Driver(models.Model): account = GenericRelation(Account, related_query_name='drivers') rating = models.FloatField() x = models.FloatField() y = models.FloatField() active = models.BooleanField(default=False) class RideRequest(models.Model): rider = models.ForeignKey(Rider, on_delete=models.CASCADE) x = models.FloatField() y = models.FloatField() car_type = models.CharField(max_length=3, choices=car_type_choices) class Car(models.Model): owner = models.ForeignKey(Driver, on_delete=None) car_type = models.CharField(max_length=3, choices=car_type_choices) model = models.IntegerField() color = models.CharField(max_length=10) class Ride(models.Model): pickup_time = models.IntegerField() dropoff_time = models.IntegerField() car = models.ForeignKey(Car, on_delete=models.CASCADE) request = models.OneToOneField(RideRequest, on_delete=models.CASCADE, null=False) rider_rating = models.FloatField() driver_rating = models.FloatField() My Code: drivers = Driver.objects.values('id').annotate( travel_time=Sum(Case( When(car__ride__pickup_time__isnull=False, then=(F('car__ride__dropoff_time') - F('car__ride__pickup_time'))), default=0 )), ).annotate( n=Case( When(Q(travel_time__gt=t) & Q(car__model__gte=n), then=Count('car__ride')), output_field=IntegerField(), default=0 ) ).values('id', 'n') When i print the result: <QuerySet [{'id': 1, 'n': 0}, {'id': 2, 'n': 0}, {'id': 2, 'n': 1}, {'id': 3, 'n': 2}, {'id': 4, 'n': 0}, {'id': 5, 'n': 1}, {'id': 5, 'n': 0}]> this is near to real answer but still need do more. … -
How to determine root cause of AWS Elastic Beanstalk Shutdown Errors
I have a Django app hosted on AWS Elastic Beanstalk. Users upload documents to the site. Sometimes, users upload documents and the server completely shuts down. The server instantly 500s, goes offline for about 4 minutes and then then magically the app is back up and running. Obviously, something is happening to the app where it gets overwhelmed. The only thing I get from Elastic Beanstalk is this message: Environment health has transitioned from Ok to Severe. 100.0 % of the requests are failing with HTTP 5xx. ELB processes are not healthy on all instances. ELB health is failing or not available for all instances. Then about 4 minutes later: Environment health has transitioned from Severe to Ok. I have 1 t2.medium EC2 instance. I've set it up as Load Balancing, but use Min 1 Max 1, so I don't take advantage of the load balancing features. Here's a screenshot of my health tab: My app shut off on 7/10 as can be seen in picture 1. My CPU spiked at this time, but I can't imagine 20% CPU was enough to overwhelm my server. How can I determine what might be causing these short 500 errors? Is there somewhere …