Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am try to get object of the logged in user in django? This list that is been created while form.save of the user that is logged in
Hello as I posted here before I new to django python need some help on how to get objects of a user that is currently logged in. I have an app named stores which contains a models named Store. I just want to gather the list of stores a user created. Do I have to add anything in setting.py ? I am really confused about it I also tried request.user and tried to filter the object but I wasn't able to do it. I am posting my code over here kindly look into it and do let me know. Do let me know if you need anything else to understand. views.py of stores app from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import NewStore from .models import Store def store(request): form = NewStore() if request.method == 'POST': form = NewStore(request.POST) if form.is_valid(): form = form.save() return redirect('stores_list') else: form = NewStore() return render(request, "default/store.html", {'form': form}) @login_required() def stores_list(request): my_stores = Store.objects.all() print(my_stores) return render(request, "default/stores_list.html", {'my_list': my_stores}) models.py of stores app from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Store(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) lat = models.DecimalField(max_digits=50, decimal_places=20) long = … -
How can i edit multiple users info in one page?
Lets say, I want to make a page in my website where I want to be able to enter in the DB if workers are present or not. Every worker has separate profile page. In my, models.py→→ class profile(models.Model): ...#other fields present = models.BooleanField(default=1) Prototype Picture In the prototype picture, if it is green it should be True in the booleanfield means present(this is defualt), and when I click their name, the booleanfield will be false means absent and it will be red. How can achieve this? I need the template and the view code. -
Serialization Method error
Hello I have model Brand and model BrandEditor which is used as mask to collect all personal brands of company. I want to add Brand to BrandEditor of user, which is creating the brand instance and If there is no BrandEditor - first create it. Have a code: class BrandAddSerializer(serializers.ModelSerializer): editor = serializers.SerializerMethodField('create_editor') class Meta: model = Brand fields = ('id', 'editor', 'name', 'image', 'description') def create_editor(self): if BrandEditor.objects.filter(owner__user=CurrentUserDefault).exists(): editor = BrandEditor.objects.filter(owner__user=CurrentUserDefault) return editor else: company = Company.objects.filter(user=CurrentUserDefault) BrandEditor.objects.create(owner=company) editor = BrandEditor.objects.filter(owner__user=CurrentUserDefault) return editor I catch create_editor() takes 1 positional argument but 2 were given, what am I doing wrong? Thanks! -
Django username in the User model can not be repeated
I am trying to create users in the django django.contrib.auth.models.User model but when I use a username which already exists in the database it will give me an error like: {username: ["A user with that username already exists."]} as an http response How can I disable this in django so I can have many users with the same username Thanks all. -
Django change model fields attributes?
If I change the model fields attributes in django should I remigrate them? will it afftect the data that is already stored there? is it safe to make that change in an already running project? -
How to use an existing django database for another project
I already have a project A which is live and now I want to create B which uses the same database of A and also the authentication can be interoperable. How can I accomplish that? I created a app called core and in that I did python manage.py inspectdb it did give me all the models but I am not able to manage the auth for both the instances will I require to use the sites framework? -
How to alert user if the name already present in the database when user try to add. Using Django, Ajax
This is code for adding the Name and Id for the plans. i want this code to be modified so user will get the warning msg with jquery popup if the database already have component name user entered if not then user data should be saved HTML Component ajax $.ajax({ type:"POST", url:"/insertPlans/", async: false, cache : false, data: { 'component_name': component_name, 'plan_id' : plan_id, }, view.py def insertPlan(request): try: logger.info("{insertplan} --called") plan_id = request.POST['plan_id'] component_name = request.POST['component_name'] query = "insert into dbo.mydbname(name, plans) \ values('%s', '%s')" % (component_name, plan_id) DBOperations.insertToDB(query,"nameproj") context = fieldView.addCustomerView(request) except: logger.error(str(traceback.format_exc())) request.session['last_activity'] = str(datetime.now().replace(microsecond=0)) return render_to_response('homepage/addhomepage.html', context, context_instance=RequestContext(request)) -
How to create multiple tables for authentication in django
There is anyway to create two user tables that can be authenticated in django one table will be used to register normal users and other admins but that can not be related with django.contrib.auth thanks -
Trigger function on model deletion and reference deleted model in Django Python
Hey guys I'm using a version of Django that doesn't seem to suport pre_delete is there a way to trigger a function when a model is deleted? Also I need a way to reference the model being deleted inside the function so I can do stuff before deleting it. Thanks in advance! -
simple way for background task processing in django
In my webapp, suppose a user upplaods an image,I want to process that using a script lets say image.py and when its done then add it to dajngo sqlite database.What would be the most straightforward/easy implementation for such task without using celery etc considering processing can take upto 1-2 mins. -
Django duplicates the int id in the url path and displays 404 when accessing a property in javascript
I am using javascript embedded directly in django template, part of the javascript is also: var location = {{ location.id|safe }}; so I am accessing directly the location through javascript, but whenever I add this piece of code it causes django to generate a wrong url and then it throws a 404 page not found. It is worth mentioning that at first it finds the write page then upon the completion of rendering the page it redirects to url that does not exist: localhost:8002/tracker/locations/230/230/ it should be localhost:8002/tracker/locations/230/ and page not found is thrown. Going through the debug I am sure that a recall to the same view is not happening as the page first generates the right template then goes to 404 during the function: def process_request_thread(self, request, client_address) in sockerserver.py in django source code. here is my setup: view: def location_management(request, location_pk): template_name = 'tracker/locations.html' location = LocationsProxy.get(location_pk) location_handler = LocationHandler(location_pk, location.device_type_id) device_type = location_handler.device_type if device_type == 'chip': chips = location.retrieve_chips() queryset = ChipsProxy.aggregate_devices_to_batches(chips) elif device_type == 'osa': osas = location.retrieve_osas() queryset = OsasProxy.aggregate_devices_to_batches(osas) elif device_type == 'module': modules = location.retrieve_modules() queryset = OsasProxy.aggregate_devices_to_batches(modules) else: queryset = None page = request.GET.get('page',1) paginator = Paginator(queryset, 10) try: context … -
Add Double Color Django Oscar
I want to add a double color scheme to my Oscar Django based web shop. I am facing to issues: Can't provide color code Can't change the picture which should be displayed on frontend Can't be extended by dashboard user Example for color scheme Through Dashboard I want to make it clickable and extendable so user can put in color schemes by oneself. Clickable in Dashboard -
Save google map coordinates placed by user on django database
I am new in Django and Javascript and I meet some difficulties to build my project. Indeed, I would like to store data coordinates (latitude/longitude) into my database each time a user place one or multiple markers on the google map frame and valid a button. My first question is : What are the fields I need to create in a django model to retrieve one or multiple markers' coordinates for one user (i'm using the user model of Django) ? And how can I save the coordinates on django database each time a user place markers on the map and valid ? This is a part of my template that just display the lat/long coordinates on a table each time a user click on the map : <div class="col-sm-5"> <div id="googleMap" class="center-block img-rounded"></div> </div> <div class="table-responsive responsive-table-line" style="margin:0px auto"> <table class="table table-striped table-bordered table-hover table-body-center" id="tableMarkers" style="text-align: center;"> <thead class="thead-light"> <tr> <th># Marker</th> <th>Lat</th> <th>Long</th> </tr> </thead> <tbody> <tr id="marker0"> </tr> </tbody> </table> </div> <button class="btn btn-primary"> <strong> Save </strong> </button> </div> </div> </div> <script> var map; var marker; var i=0; function initialize() { var maPos=new google.maps.LatLng(45.003510,2.438965); var mapProp = { center: maPos, zoom:5, mapTypeId:google.maps.MapTypeId.ROADMAP, mapTypeControl: false, streetViewControl: false, … -
Error:" '_io.BufferedRandom' object has no attribute 'getvalue' " python
I am trying to use python-magic to identify the uploaded file type, i have used it to identify image and audio file it works fine but for video file it throws error. For video file i have class VideoFileUploadForm(forms.ModelForm): def clean(self): cleaned_data = super(VideoFileUploadForm, self).clean() upload_file = cleaned_data['upload'] try: if upload_file: supported_types = ['video/mp4', 'video/x-matroska', 'video/ogg','video/quicktime', 'video/x-ms-wmv', 'video/webm'] mimetype_of_file_uploaded = magic.from_buffer(upload_file.file.getvalue(), mime=True) val = 0 for item1 in supported_types: if item1 == mimetype_of_file_uploaded: val = 1 break if val == 0: raise ValidationError(u'Error! File can only be .mp4, .mkv,.ogg,.mov ,.wmv and .webm(video) format') except (RuntimeError, TypeError, NameError,AttributeError) as e: print(e) raise ValidationError("Error! Something is wrong.File should be .mp4," " .mkv,.ogg,.mov ,.wmv and .webm(video) format!") class Meta: model = VideoFileUpload fields = ( 'file_name', 'upload', ) def __init__(self, *args, **kwargs): super(VideoFileUploadForm, self).__init__(*args, **kwargs) self.fields['upload'].widget.attrs = { 'class': 'btn btn-block', 'name': 'myCustomName', 'placeholder': 'Upload file', 'required': 'true' } This code works fine if i supply image mime types and audio mime types in the place of "supported_types" but now for video it does not support what could be the reason Error thorwn is like this: '_io.BufferedRandom' object has no attribute 'getvalue' File i tried to upload is of .mp4 format which plays … -
Django-like unit testing database in plain python
I have a python project that uses Postgresql. I would like to use django-like unit tests where the database is created and destroyed at every test. However, I don't want to use sqlalchemy. I tried something along these lines: pg = psycopg2.connect( "host={} dbname={} user={} password={}".format( POSTGRES_HOST, 'postgres', POSTGRES_USER, POSTGRES_PASSWORD)) pg.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cur = pg.cursor() def reset_db(): cur.execute('DROP DATABASE IF EXISTS {} '.format(POSTGRES_DB)) cur.execute('CREATE DATABASE {}'.format(POSTGRES_DB)) newconn = psycopg2.connect( "host={} dbname={} user={} password={}".format( POSTGRES_HOST, POSTGRES_DB, POSTGRES_USER, POSTGRES_PASSWORD)) newcur = newconn.cursor() # SCHEMAS is an imported dict containing schema creation instructions for schema in SCHEMAS: newcur.execute(SCHEMAS[schema]) return newcur class Test(TestCase): def setUp(self): os.environ['testing'] = 'true' self.cur = reset_db() Then the setUp method sets an environmental variable that informs my database layer to use the testing db. This seems to work fine. The only problem is the reset_db() takes about 0.8 seconds, which is far too much. Are there better approaches or ways to optimise my approach? -
Batch script to automate Django installation process stop executing after activating virtual environment
This batch script is to automate the processes involved starting a Django Project but then there is a problem with my script. When it finished activating the virtual environment the rest of the commands does not execute. What I am doing wrong? @Echo off title Django Girls Workshop! @echo on mkdir djangogirls cd djangogirls python -m venv myvenv myvenv\scripts\activate @echo off echo Done Activating Virtual Environment! @echo on pip install --upgrade pip Rem You can change the django version on the next line pip install django~=1.10.0 django-admin startproject mysite . dir @echo off echo Yah! You just started a Django Project! echo Your project directory will open next. echo Do the necessary configurations! echo Happy coding! Timeout /T 5 @echo on start mysite -
Is it possible to pass django model objects in the datalist of an ajax function?
I am trying to create a dynamic dependent dropdown list. My attempt is not working as the options are not being loaded, on running the server. Scenario is a model with fields: scenario_id and scenario_name. The url name Get_Scenario links to the view function get_scenario given below. My .html file <form action="" method="post"> {% csrf_token %} <div class="row"> <div class="col-md-1"></div> <div class="col-md-5" id="orgdiv"> <select class="form-control" id="txtOrganization" > <option value="" disabled selected>Select Organization</option> {% for organization in Organization %} <option value="{{ organization.org_id }}">{{ organization.org_name }}</option> {% endfor %} </select> </div> <div class="row"> <div class="col-md-1"></div> <div class="col-md-5" id="scenariodiv"> <select id="txtScenario" class="form-control" required> <option value="" disabled selected>Select Scenario</option> </select> My ajax function $('#txtOrganization').on("input", function () { if (scenarios) { $.ajax({ type: "POST", url: {% url 'Get_Scenario' %}, data: {scenarios: scenarios}, success: function (data) { var udata = ""; for (var i = 0; i < data.length; i++) { udata = udata + "<option value='"+ scenarios[i].scenario_id + "'>" + scenarios.scenario_name + "</option>" } $("#txtScenario").append(udata); } }); } }); views.py def get_scenario(request): org_id = request.GET.get('org_id') organization = Organization.objects.get(pk=org_id) scenarios = organization.scenario_set.all() return scenarios I feel the problem lies in passing the django model object scenarios to the ajax function datalist, and perhaps it's not able … -
Django REST Framework - overriding JSONWebTokenAuthentication for custom JWT authentication
I have a Django application with external database, which means that for every user request I'm sending SQL queries to external DB server. No local DB (like sqllite or such) exists. Also, JWT should be used to authenticate users. To do so, I've overwritten ObtainJSONWebToken view: class ObtainJWT(ObtainJSONWebToken): def post(self, request, *args, **kwargs): username = request.data.get('username') password = request.data.get('password') # verify that user with given credentials exist in db resp = requests.post(settings.SERVER_HOST+"/auth/", json={"username":username, "password":password}) if resp.status_code == status.HTTP_401_UNAUTHORIZED: return Response({'error':'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED) # create token payload = jwtutils.jwt_payload_handler(username, password, api_settings.JWT_EXPIRATION_DELTA) token = jwt_encode_handler(payload) return Response({'token': token}, status=status.HTTP_200_OK) And jwt_payload_handler in jwtutils: def jwt_payload_handler(username, password, delta): # custom payload handler payload = { 'username': username, 'password': password, 'exp': datetime.utcnow() + delta } return payload Now I can successfully obtain token without using any User objects. But when obtained token is used (a user tries to access protected routes with the token), {"detail":"Invalid signature."} is returned. I think it's because DRF's JSONWebTokenAuthentication class that I'm using has authenticate_credentials method that checks if a user with given credentials exists in local DB ( https://github.com/GetBlimp/django-rest-framework-jwt/blob/master/rest_framework_jwt/authentication.py#L59 ), hence the error. So I decided to create custom authentication class. There is what I wrote: class JSONWebTokenAuthentication(BaseAuthentication): … -
Django version 2.0.6 is compatible with coverage 4.5.1?
I am working with test coverage using circleci and coveralls.io. But when i run build i am facing issues in configuration files. Here is Error: Submitting coverage to coveralls.io... Traceback (most recent call last): File "/home/circleci/.local/share/virtualenvs/Amazon_customers-UJeFg6OU/bin/coveralls", line 11, in sys.exit(main()) File "/home/circleci/.local/share/virtualenvs/Amazon_customers-UJeFg6OU/lib/python3.6/site-packages/coveralls/cli.py", line 48, in main result = coverallz.wear() File "/home/circleci/.local/share/virtualenvs/Amazon_customers-UJeFg6OU/lib/python3.6/site-packages/coveralls/api.py", line 71, in wear data = self.create_data() File "/home/circleci/.local/share/virtualenvs/Amazon_customers-UJeFg6OU/lib/python3.6/site-packages/coveralls/api.py", line 110, in create_data self._data = {'source_files': self.get_coverage()} File "/home/circleci/.local/share/virtualenvs/Amazon_customers-UJeFg6OU/lib/python3.6/site-packages/coveralls/api.py", line 118, in get_coverage workman._harvest_data() AttributeError: 'Coverage' object has no attribute '_harvest_data' Exited with code 1 I have tried and read many documents for solutions. Is there anybody who have any idea of that django 2.0.6 is compatible with coverage 4.5.1. -
Checking if an optional django form was posted or not before calling is_valid() on it
My user registration form is made up of 3 django forms but the third form is optional. The 3 django forms are UserPersonalDetailsForm, UserCompanyDetailsForm and the third and optional form is UserBankingDetailsForm. Now, I need to find a way to check in the view if the UserBankingDetailsForm was posted together with the other 2 form before I call is_valid() on it. The reason for this is that I want to know before time if my if-statement in the view should be if UserPersonalDetailsForm.is_valid() and UserCompanyDetailsForm.is_valid() and UserBankingDetailsForm.is_valid(): pass or should it be just if UserPersonalDetailsForm.is_valid() and UserCompanyDetailsForm.is_valid(): pass -
Unicode Encode Error 'latin-1' codec can't encode character u'\u2013' in position 4939: ordinal not in range(256)
I'm trying to render a pdf file for a transaction report in django. most of the transaction works fine. some throws this error UnicodeEncodeError at /app/finance/transaction-report/ 'latin-1' codec can't encode character u'\u2013' in position 4939: ordinal not in range(256) here is my pdf html {% extends "pdf_base.html" %} {% load i18n %} {% load static %} {% block content %} <h4 style="text-align: center; text-decoration: underline; font-weight: bold; margin-bottom: 15px;"> Transaction Report </h4> <table class='table-bordered'> <tr> <td> Type: </td> <td> {{instance.get_transaction_type_display|default:"-"}} </td> </tr> <tr> <td> Category: </td> <td> {% if not instance.transaction_category.is_system_generated or instance.transaction_category.name == "credit" or instance.transaction_category.name == "debit" %} {% if request.user.is_superuser or 'can_view_transaction_category' in user_instance.permissionlist %} {{instance.transaction_category.name}} {% else %} {{instance.transaction_category.name}} {% endif %} {% else %} {{instance.transaction_category.name}} {% endif %} </td> </tr> {% if category_name == "Vehicle payment" %} <tr> <td> Expense Type: </td> <td> {{instance.vehicle_expense|default:"-"}} </td> </tr> {%endif%} {% if instance.buidling_name %} <tr> <td> Building: </td> <td> {{instance.buidling_name|default:"-"}} </td> </tr> {%endif%} <tr> <td> Date: </td> <td> {{instance.date|default:"-"|date:"d/m/Y"}} </td> </tr> {% if instance.details %} <tr> <td> Details: </td> <td> {{instance.details|default:"-"}} </td> </tr> {% endif %} <tr> <td> Amount: </td> <td> {{instance.amount|default:"-"}} </td> </tr> {% if instance.amount_vat %} <tr> <td> Amount VAT: </td> <td> {{instance.amount_vat|default:"-"}} </td> </tr> {% … -
python django OR condition
I have this code: {{ object.subtotal }} I want to print 0 in case if object.subtotal is empty or false: I've tried like this: {{ object.subtotal or 0 }} but I've got a server error 500 -
Django equivalent of rail respond_to
In Rails, I can use respond_to to define how the controller respond to according to the request format. in routes.rb map.connect '/profile/:action.:format', :controller => "profile_controller" in profile_controller.rb def profile @profile = ... respond_to do |format| format.html { } format.json { } end end Currently, in Django, I have to use two urls and two actions: one to return html and one to return json. url.py: urlpatterns = [ url(r'^profile_html', views.profile_html), url(r'^profile_json', views.profile_json), ] view.py def profile_html (request): #some logic calculations return render(request, 'profile.html', {'data': profile}) def profile_json(request): #some logic calculations serializer = ProfileSerializer(profile) return Response(serializer.data) With this approach, the code for the logic becomes duplicate. Of course I can define a method to do the logic calculations but the code is till verbose. Is there anyway in Django, I can combine them together? -
Django messages framework not working inside XHR POST request
In my web page, there is an option to include an URL in a form which data is sent through a XHR request. In my server, I check if the URL written is correct, and if not, I generate an error message that will be displayed through a Materialize toast. The thing is that this mechanic I have done it before and works perfectly, now I copied the code and it doesn't store a message in the django session. My code: @login_required def analyze(request): if request.method == 'POST': ... if: ... else: print "hello there" messages.error(request, 'The URL introduced is not valid.') return render(request, "analyze.html") The else block is executed as I can see the "hello there" message in the terminal, but it looks like the message is not stored... Template {% block javascript %} {% if messages %} {% for message in messages %} {% if message.tags == 'error' %} <script> M.toast({html: '{{ message }}', classes: 'rounded red'}) </script> {% endif %} {% endfor %} {% endif %} ... {% endblock %} The thing is that if I put the message.error(...) before the if request.method == 'POST', it works perfectly fine each time I refresh the page. It could … -
Django filter with reverse relation
I am using django rest framework for API. And followed the document here. Here is a model named 'NetworkMember'. class NetworkMember(CommonInfo): name = models.CharField('name',max_length=255, blank=True, null=True, default=None) status = models.CharField(max_length=50, choices=NETWORK_STATUS_OPTS, default=None) network = models.ForeignKey(Network, related_name='network_members', on_delete=models.CASCADE, default=None) sender = models.ForeignKey(Account, related_name='sender', on_delete=models.CASCADE, default=None) receiver = models.ForeignKey(Account, related_name='receiver', on_delete=models.CASCADE, default=None) def __str__(self): return self.name Question is related to 'receiver' field only. So putting up below is the related 'Account' model. class Account(CommonInfo): name = models.CharField(max_length=50) is_master_ma = models.CharField(max_length=10, choices=IS_MASTER_MA_OPTS, blank=True, null=True,default=None) account_type = models.CharField(max_length=50, choices=ACCOUNT_TYPE_OPTS) master_account = models.ForeignKey('self', related_name='masterMA',on_delete=models.CASCADE, blank=True, null=True,default=None) billing_account = models.ForeignKey('self', related_name='BA',on_delete=models.CASCADE, blank=True, null=True,default=None) def __str__(self): return self.name One Billing account can have one master account. Again one master account can have multiple sub user accounts. So there are 2 self relations - master_account, and billing_account in the 'Account' model. Now the network members are related to master account. We have some devices too. And devices are related to billing accounts. Here is device model. class Device(CommonInfo): name = models.CharField(max_length=250) unique_id = models.CharField(max_length=100) status = models.CharField(max_length=50, choices=DEV_STATUS_OPTS, blank=True, null=True, default=None) billing_account = models.ForeignKey(Account, related_name='ba_devices', on_delete=models.CASCADE, blank=True, null=True, default=None) primary = models.CharField(max_length=50, choices=DEV_PRIMARY_OPTS, blank=True, null=True, default=None) def __str__(self): return self.name So I need to get devices of network …