Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How to print the path of the html file in response in Django test
I want to know which template file django is reading when I'm testing. I use MEZZANINE for my website. I tried to change the home page. But I'm not sure which file to change. from django.test import TestCase import os # Create your tests here. class ProjectTests(TestCase): def test_homepage(self): response = self.client.get('/') #print dir(response) print response.template_name self.assertEqual(response.status_code, 200) I expect to print the absolute path of response.template_name. Thanks. -
Why "label.tag" in {{ attribute.label.tag }} does not work in django template? How can we get the label of a column in template?
It is possible to get the value from views.py in template in django. It does not work to get the label and then its value. What is the way to get it? in modules.py class Article(models.Model): pub_date = models.DateField() headline = models.CharField(max_length=200) content = models.TextField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): return self.headline in views.py def articlesindex(request): data = Articles.objects.all().last() return render(request, 'Articles\index.html', {'articles':data} in index.html {{ articles.headline }} //gives you the value {{ articles.headline.label.tag }} //does not give you the name "headline" -
Error: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty
I am currently attempting to update django from 1.4 to 2.0 after many syntax corrections I have run into this error when trying to run the server. I am updating django by having installed the latest version on my previous directory. From everything that ive read online, the SECRET_KEY should be set in the settings.py which it is in my case. django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. If anyone has any resolutions please let me know as I have been struggling with this error for a couple of days now. I understand this may be an issue in the way I am updating so if anyone has more in depth information on updating django that would be very helpful as well. -
Why use dj-stripe or pinax-stripe instead of vanilla stripe?
It seems to me that stripe app is fairly easy to use. What are compelling reasons to consider using dj-stripe of pinax-stripe? -
How to add value in multi dimensions dictionary?
I have a column in MySQL "abc" contains data => demo1, demo1, demo2, demo2 and another column name value data => abc1, abc2, abc3, abc4 how to convert that into a dictionary like { 'demo1': {'abc1', 'abc2'}, 'demo2' : {'abc3', 'abc4'} } for branch in get_branch: branch_array[branch.abc].append( branch.value) for branch in get_branch: branch_array[branch.abc] = branch.value But nothing worked properly -
Access dictionary position in Django template
I have this dictionary in my Django template using {{ item }}: dict_items([('user_id', 28), ('id', 10), ('nome', 'Depósito'), ('informacoes_complementares', 'Depósito central'), ('_state', <django.db.models.base.ModelState object at 0x7f8ea009f208>)]) How do I get the "id" and "nome"? I'm using Django 2.1.7. Thank you. -
Cannot Publish/Deploy Django/Python site in local IIS (through Visual Studio publish)
I had trouble deploying to local IIS my DjangoWebProject from Visual Studio (2019). 1) This is for Windows 10 environment. 2) Used stack: Python/Django/MongoDB/Javascript/D3 3) IIS works and successfully shows the default IIS site (tried from localhost and another machine) 4) Everything works great! I could successfully code/build the site and tested everything is working in debug mode (from VS) - e.g. it opens up http://localhost:<portnumber> in Chrome/EDge and the whole website works perfectly with all the form submission etc. etc. 3) Now I wanted to create the internal site published so other users can access and I tried Publish option... WebpublishMethod: MSDeploy Server Name: <my machine name> Site name: Default Web Site Destination URL: <my machine name>.corp.<my company>.com Validate Connection : Successful Other conf details: ExcludeAppData: False SkipExtraFileOnServer: True MSDeployPublishMethod: InProc EnableMSDeploybackup: True It gets published and it creates all the folder structure and everything (including resource files etc. needed) in the C:\inetpub\wwwroot\app location and the folder structure is consistent with the Visual Studio folder structure for code - it shows all the files like __init__.py forms.py models.py tests.py views.py etc. plus all the required javascript and d3 code and everything. BUT THE PROBLEM: When I go to the … -
Deploying Django from gitlab to windows VM using Jenkins
I am looking for solution to deploy Django application on Windows Server. I tried to do it in several ways with no effect. Architecture: 1. Host: Windows Serve with Apache WSGI 2. Another Windows server with Jenkins 3. Gitlab with Django application 4. Me :-) I am trying with psexec to run CMD file on host using Jenkins. Inside this file I has a simple script: cd "destination" git status git fetch --all git pull origin master On host server I have configured and generated SSH keys for my user account. Job has very simple configuration with only one build step as a batch script: PsExec64.exe \Remote_server script_path Django on host is cloned from SSH repository. When I try to run above script than I got "Access Denied" or some issues with git. But Jenkins doesn't produced any logs from git. Maybe I should set-up node on Host or use git remote url with HTTPS instead of SSH? -
git continues to control changes on __pycache__ even when it is in gitignore
This is my .gitignore: *__pycache__* *.pyc db.sqlite3 *.DS_Store media/ res/ I can see on my Atom that __pycache__ directories are VcsIgnored (which implies that are recognized as not version controlled by git) But, any way, when I make changes to a file, I get several __pycache__ files as modified and unstaged on my Atom git window: I don't know wether the problem is in git or in Atom.