Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to carry out uploading multiple files in Django with CreateView?
Please help me. I am new to Django, cannot undertsand the following thing - I have subclass of CreateView for creating a comment. I want to create a project where people can leave their comments and attach files (images) to this comment. One should have possibility to attach as many images as he wants to ONE form with text comment. I have found in Internet a decision that I need to use 2 models - 1 model for text comment + 1 separate model for images. Is it so? Comment (text) form is created and handled in my views.py by sublass of CreateView. How to connect new separate model for images with my CreateView ? models.py class Descriptions(models.Model): … city = models.ForeignKey(Cities, on_delete=models.CASCADE) description = models.TextField() date_added = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.DO_NOTHING) … class Description_Photos(models.Model): image = models.ImageField(upload_to='images/', blank=True) description = models.ForeignKey(Descriptions, on_delete=models.CASCADE, related_name='photos') forms.py class DescriptionsForm(forms.ModelForm): class Meta: model = Descriptions exclude = [] widgets = {'description': forms.Textarea(attrs={'cols':90})} class Photos_form(forms.Form): photos = forms.FileField(widget=forms.FileInput(attrs={'multiple': True})) views.py class DescriptionCreate(CreateView): model = Descriptions form_class = DescriptionsForm template_name = 'countries/new_description.html' def get_success_url(self): return reverse('countries:descr', args=[self.kwargs['country_id'], self.kwargs['city_id']]) def get_context_data(self, **kwargs): self.city = get_object_or_404(Cities, id=self.kwargs['city_id']) kwargs['city'] = self.city return super().get_context_data(**kwargs) def form_valid(self, form): form.instance.city … -
Django/Heroku: FATAL: too many connections for role
So I just launched a website with Channels 2.0 Daphne 2.2.0 and asgi via Heroku (Hobby) and Postgres (trial). When I launch my website, I click around for a few pages and I get a 500 error. The error message I get emailed is FATAL: too many connections for role ..." When I run heroku pg:killall or wait long enough I can click around a few more times until the error message repeats itself. However, when I run heroku pg it shows Connections 0/20. Does anyone know what is going on and how I can stop the errors? It's possible that I have two many connections open for a second, but it doesn't seem that way. File "/app/.heroku/python/lib/python3.6/site- packages/django/contrib/sessions/backends/base.py" in _get_session 191. return self._session_cache During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py" in ensure_connection 216. self.connect() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py" in connect 194. self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py" in get_new_connection 168. connection = Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py" in connect 130. conn = _connect(dsn, connection_factory=connection_factory, **kwasync) The above exception (FATAL: too many connections for role "polewdwynmvyyt" ) was the direct cause of the following exception: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" … -
Nested Dict As HttpRequest Django
I am trying to write some test cases for some code I've developed using Elasticsearch and Django. The concept is straightforward - I just want to test a get request, which will be an Elasticsearch query. However, I am constructing the query as a nested dict. When I pass the nested dict to the Client object in the test script it gets passed through Django until it ends up at the urlencode function which doesn't look like it can handle nested dicts only MultivalueDicts. Any suggestions or solutions? I don't want to use any additional packages as I don't want to depend on potentially non-supported packages for this application. Generic Code: class MyViewTest(TestCase): es_connection = elasticsearch.Elasticsearch("localhost:9200") def test_es_query(self): client = Client() query = { "query": { "term": { "city": "some city" } } } response = client.get("", query) print(response) Link for urlencode function: urlencode Django The issue is clearly at the conditional statement when the urlencode function checks if the dictionary value is a str or bytes object. If it isn't it creates a generator object which can never access the nested portions of the dictionary. -
Unable to register the default user model with django.contrib.admin
I'm trying to manage my User table with django.contrib.admin But during I add the User table in admin, I had an issue that doesn't appear in admin site. Here is my code. from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User @admin.register(User) class CustomUserAdmin(UserAdmin): pass assert admin.site.is_registered(User) # Fails here And when I added the other custom model, it works. Thanks -
Using external script in Views.py (Django)
I have a file that sends a request to an API and retrieves information. Let's call this file get_info.py. I am now building a GUI that uses Django and the views.py file, with methods 'GET' and 'POST'. I am now importing the function from get_info.py into views.py and using it as follows from get_info import get_info def@api_view(['GET']) def generate_route(request): """ :param request: 1. lat: posx 2. lng: pos, 3. r: radius in km 4. strategy, 5. edge_num, 6. deep, :return: """ posx = request.query_params.get('lat', None) posy= request.query_params.get('lng', None) r= request.query_params.get('r', None) strategy = request.query_params.get('strategy', None) strategy = strategy if strategy else 3 edge_num = request.query_params.get('edge_num', None) edge_num = edge_num if edge_num else 3 deep = request.query_params.get('deep', None) deep = deep if deep else 3 print("BEFORE", posx, posy, r, strategy, edge_num, deep) route = get_info(posx, posy, r) print("AFTER", route) if request.query_params.get('lat', None) is not None \ and request.query_params.get('lng', None) is not None \ and request.query_params.get('r', None) is not None: return Response({}, status=status.HTTP_200_OK) else: return Response({ "Error": 'Need lat, lng, and r {}'.format(request.query_params.get('lat', None)) }, status=status.HTTP_400_BAD_REQUEST) ``` However, I get the response The request argument (which is in get_info.py) must be an instance of a django.http.HttpRequest, not __builtin__.unicode. However, when I use … -
Django - force pk_url_kwarg to query other model instances
Consider the following code: views.py class BHA_UpdateView(UpdateView): model = BHA_overall pk_url_kwarg = 'pk_alt' form_class = BHA_overall_Form To my understanding, pk_url_kwarg = 'pk_alt' will query and return instances of model = BHA_overall. Is there any way that I can force pk_url_kwarg to query & return other model instances defined in models.py (like model = other_model), while having my get_object() method to return objects in model = BHA_overall? What CBV should I use (I think UpdateView is not a good choice in this case)? ++ I'm trying to make a page that allows users to manage information about the product they use. So, ultimately I will implement forms, and the user input needs to be saved in DB -
Retrofit returning only 200 OK on push and put
Im trying to send JSON messages through HTTP with retrofit2 in android, to a django server with the rest api running. using a retrofit interface and the calls: @POST("getDates/") Call<Event> newEvent(@Body Event event); @PUT("getDates/{id}/") Call<Event> updateEvent(@Path("id") int id, @Body Event event); as well as public void postNewEvent(Event event) { Call<Event> call = service.newEvent(event); call.enqueue(new Callback<Event>() { @Override public void onResponse(Call<Event> call, Response<Event> response) { Log.i("REST", "POST was sucessful: " + response.isSuccessful()); Log.i("REST", "response body: " + response.body().toString()); Log.i("REST", "response message: " + response.message()); Log.i("REST", "response code: " + response.code()); Log.i("REST", "response code: " + response.errorBody()); } @Override public void onFailure(Call<Event> call, Throwable t) { Log.e("REST", t.getMessage()); Log.e("REST", call.toString()); } }); } public boolean updateEvent(Event event) { Call<Event> call = service.updateEvent(event.getId(), event); call.enqueue(new Callback<Event>() { @Override public void onResponse(Call<Event> call, Response<Event> response) { success = response.isSuccessful(); } @Override public void onFailure(Call<Event> call, Throwable t) { Log.e("REST", t.getMessage()); } }); } However, every message i send to the server through my interface only gets a reply with: OK and code:200. I have tried sending the calls manually through the api and it works just fine. This code used to also work for me, but now it just stopped. I've added an Nginx … -
Django ORM. How does Django know the auto incremented pk of newly created record
Suppose Book table has two fields id, name. id is auto incremented pk. Database back end is mysql In Django. book = Book.objects.create(name="Tender Is the Night") How does Django know new book's id. What sql statements dose Django send to Mysql server? Only the insert statement ? if so,does insert statement will return the id of newly created book? -
Access custom user model's field in views
I have extended the default User model using OneToOneField as following: # models.py class Employee(models.Model): USER_TYPE = ( ('publisher', 'Publisher',), ('editor', 'Editor',) ) user = models.OneToOneField(User, on_delete=models.CASCADE) user_type = models.CharField(choices=USER_TYPE, max_length=255) def __str__(self): return self.user.username Also, i have a simple model Article: class Article(models.Model): title = models.CharField(max_length=255) text = models.TextField() created_by = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True) def __str__(self): return self.title I'm using generic class-based views (ListView) in views.py, and I want to reference the custom user model, specifically to check if the current logged-in user user_type is publisher then run specific queryset, else if editor run another queryset, and so on. I'm bit familiar with 'request.user', or request.user.is_staff, but i cannot find any documentation or Stackoverflow questions related to my case. -
How to input a string when Django start up?
I need to save a string as password when Django startup. The password must always keep in memory if Django not shutdown. When some request come up, the password will be used to decrypt something. How to input this string when the Django start? -
Django update all fields implicitly
When using django rest framework, I have a method to update a model based on inputted form data. def update(self, instance, validated_data): instance.Name = validated_data.get('Name', instance.Name) instance.save() return instance Is there a way that I can have all the fields on the model update with the validated_data if the names of the fields all line up? (Aka validated_data.Name matches instance.Name, validated_data.Otherfield is the same as instance.Otherfield, instead of having to explicity list all the fields. -
django filter results with comma separated string and each string is separated by pipe |
I have a django model like this class MyModel(models.Model): status_1 = models.CharField(max_length=255, blank=True, null=True) status_2 = models.CharField(max_length=255, blank=True, null=True) I will pass the comma separated string and each string value is seperated with pipe (|). Each string value will be a combination of status_1|status_2 like this api/v1/myurl/?status=1|2,2|3 # This is status_1|status_2 So the question is, I need to get the results based on the combinations of status_1 and status_2. For example, I need to get a record if the record has status_1=1 and status_2=2 OR status_1=2 and status_2=3 Anyone here please help me to achieve this? Thanks ::) -
Is it possible to connect multiple databases with only ONE mysql option file in Django?
In django, I can use read_default_file to get database connection strings from MySQL option file. But if I wanna connect multiple databases, is it possible to get connection strings from only ONE MySQL option file as follows? settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': os.path.join(BASE_DIR, 'connections.cnf') }, 'service': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': os.path.join(BASE_DIR, 'connections.cnf') } }} connection.cnf: [client1] database=mysqldb user=root password=root default-character-set=utf8 [client2] database=mysqldb2 user=root password=root default-character-set=utf8 Thanks. -
Django - selectively query models using pk_url_kwarg
Consider the these two models and view: models.py class BHA_List(models.Model): well = models.ForeignKey(WellInfo, 'CASCADE', related_name='bha_list') bha_number = models.CharField(max_length=100) class BHA_overall(models.Model): bha_number = models.ForeignKey(BHA_List, 'CASCADE', related_name='bha_overall') drill_str_name = models.CharField(max_length=111) depth_in = models.CharField(max_length=111) views.py class BHA_UpdateView(UpdateView): model = BHA_overall pk_url_kwarg = 'pk_alt' form_class = BHA_overall_Form To my understanding, pk_url_kwarg = 'pk_alt' will query and return instances of model = BHA_overall. Let's say that I use a different CBV other than UpdateView, and want to implement two models. So something like this: model = (BHA_overall, BHA_List). Is there any way that I force my pk_url_kwarg = 'pk_alt' to query and return instances only in BHA_List, but force my get_object() return objects in BHA_overall?? What CBV should I use? -
Django-rest-framework - JWT authentication
In my settings.py file I have set this: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), } Now, I have created a ListCreateAPIView: class ListSubreddits(ListCreateAPIView): queryset = Subreddit.objects.all() authentication_classes = (JSONWebTokenAuthentication, ) def get_serializer_class(self): if self.request.method == 'GET': return SubredditSerializer_detailed if self.request.method == 'POST': return SubredditSerializer So, I have sent a POST request creating without just content-type header and the POST request was successful. I haven't provided any Authentication or Authorization headers. What am I missing here? -
How to get the URL of the page in a CreateView of the Report/Flag User object
I am trying to create one report model that will go on all my templates. The idea is that members will be able to report other members for unauthorized content. the moderator will know what is being reported by the URL of the page and the username of the user on that template. I am not sure how to get the URL on which the report button is clicked. I am also having difficulty returning the user to the same page once the report object is created Below is the model for the report models.py class Report(models.Model): reporter = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='reporting_members') reported = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='reported_members') report_url = models.URLField(max_length=2000, blank=True, null=True) reported_at = models.DateTimeField(auto_now_add=True) reporting_choices = ( ('1', 'The images posted by this user are not relevant to the Post), ('2', 'Rude or abusive content, The words chosen by the user are inappropriate'), ('3', 'This user is asking me to change my review in return for favor '), ('4', 'Other'), ) reason_to_report = models.CharField(max_length=1, choices=reporting_choices) explain_reason = models.TextField(blank=True, null=True) Below are my views.py class ReportCreateView(LoginRequiredMixin, CreateView): model = Report fields = ('reason_to_report', 'explain_reason') def form_valid(self, form): form.instance.reporter = self.request.user #This works form.instance.reported = User.objects.get(username=self.kwargs.get('username')) #This works form.instance.report_url … -
Open port on Ubuntu 16.04
How do I open port 5002 for websockets to run? I tried sudo ufw allow 5002 but I continued to get error WebSocket connection to 'ws://localhost:5002/ikdyuju9xrtkab7055onyurnrjmw48ae/josh' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED Firewall settings To Action From -- ------ ---- Nginx Full ALLOW Anywhere OpenSSH ALLOW Anywhere Nginx Full (v6) ALLOW Anywhere (v6) OpenSSH (v6) ALLOW Anywhere (v6) -
[Django-xadmin]: Drop-down box failure in filter front-end page
enter image description here enter image description here enter image description here This is the code: -
How to unit test FormView? Never reaches result page
Django's FormView returns 302, something that makes it difficult to test: class A(TestCase): def test_add_item(self): a_valid_value = "aaa" a_invalid_value = "ccc" successful_text = "gratz" failure_text = "fail" resp = self.client.post('/add/', {'item': a_valid_value}) print(resp.content) # prints b'' self.assertContains(resp, successful_text, status_code=??) The status_code of first response (Redirect) is 302 and resp.content is empty. The issue is that I never get the final response in the test file in order to test the contents. Any ideas? -
How do I hook a django-allauth signal?
Signals page for django-allauth: https://django-allauth.readthedocs.io/en/latest/signals.html I am trying to hook the email_verified signal: allauth.account.signals.email_confirmed(request, email_address) And am getting nothing whenever a user confirms their email. Here is my code: from allauth.account.signals import email_confirmed from channels import Group def send_to_user_socket(sender, **kwargs): Group('%s.get-started' % (kwargs['request'].user.username)).send({'text': json.dumps({'message': 'Email confirmed'})}) email_confirmed.connect(send_to_user_socket) What am I doing wrong? Thanks in advance. -
Import CSV file to Django models
I have one CSV file and I want to import the content of this file to my Django Models, can someone help me and explain how can I do this? This is my CSV. NAME,CLUB,LEAGUE,POSITION,RATING,PACE,SHOOTING,PASSING,DRIBBLING,DEFENDING,PHYSICAL,LOADDATE Aleksandar Kolarov,Roma,Calcio A,LB,81,72,68,72,64,84,85,2018-04-14 08:37:48 And my models are; class Player(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=128) league = models.ForeignKey('League', on_delete=models.CASCADE) club = models.ForeignKey('Club', on_delete=models.CASCADE) attributes = models.ForeignKey('Attribute', on_delete=models.CASCADE) def __str__(self): return self.name class League(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class Club(models.Model): name = models.CharField(max_length=30) league = models.ForeignKey('League', on_delete=models.CASCADE) def __str__(self): return self.name class Attribute(models.Model): pace = models.IntegerField() shooting = models.IntegerField() passing = models.IntegerField() dribbling = models.IntegerField() defending = models.IntegerField() physical = models.IntegerField() position = models.CharField(max_length=4) overall = models.IntegerField() def __str__(self): return '%s %s'%(self.overall, self.position) -
Issue using Django template tags inside Jquery
Got stuck in a very small issue, I don't know it is even possible or not. I have write a method viewRender which render calendar (used fullCalendar Api for my project). I am getting date from calendar like that: var newDate = $('#calendar').fullCalendar("getDate"); Now from Django side, I send a dict which contain date ranges as a key and values against that key. I have wrote a template tag to get value against that dictionary. dictionary name is range_dict and template tag used is get_all_configurations. Now what happens when I try to get value from template tag against that key it throws error because it considers newDate as a string and passing it as a key which is wrong. I want to pass a value of newDate variable but don't know why I am unable to do so. This is line: var newDate = $('#calendar').fullCalendar("getDate"); console.log( "{{ range_dict|get_all_configurations:newDate}}"); I also wrote it as var newDate = $('#calendar').fullCalendar("getDate"); console.log( {{ range_dict|get_all_configurations:newDate}}); But it didn't worked. Function viewRender: function(view) { startedViewRender = true; var newDate = $('#calendar').fullCalendar("getDate"); //This is line console.log( {{ range_dict|get_all_configurations:newDate}}); if (!newDate.isSame(prevDate, 'day')) { //if the date changed prevDate = moment(newDate); var events = $('#calendar').fullCalendar("clientEvents"); //Get all current events … -
Django Formview from populate the form with API data
I having hard time figure out something that might be so simple. I am new to Django/Python development. I want to able to edit the form with pre-populate data. The data, itself, come from an api call. I am able to get data from API. But, I am unable to initial the form with API data so the user edit the information to submit. I created a form with class YourPlace(forms.Form): place_name = forms.CharField(help_text="Enter place name") place_location = forms.CharField(help_text="Enter place location") In my view, I have class like this : class EditPlace(generic.FormView): template_name = 'core/place.html' form_class = YourPlace def get_initial(self): initial = {} api = apiclient.apiCall() placeid = api.placeID(2)["data"] placeid = json.loads(placeid) initial['name'] = placeid['name'] initial['location'] = placeid['location'] return initial def get_form_kwargs(self): kwargs = { 'initial': self.get_initial(), 'prefix': self.get_prefix(), } return kwargs -
Django ORM: Filter results by values from list, limit answers per value?
I'm using Django 2.0 and have a Content model with a ForeignKey(User, ...). I also have a list of user IDs for which I'd like to fetch that Content, ordered by "newest first", but only up to 25 elements per user. I know I can do this: Content.objects.filter(user_id__in=[1, 2, 3, ...]).order_by('-id') ...to fetch all the Content objects created by each of these users, plus I'll get it all sorted with newest elements first. But I'd like to fetch up to 25 elements for each of these users (some users might create hundreds of these objects, some might create zero). There's of course the dumb way: for user in [1, 2, 3, ...]: Content.objects.filter(user_id=user).order_by('-id')[:25] This however hits the database as many times as there's objects in the user ID list, and that goes quite high (around 100 or so per page view). Is there any way to optimize this case? (I've tried looking around select_related, but that seems to fetch as many related models as possible.) -
How to serve different web apps using one domain name in Apache?
I'm currently trying to deploy my Django 2.0 App on an Apache Web Server. However I'm experiencing difficulties in configuring it because my Virtual Host configuration overrides other Virtual Hosts which is used by other projects (Ruby and PHP WebApps). We only have one domain name at the moment so I cannot use other domain names to host my app. Is it possible to serve different kind of apps with one domain name using Apache Virtual Hosts?