Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
__init__() got an unexpected keyword argument 'init_command'
I got this probleme when trying to include swagger in django from django.urls import path from django.conf.urls import url from rest_framework_swagger.views import get_swagger_view from index import views schema_view = get_swagger_view(title='API') urlpatterns = [ #path('', views.index), path('img', views.add_image), path('valider', views.valider), path('all', views.get_all_image), path('docs/', schema_view), path('<str:idd>', views.get_image), ] -
Leaflet.Draw edit and delete button not working
I'm using Leaflet Draw to let users draw a polyline in a map in order to measure sections. First step is to use Leaflet.Draw to let users draw the line. Leaflet.Draw includes a delete and edit button. These buttons are, however not working. I've (re)used working code from other projects to create the draw control and pass it a FeatureGroup and editable layers. // My draw Toolbar var drawnItems = new L.FeatureGroup() map.addLayer(drawnItems) var drawControl = new L.Control.Draw({ draw:{polygon: false, marker: false, circlemarker: false, rectangle: false, circle: false, }, edit: { featureGroup: drawnItems } }); map.addControl(drawControl); map.on(L.Draw.Event.CREATED, function (e) { var layer = e.layer; map.addLayer(layer); }); Seems like I'm linking the feature group correctly, but for some reason the delete and edit are not working :( -
URL GET parameters only showing for `list`, Swagger-DRF
I am trying to get Swagger to show my URL GET parameters for a specific endpoint. The parameters should be available for all the GET actions on my ModelViewSet, however I only get to display them for the list action, but not for the retrieve one. The way I am going about it is as follows: class SomeFilter(BaseFilterBackend): def get_schema_fields(self, view): print(view.action) if view.action in ['list', 'retrieve']: return [ coreapi.Field( name='my-name', location='query', required=False, schema=coreschema.Boolean(), description="Include(true)/Exclude(false) some query fields" ) ] else: return [] class SomeMixin: filter_backends = (SomeFilter,) def filter_queryset(self, queryset): return queryset ... # Some other irrelevant stuff... Once again I succesfully get the list action parameter to show (and work), but not the retrieve one. The URL's I am trying to call are (for reference): http://my-api/objects/?my-name=[true, false] (this works) and http://my-api/objects/{id}/?my-name=[true, false] (Swagger doesn't pick this up). Also as a side note, I know for a fact that calls to both enpoints are possible and obtain the desired results (because I tried with other tools). Any help is greatly appreciated, thanks! -
Connecting Django CMS with Firebase Console
I am currently working on a RESTful API using django-rest-framework, The API talks to the Firebase Realtime Database. I am currently updating the Firebase Database when a particular HTTP request (GET/POST/DELETE) is requested to a specific route. The problem is when I add data to tables using the django admin panel only then the firebase database should be updated. Is there any way ?? Should I use forms in django to do CRUD Operations -
Django fails to model legacy database with inspectdb
I have a currently empty Geodjango app set up - I am connected to my Postgis database in which I have a table named aadf that I am attempting to create a model from. I am using inspectdb to do this. I get the following error message: from django.contrib.gis.db import models # Unable to inspect table 'aadf' # The error was: sequence index must be integer, not 'slice' # Unable to inspect table 'auth_group' # The error was: sequence index must be integer, not 'slice' # Unable to inspect table 'auth_group_permissions' # The error was: sequence index must be integer, not 'slice' ** This error message repeats for multiple other tables that Django has created ** The connection to the database evidently seems fine as it is able to pick up the relevant table name. That said, it also seems to be trying to inspect the other tables Django has created in the database such as 'auth_group' and 'auth_group_permissions'. -
I am using Django 2.2 and I am try to use django-star-ratings 0.7.0
I have installed django-star-ratings 0.7.0 on my virtualenv and also added 'star-ratings' in my INSTALLED_APPS at setting.py but I still got this error: ModuleNotFoundError: No module named 'star-ratings' -
What is difference between celery and django channel's async_to_sync?
I have been trying to call an asynchronous code from a django rest framework to send notifications via firebase. For that I found out that I can use celery. My first question is whether celery runs the task on a different thread/ on different cpu core/ or just asynchronously on same thread? I also found out that I can use async_to_sync function from django channels functions to run it asynchronously. Again the same question, whether that will be on different thread/ core etc. Also how is celery different from async_to_sync? And one last question is whether djnago server runs on single thread or multiple threads. Whether it runs on single core or multiple cores? Also where to specify these factor while running a django server? -
Image saving in different table
I have one view to upload the photos. I was using one model 'Photo' and model form PhotoForm. Image was saving in db successfully. But I added one more model PhotoTemp and associated modelfom PhotoTempForm and using them in the view instead of using Photo and PhotoForm. But while uploading the image it is saving into old Photo model instead of PhotoTemp. I am not able to understand why it is happening. I am not using any kind of caching in my django project. Is django use any default caching? Can someone tell me why it is happening? This my view: class ProgressBarUploadView(View): def post(self, request): time.sleep(1) form = PhotoTempForm(self.request.POST, self.request.FILES) if form.is_valid(): photoTemp = form.save(commit=False) photoTemp.photo_type = 'product' if ProgressBarUploadView.cover_photo: photoTemp.cover_photo_flag='yes' ProgressBarUploadView.cover_photo = False else: photoTemp.cover_photo_flag='no' photoTemp.save() data = {'is_valid': True, 'name': photoTemp.file.name, 'url': photoTemp.file.url,'info':info} else: data = {'is_valid': False} return JsonResponse(data) -
Error in user.id while saving data in Model - Commit False not working
I am using AbstractBaseUser for that i have created a managers.py for creating superuser. Everything is working except these line in managers.py. Even i tried to print(user.id) before user.save(using=self._db) it is printing None user.save(using=self._db) user.created_by_id = user.id user.updated_by_id = user.id user.save() I have also used commit=False in user.save(using=self._db, commit=False) still it is giving error. See the errors at bottom. In my models.py i have tweo field created_by & updated_by which should should not be null. Thats why i am saving in Managers.py which is creating all this error. How can i solve this issue. Is there better approach. This condition is only required for creating superuser. Models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) is_active = models.BooleanField(_('is user active'), default=True) profile_image = models.ImageField(default='user-avatar.png', upload_to='users/', null=True, blank=True) is_staff = models.BooleanField(_('staff'), default=True) role = models.ForeignKey(Role, on_delete=models.CASCADE) phone_number = models.CharField(max_length=30, blank=True, null=True) address = models.CharField(max_length=100, blank=True, null=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, related_name='user_created_by') created_on = models.DateTimeField(_('user created on'), auto_now_add=True) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, related_name='user_updated_by') updated_on = models.DateTimeField(_('user updated on'), auto_now=True) Managers.py class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): """ Creates and saves a User with the … -
Django migrations - Get current app name in RunPython function
One of my migrations has the additional function to be run using RunPython. This message's purpose is only to show a happy message to user. The only problem is, that I need to show an app name, in which current migration was created and run. Is this somewhat possible? My code: from django.db import migrations, models import django.db.models.deletion def happy_message(apps, schema_editor): print('A happy message from migration inside app named {}') class Migration(migrations.Migration): operations = [ migrations.AddField( model_name='mymodel', name='rank_no', field=models.IntegerField(null=True), ), migrations.RunPython( happy_message, migrations.RunPython.noop ), ] -
Want to add retrived data from django DB to my html option tag
I want to retrieve data from Django DB and add it to HTML Option tag to show drop down list views.py from django.shortcuts import render from Home.models import Train, LoadStation def LoadData(request): stations = LoadStation.objects.all() return render(request, 'Home/finalproject.html', {'stations': stations}) finalproject.html <select name="Source_Station" style="width:20%; border: 3px solid red;" id="txt1" onchange="{% url 'Home:LoadData' %}"> {% for data in stations %} <option value="{{ data.Station_Name }}">{{ data.Station_Name }} </option> {% endfor %} </select><br><br> Expected Output : Drop down list filled with data in LoadStation Table. Actual Output : Option Box is empty. -
Is there a way to link the html button with the text written above in the placeholder?
I'm setting up link between the directory of the file written in the placeholder and the button. How can I link the button with the text so that the files in the directory can be processed and stored in the database. def index(request): filePath = str(request.POST.get("text")) totalCount = preparingData(filePath) #print(f) Info1 = " Files are ready for extraction..." # creating a cluster with cassandra and linking it to the keyspace content={"totalCount" :totalCount, "Info1" : Info1, } cluster = Cluster(['127.0.0.1']) session = cluster.connect() session.set_keyspace('simar') # saving the input taken in html to variable new_title # this ORFile is use to run code on that file for extraction # filep = re # print(None) orFile(filePath) # if filep != None: # orFile(filePath) # orFile(filePath) # shuting down the cluster cluster.shutdown() return render(request,"app/main.html",content) Main.html <body background=""> <font size="90"><b>AUTOMATION</b></font> <h2>Select File Path</h2> <form method="post">{% csrf_token %} <input type="text" name="text" placeholder="Filepath"><br> <!--<input type="submit" value="Submit"><br>--> {% if totalCount %} <h1>{{totalCount}} {{Info1}}</h1> {% endif %} <fieldset> <legend><b>MetaData Fields</b></legend> <div> <br> <label>Title</label> <br><br> <input type="submit" value="extract"> <br><br><br> <label>Type</label><br><br> <button type="button">extract</button> <output type="result"></output> <br><br><br> <label>Counter Party</label><br><br> <button type="button">extract</button> -
What is the difference between "POST" and "GET" when sending parameters using Django Rest Framework
I was wondering. Is it good and safe to use "post" or "get" method when sending parameters with Axios using Django Rest Framework? Usually, the "post" method is used to send parameters. But when I research the Django Rest Framework, usually use the "get" method to send parameters. -
Django making table from Pandas Pivot Table
I have created a Pivot table and now need to convert it do a Django table. I get this data with this: df = pd.pivot_table ( df, index = [ "category" ], columns=['date'], values = ['comm'], aggfunc = np.sum, fill_value=0 ) which gives me this: comm date 2013-12-28 2014-12-27 2015-12-25 2016-12-31 2017-05-20 category CONT ASSET FEES 3868.32 4450.94 6063.94 5285.85 17479.07 FIXED ANN TRAIL 1299.94 1299.94 1277.24 1223.70 1848.56 .... INSURANCE 5132.08 6017.77 1672.13 0 5059.51 INSURANCE TRAIL 935.05 701.68 623.86 458.45 1357.83 send to the template with this: context = { 'annual' : df.to_records (), } Now need to convert it to a Django table. I am guessing ".comm" will be part of the code. {% for c in annual %} <tr> <td>{{ c.category }}</td> <td>{{ c.comm|floatformat:"0"|intcomma }}</td> <td>{{ c.comm|floatformat:"0"|intcomma }}</td> <td>{{ c.comm|floatformat:"0"|intcomma }}</td> <td>{{ c.comm|floatformat:"0"|intcomma }}</td> <td>{{ c.comm|floatformat:"0"|intcomma }}</td> </tr> {% endfor %} obviously I cant you the data string. what can I do to get this to print? Thanks! -
Implementing Internal SSO with Django
I am looking for some suggestions and guidelines for implementing an internal SSO. After doing some research about it, I came to know that there are 2 major protocols, SAML and CAS. Currently what my thoughts are: SAML is a complex and detailed protocol, somewhat difficult to implement and manage. It is mainly useful for large enterprises. CAS is simpler and has easier implementation as compared to SAML, therefore a better choice for small to medium sized companies I like django-mama-cas and django-cs-ng as choices for server and clients respectively. But as this is my first time getting involved with SSO so I get a little confused trying to wrap my head around these concepts. Please share your suggestions about this, would really appreciate -
POST HTTP method having 500 Internal Server Error on Apache and Django2 production
I'm having an error regarding my POST method not working on production for Apache and Django2 project I already have the code for POST as Views, and here is the code for the Views: **views.py:** class Smoke(View): def get(self, request, *args, **kwargs): return render(request, 'add/index.html') def post(self, request, *args, **kwargs): return JsonResponse( { "message": "Successfully Added", "details": data }, status=200 ) Also, here is the code for the urls.py urlpatterns = [ path('add/', Smoke.as_view({'get', 'post'}), name='smokeping-add'), ] Is there anything I needed to do in order for the POST method to work properly in Fetch API? fetch('',{ method: 'POST', header: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) -
How to get current instance of model in graphene-python DjangoObjectType
I have a graphene-python DjangoObjectType class, and I want to add a custom type, but I don't know how to get the current model instance in the resolver function. I am following this tutorial, but I can't find any reference. This is my DjangoObjectTypeClass: class ReservationComponentType(DjangoObjectType): component_str = graphene.String() class Meta: model = ReservationComponent def resolve_component_str(self, info): # How can I get the current ReservationComponent instance here?. I guess it is somewehere in 'info', # but documentation says nothing about it current_reservation_component = info.get('reservation_component') component = current_reservation_component.get_component() return component.name -
request.POST.get returns NULL
I'm trying POST my text value from my HTML form to Django view but always get NONE as a result. Initially, I was trying to fetch value by request.POST which threw "MultiValueDictKeyError" then I changed my code to request.POST.get which is returning None HTML file <!DOCTYPE html> <html lang="en"> <head> {% block head %} <meta charset="UTF-8"> <title>Home Page</title> {% endblock %} </head> <body> {% block body %} <nav class="navbar navbar-expand-lg navbar-dark bg-dark" style="margin-left: -290px; margin-top: -50px"> <a style="font-family: Brush Script MT;font-size: 30px;color: azure"> HandBook.</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar1" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbar1"> <ul class="navbar-nav ml-auto"> <a class="btn btn-info btn-lg" style="padding: 2px; font-family: Courier;color: azure;font-size: 15px;margin-right: 10px" class="btn btn-info btn-lg"><i class="fas fa-book"></i> Yodlee Docs</a></li> {#<li class="nav-item dropdown">#} {# <a class="nav-link dropdown-toggle" href="#" data-toggle="dropdown"> Dropdown </a>#} {# <ul class="dropdown-menu">#} {# <li><a class="dropdown-item" href="#"> Menu item 1</a></li>#} {# <li><a class="dropdown-item" href="#"> Menu item 2 </a></li>#} {# </ul>#} {#</li>#} </ul> </div> </nav> </br> <button type="button" style="padding: 3px;margin-left: -250px; font-family: Courier" class="btn btn-info btn-lg" data-toggle="modal" data-target="#exampleModalCenter"> <i class="fas fa-wrench"></i> Add environment </button> <form method="post" action="/NewHandBook/AddEnvironment">{% csrf_token %} <!-- Modal --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 … -
Assign selected user to object Django
The following code assigns the logged in user to the object, how can I change it to assign the selected user from the dropdown menu to the object? <form method='POST' action="{% url 'post:car' post.id %}"> {% csrf_token %} <label for="select1"></label> <select class="mdb-select md-form" id="select1" onChange="form.submit();"> <option value="" disabled selected>Assign</option> {% for user in current_users %} <option value="{{ user.id }}"> {{ user }} </option> {% endfor %} </select> </form> The goal from the above is to assign the selected {{user.id}} to the {{post.id}} The urls.py is path('post/<int:tag>', views.assigned_post, name='car'), The current_users has been achieved by injection from the views.py using context['current_users'] = ProjectUser.objects.all() The views.py is def assigned_post(request, tag): as_curr = get_object_or_404(Post, id=tag) if request.method == 'POST': if as_curr.assigned_to: as_curr.assigned_to = None as_curr.save() else: as_curr.assigned_to = request.user # < -- Assign to drop down user instead of current user as_curr.save() return HttpResponseRedirect(reverse('post:tasks')) The models.py is class Post(models.Model): assigned_to = models.ForeignKey(ProjectUser, related_name="assigned_user", blank=True, null=True, on_delete=models.CASCADE) -
Is there any settings to set url based proxy setup?
How to set url based proxy setting in django? module.exports = { devServer: { proxy: { "/api": { target: "http://localhost:5000", ws: false, changeOrigin: true } } } }; we can do like this in vue. but i wanna this for django have to do like that. What to do? Or else Is there any way access this config in django? -
How to view user details in profile page using session in django?
I'm new in django,I need a help.How to view a person profile in template using django?.I used {{tablename.Username}}to view the user name.It is working properly on the home page.But when i used the same to the view profile page to show all the fields it's not working.Please help !! -
Best way to handle unique together error - Django 2.2?
I know this question has been asked many times, but still i am unable to find the right solution., let's say i have model like follow class Student(models.Model): number = models.IntegerField() department = models.ForeignKey(Department, on_delete=models.CASCADE) class Meta: constraints = [ models.UniqueConstraint(fields=['department', 'number']) ] and my serializer look like follow. class StudentModelSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ("number",) In this model department and number is unique together, now the department is fetched from pk passed in url. the way i am handling unique error is like follow. class StudentViewSet(ModelViewSet): queryset = Student.objects.all() serializer_class = StudentModelSerializer def perform_create(self, serializer): department = Department.objects.get(pk=self.kwargs['pk']) serializer.save(department=department) def create(self, request, *args, **kwargs): try: return super().create(request, *args, **kwargs) except IntegrityError as err: if 'UNIQUE constraint' in err.message: raise ValidationError({ 'number': 'Number field should be unique.' }) else: raise IntegrityError(err) As seen above i invoked the super().create() catch the exception, then checks the UNIQUE message presents, if present i am raising validation error again, so rest framework's exception handler handle that. if not i am raising error again. The problem with this approach is i am checking unique error with the message UNIQUE which may change in future., of course i can add department to serializer … -
Unable to unpack django context data into template that renders heatmap
I have a heatmap as part of a django template. I am sending the 2D data required for the heatmap from my view but I am having difficulties unpacking the context data. In my view: context['heatmap']=[[32, 22, 48, 77, 0, 6], [19, 12, 28, 30, 0, 3], [15, 30, 144, 70, 29, 31]] In my template var ZValues = [{% for value in heatmap %} "{{ value }}", {% endfor %}]; My attempt does not work. Any help is greatly appreciated -
Multi-Tenancy with Django, unable to authenticate user from multiple isolated databases
I am currently working on a django application to feature multi-tenancy. I am currently using an isolated data base model for my project. I currently have two databases. 1. Default 2. Alora The project logs me in effortlessly on choosing the Default database. However, I am facing problems on selecting Alora and working on it. Although I am unable to find the problem while debugging. Both database are similar and have one superuser created on them. My differentiator for selecting the database is using a field called school_ID. positive test cases: username: harish password: Happy@123 school ID: default The above should make me work on the default database. username: admin password: Happy@123 school ID: Alora the above should make me work on the Alora database. I have edited the following files in django.contrib.auth. Please note that I have only pasted the changed section of the file. the remaining would stay the same. forms.py - to include a third authentication field- school_ID class AuthenticationForm(forms.Form): """ Base class for authenticating users. Extend this to get a form that accepts username/password logins. """ username = UsernameField(widget=forms.TextInput(attrs={'autofocus': True})) password = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput, ) school_ID = forms.CharField(widget=forms.TextInput(attrs={'autofocus': True})) error_messages = { 'invalid_login': _( … -
I am looking for an efficient django queryset to stop so many hitting my DB
I am looking for an efficient queryset because my codes are trying to ignite my database. As you can see in the code below, these are too inefficient. But I have no idea how to change them to small lines codes efficiently with select_related and prefetch_related. Framework : Django 2.2 -------models.py-------- class SubjectModel(models.Model): project = models.ForeignKey(ProjectModel, on_delete=models.CASCADE) sex = models.CharField(choices=SEX, max_length=1, blank=True) hospital = models.ForeignKey(UserProfile, on_delete=models.CASCADE) age = models.CharField(blank=True, max_length=10) status = models.CharField(choices=STATUS, max_length=3, default='on') class SubjectDateModel(models.Model): whose = models.ForeignKey(SubjectModel, on_delete=models.CASCADE) will_visit_date = models.DateField(blank=True, null=True) visited_date = models.DateField(blank=True, null=True) visit_check = models.BooleanField(default=False) FEELING = ( (1, 'sobad'), (2, 'bad'), (3, 'normal'), (4, 'good'), (5, 'verygood'), ) FLAG = ( ('device', 'DEVICE'), ('drug', 'DRUG'), ('side', 'SIDEEFFECT'), ('feel', 'FEELING'), ('pain', 'PAIN'), ) DRUG = ( ('yes', 'ATE'), ('no', 'NO'), ) class DataModel(models.Model): user_id = models.ForeignKey(SubjectModel, on_delete=models.CASCADE) beacon_info = models.CharField(max_length=100, blank=True, null=True) drug = models.CharField(choices=DRUG, max_length=3, blank=True, null=True) side_effect = models.CharField(max_length=50, blank=True, null=True) side_effect_more = models.CharField(max_length=255, blank=True, null=True) feeling = models.PositiveSmallIntegerField(choices=FEELING, blank=True, null=True) pain = models.PositiveSmallIntegerField(blank=True, null=True) date = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) flag = models.CharField(choices=FLAG, max_length=6) -------views.py-------- def subject_detail(request, pk): details = get_object_or_404(SubjectModel.objects.select_related('hospital__whose').select_related('project'), pk=pk, status='on') dates = SubjectDateModel.objects.filter(whose=details) drug_percent = details.project.drugs.when count = 0 for i in drug_percent: count = count + …