Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Running 2 django project in different port number at the same time
As what the title said, is it possible to run 2 django project at the same time ? Since by default, all django run by http://127.0.0.1:8000/. Is there anyway i can change the port number for both the django project ? My task is this: Integration of django 1 api and django 2 api, to setup two django app, on same server / PC, with different port As far from what i know, i can change the port number in the settings.py database section. I also cant seems to find much information about this. The only solution i found which is running this command: manage.py runserver 8005 will allow the django project to run in 8005 port. But is it possible to do it without writing the command and just do it in the settings.py or other file ? As i know this is just for development phrase. If its on production, it cannot use in this way. -
How to iterate 'dict' with 'enumerate'
I have the following code. This just show me one user instead of all the users I have inside my JSON, and also I have another problem, when I'm concatenating my strings it show me a "\" after I put a '"': def get(self, request, format=None): users = Caseworker.objects.all() response = self.serializer(users, many=True) for j in range(0,len(response.data)): dictionary = response.data[j] myresponse = "" for i, (val, v) in enumerate(dictionary.items()): myresponse = myresponse + '{"text":' + '"' + v + '"' + '}' + ',' print(myresponse) # for i,(k,v) in enumerate(dictionary.items()): # myresponse = myresponse + '{"text":' + '"' + v + '"' + '}' + ',' # print(myresponse) return HttpResponse(json.dumps({'messages': myresponse}), content_type='application/json') -
Django under supervisord?
django project is running under supervisord, when i try to edit the html templates, nothing changes in the web site, should I restart the supervisord or is there other easier way to make changes to the project? -
Update django view context from another part of application
I have two django applications A and B, i have overidden a template of A in B by dding an extra button. Now on click of this button i want to update the context of application A view. How can i do it in application B. -
Integrating redis with django
I am newbie in Django,My task is design a backend where there will be login system(using the dfault user table provide by django).There are two other tables one is the image table which has the imgvalue column which contains the key from redis database.The other table(imgacl) is to provide the access control to users for viewing the particual images which a required user has access.The redis databse is actually storing the images with key-value pair,and that key is stored in the imgvalue column.Here are my codes: models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class Image(models.Model): imgvalue = models.Charfield(max_length =250) class Imageacl(models.Model): id = models.ForeignKey(Image,on_delete =models.CASCADE) A separate python program for storing 50 images in Redis db.Suppose there are 5 users, the user1 can view 10 images,users2 can view 15 images............ import redis from PIL import Image rd = redis.StrictRedis() for x in range(1,51): img = open("{}.jpg".format(x),"rb").read() rd.set("key{}".format(x),img) I have two question:1)How I wll integrate redis with django & 2)How I will provide the access control to users?? -
Java based ORM vs Django ORM?
I have worked on Java web applications (using Spring framework with Hibernate as ORM) and python web applications (using Django with its inbuilt ORM). Please help me in comparing Hibernate (or any java based ORM like datanucleus or mybatis) and django ORM. Comparison will be specific to: Ease of use Handling of complex queries like doing multiple joins, partitioning, group by, having clause etc. Query execution performance Prior experience with java based ORM - not at all easy to use, have to do a lot of configuration, unable to write complex queries like joining multiple tables and all(it might be design issue). I have seen a lot of projects in which raw query has been written for the particular database which beats the MAIN purpose of ORM. Experience with Django ORM - easy to configure, easy to use, can easily write complex queries. -
How to create a virtual environment for Django in Pycharm?
Currently, I am developing a Django web app in a virtual environment but when I try to edit the web app it just seems that the libraries that I installed in the virtual environment are not found. This is the scenario I have: I installed a virtual environment in C:\Users\myUser\PycharmProjects. mkdir virtualenvs ; cd virtualenvs python -m venv virtualenvs I got access to the new folder, activated the virtual environment, upgrading pip and started installing the libraries I need for my project. cd C:\Users\myUser\PycharmProjects\virtualenvs\virtualenvs\Scripts ; .\activate (virtualenvs) python -m pip install --upgrade pip (virtualenvs) pip install django djangorestframework pandas numpy requests I go back to C:\Users\myUser\PycharmProjects to create my new Django project (I am still inside of my virtualenvs). (virtualenvs) mkdir C:\Users\myUser\PycharmProjects\apps ; cd C:\Users\myUser\PycharmProjects\apps (virtualenvs) django-admin.exe startproject app1 (virtualenvs) python manage.py startapp web_app_navigator (virtualenvs) python manage.py runserver I am able to see the Django successful message The install worked successfully! Congratulations!, but when I open this new application in PyCharm to do some changes such as trying to import any library that I installed I get an error message that the library is not found. My guess is that the virtualenvs and app folder is in some way disconnected … -
Django: how do i create a model dynamically
How do I create a model dynamically upon uploading a csv file? I have done the part where it can read the csv file. -
How can i resolve HTTPSConnectionPool(host='www.googleapis.com', port=443) Max retries exceeded with url (Google cloud storage)
I have created API using Django Rest Framework. API communicates with GCP cloud storage to store profile Image(around 1MB/pic). While performing load testing (around 1000 request/s) to that server. I have encountered the following error. I seem to be a GCP cloud storage max request issue, but unable to figure out the solution of it. Exception Type: SSLError at /api/v1/users Exception Value: HTTPSConnectionPool(host='www.googleapis.com', port=443): Max retries exceeded with url: /storage/v1/b/<gcp-bucket-name>?projection=noAcl (Caused by SSLError(SSLError("bad handshake: SysCallError(-1, 'Unexpected EOF')",),)) -
How to iterate the values in the list in django template?
I am going to print four array values simultaneously in django template . like this the four arrays are of equal length ,they are header_list , domain_list , domain_data , dom for i in range(10): print headerlist[i] print domain_list[i] print domain_data[i] print dom[i] how to acheive these in django template . also tried from django import template register = template.Library() @register.filter(name='myrange') def myrange(number): return range(number) -
Django Rest Framework - Multiple "lookup_fields" URL router.register
I can't seem to figure out how to register a route with multiple lookup_fields in the case where there is a composite primary key. My look up fields are isin and valuedate The ideal url would look either like: /price/?isin=AT0000383864&valuedate=2018-01-16 or /price/AT0000383864/2018-01-16 when i update my views.py to the multi look up I get the following error lookup_field = ('isin','valuedate') ImproperlyConfigured: "^price/(?P[^/.]+)/(?P[^/.]+)//(?P<(u'isin', u'valuedate')>[0-9a-f]{32})/$" is not a valid regular expression: bad character in group name u"(u'isin', u'valuedate')" urls.py # router.register('price', priceViewSet, 'price') If i revert back to just isin in my lookup_field I can narrow my record set by making the URL /price/AT0000383864 But never the next level Thanks -
how to pass the email of the current user login in python function django
this is my python function i want to pass the user's email to my variable to_email how can i do that? def email_two(request): subject = "Skin Diagnosiss" message = 'Image that has been diagnosed \n https://aqueous-citadel-60536.herokuapp.com' + fname from_email = settings.EMAIL_HOST_USER member = Member.objects.get(email=request.POST['email']) to_email = [member] send_mail(subject, message, from_email, to_email, fail_silently=False) return HttpResponse('Diagonis successfully sent to your emai') -
I did not get the data in APIView
In my APIView: data = { "user":user_dict, # the user_dict have data. "account":account_dict # the account_dict have data too. } serializer = UserInfoSerializer(data=data) is_valid = serializer.is_valid() # the `is_valid` is True return Response(data=serializer.validated_data, status=HTTP_200_OK) But when I access this APIView, I get nothing. The UserInfoSerializer code is bellow: class UserInfoSerializer(Serializer): user = serializers.DictField(read_only=True) account = serializers.DictField(read_only=True) -
I'm trying to implement Pyrebase on my Django Project but somehow I get an error when I try to login the user
Here is the complete Traceback [16/Jan/2018 11:43:13] "GET /login/ HTTP/1.1" 200 2019 Internal Server Error: /login/ Traceback (most recent call last): File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\views\generic\base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\views\generic\base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\views\generic\edit.py", line 182, in post if form.is_valid(): File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\forms\forms.py", line 183, in is_valid return self.is_bound and not self.errors File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\forms\forms.py", line 175, in errors self.full_clean() File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\forms\forms.py", line 385, in full_clean self._clean_form() File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\forms\forms.py", line 412, in _clean_form cleaned_data = self.clean() File "C:\Users\CLAIRE\Desktop\Thesis\finalThesis\well\now\accounts\forms.py", line 130, in clean login(request, user) File "C:\Users\CLAIRE\Anaconda3\lib\site-packages\django\contrib\auth__init__.py", line 154, in login request.session[SESSION_KEY] = user._meta.pk.value_to_string(user) AttributeError: 'dict' object has no attribute '_meta' [16/Jan/2018 11:43:26] "POST /login/ HTTP/1.1" 500 105312 forms.py from django import forms from django.contrib.auth import authenticate, login, get_user_model from django.contrib.auth.forms import ReadOnlyPasswordHashField from profileacc.models import DocProfile import pyrebase User = get_user_model() config = { 'apiKey': "AIzaSyB0bEes5zKUjJqiOL7YWtJ0RdtFbhqqDBM", 'authDomain': "chartsdjango.firebaseapp.com", 'databaseURL': "https://chartsdjango.firebaseio.com", 'projectId': "chartsdjango", 'storageBucket': "chartsdjango.appspot.com", 'messagingSenderId': "176923102759" } firebase = pyrebase.initialize_app(config) auth = firebase.auth() class UserAdminCreationForm(forms.ModelForm): """A form for creating new users. Includes all … -
Django rest framework integrate 2 different django project API
I have 2 different django project. Django 1 is a social medical app which is for user with their medical information. Django 2 is a doctor app which is for the doctor and staff who will prescription details to patient who visited them. So i have these task. Integration of django 1 api and django 2 api, on django api method on django 1 api, code to POST BookAppt Integration of django 1 api and django 2 api, on django api method on django 2 apiI, code to GET BookAppt Integration of django 1 api and django 2 api, on django api method, connect to another API From my understanding, django 1 will post to django 2 BookAppt API. But how do i integrate these 2 app together so that i can post from django project 1 into django project 2 ? Is it possible to give an example ? As i cant find any link which helps me for these situation. -
Django: Server Error (500) when Debug is False
I'm trying to configure my Django app for production. When I set Debug to False I get "Server Error(500)" When I set debug to true, I get this error instead TemplateSyntaxError at /beginners/ Invalid block tag on line 11: ''style.css''. Did you forget to register or load this tag? Things I've tried: manage.py collectstatic && y Relevant code snippets: STATIC_URL = '/static/' PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') STATICFILES_DIRS = ( os.path.join('static'), ) SECRET_KEY = os.environ.get('SECRET_KEY', "default_value") BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ALLOWED_HOSTS = ['*'] [installed_apps] 'django.contrib.staticfiles', I think it's because it cannot locate my static folder, since that is the error I get when debug is true -
Automatic retrying after deadlock in django and mysql setup causes duplicate entry
I'm using solution from Hook available for automatic retry after deadlock in django and mysql setup to handle deadlocks, I thought in case of deadlock exception, the corresponding SQL operation should fail, not changing the status of data in the database. But it seems I was wrong. When I insert some data into a table with unique restrictions, the first try failed because of deadlock, And then execute_wrapper retried automatically, which failed with IntegrityError (1062, "Duplicate entry '96-1160' for key 'xxxxxxxxxxxxx_id_4714853c_uniq'") exception. Can anybody tell me why the first try still changed the data in case of deadlock exception? And any suggestions on how to handle it? Thanks! The execcute_wrapper code listed as below: original = django.db.backends.utils.CursorWrapper.execute def execute_wrapper(*args, **kwargs): attempts = 0 while True: try: return original(*args, **kwargs) except OperationalError as e: code = e.args[0] if attempts == 10 or code != 1213: raise e attempts += 1 time.sleep(0.3) django.db.backends.utils.CursorWrapper.execute = execute_wrapper Thanks! -
Distributed or Central Authorisation in Django Microservices
I'm building a Django rest framework based service which has some complicated permissions. So far, my microservices stack looks like this: /auth/ JWT authentication service /users/ - adding users, adding them to different services /new-service/ - needs authorization Users database is shared by auth and users read-only, and read/write respectively. new-service has no access to this database but the challenges consist of: user can be in multiple groups specific to that service user could have read-only access to one item in one of the groups user could be allowed to create new users with access to one of the groups users have different roles in the service, but we still need to allow for access like the read-only one listed Groups are used not to manage users, but to provide access to things. Like GitLab groups provide access to GitLab projects. If I put all the permissions in the users service, my new service has to talk to that one and it will get chatty. It seems like there has to be a data divide, but I'm not sure exactly where to put it. Conversely, should the django-rest-framework service even have a shadow entry of the user account in it's … -
Django Form Not Posting to SQL
I have a page where an item from a list nested within my form can be favorited, it redirects back to the same page following what should be an update to the database, then it shows a star next to the item. While this should work fine my form doesn't change the DB at all. I am confident it is not the html rendering since when I manually change the field in the admin panel it renders fine. What is causing this to not post? view.py: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from django.template import loader from .models import Album, Song # Create your views here. def index(request): all_albums = Album.objects.all() template = loader.get_template('music/index.html') context = {'all_albums' : all_albums,} return render(request, 'music/index.html', context) def detail(request, album_id): album = get_object_or_404(Album, pk=album_id) return render(request, 'music/detail.html', {'album' : album}) def favorite(request, album_id): album = get_object_or_404(Album, pk=album_id) print("favorite stuff happens here") try: selected_song = album.song_set.get(pk=int(request.POST['song'])) except (KeyError, Song.DoesNotExist): return render(request, 'music/detail.html', { 'album' : album, 'error_message': 'Did not select a valid song' }) else: selected_song.favorite = True selected_song.save() return render(request, 'music/detail.html', {'album' : album}) <img src="{{album.album_logo}}"> <h1>{{album.album_title}} </h1> <h2>{{album.artist}} </h2> {% if error_message %} <p><strong> {{error_message}} </strong></p> {% endif %} <form … -
Dropdown Menu Not Working When Implementing with Django
I'm new to working with Django and am running into a problem implementing it into the static site that I've made. Could you please advise as to why the dropdown menu is not working (not dropping down)? It was working fine when it was just the html/css files before django implementation. Attached image shows the file/folder layout - please let me know if you need to see any of the additional files and I can post them. Am thinking I have some css in the wrong directory (?) Image: IMAGE {% load staticfiles %} <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="Test Site"> <meta content="width=device-width, initial-scale=1, user-scalable=no" name="viewport"> <title>Test Site</title> <meta name="description" content="Test Site Web Application"/> <link rel="shortcut icon" href="{% static 'themes/images/favicon.ico' %}"> <!-- Google icon --> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!-- Bootstrap css --> <link rel="stylesheet" href="{% static 'assets/css/bootstrap.min.css' %}"> <!-- Propeller css --> <!-- build:[href] assets/css/ --> <link rel="stylesheet" href="{% static 'assets/css/propeller.min.css' %}"> <!-- /build --> <!--Propeller date time picker css --> <link rel="stylesheet" href="{% static 'components/datetimepicker/css/bootstrap-datetimepicker.css' %}" /> <link rel="stylesheet" href="{% static 'components/datetimepicker/css/pmd-datetimepicker.css' %}" /> <!-- Propeller theme css--> <link rel="stylesheet" href="{% static 'themes/css/propeller-theme.css' %}" /> <!-- Propeller admin theme css--> <link rel="stylesheet" href="{% static 'themes/css/propeller-admin.css' … -
Use 'pass' return value in another function in python
I am using python 3.5. Function1 is : def boolean_key_validation(dictionary, key): data = {} try: dictionary_value = dictionary[key] except KeyError: pass else: if dictionary_value == 'TRUE': data[key] = True elif dictionary_value == 'FALSE': data[key] = False else: raise ValueError("{} value should be either blank or 'TRUE'/'FALSE' only".format(key)) return data[key] # not able to get the 'do_nothing' value here Function 2 is : def read_file(start_date, end_date, dictionary): read_data = {} files = File.objects.all() # ... # read_data['downloaded'] = boolean_key_validation(dictionary, 'downloaded') read_data['integrity'] = boolean_key_validation(dictionary, 'integrity') read_data['validation'] = boolean_key_validation(dictionary, 'validation') return files.filter(**read_data) I want to filter my model 'File' based on the boolean values of 'downloaded', etc. In function1 what I want is that if key is not present in dictionary this function1 should do nothing and my read_data dictionary in function2 should have no value for that key. I have searched for similar problem but those are using 'pass' in conditional statements within some function. -
Select Element in a Django Form
I am learning the Django framework, and I would like to build all of my forms the "Django way" instead of the old fashioned HTML way. Could someone please show me a simple example of how to build a simple select element within a form.py file? -
NOT NULL constraint failed: with my create function
I'm trying to have one view that produces 2 forms and saves them both with one button. I have a good idea on how to accomplish this in an update view so I'm trying to apply the same logic with a create view. Everything seems to be working ok but I'm getting a NOT NUlL constraint failed error. I realize that this error has something to do with my second form probably not being able to find the "carrier" to attach itself too, I just don't know how to go about solving it. Here's my code: MODELS.PY class Carrier(models.Model): carrier_name = models.CharField(max_length=255, unique=True) mc_number = models.CharField(max_length=10, unique=True, blank=True) dot_number = models.CharField(max_length=15, unique=True, blank=True) carrier_ein = models.CharField(max_length=9, unique=True) carrier_phone = models.CharField(max_length=10) carrier_phone_two = models.CharField(max_length=10, blank=True) carrier_phone_three = models.CharField(max_length=10, blank=True) carrier_fax = models.CharField(max_length=10, blank=True) carrier_email = models.CharField(max_length=50, blank=True) US_STATES_OR_CAN_PROVINCES = ( ('AK', 'Alaska'), ('AL', 'Alabama'), ('AR', 'Arkansas'), ('AS', 'American Samoa'), ('AZ', 'Arizona'), ('CA', 'California'), ('CO', 'Colorado'), ('CT', 'Connecticut'), ('DC', 'District of Columbia'), ('DE', 'Delaware'), ('FL', 'Florida'), ('GA', 'Georgia'), ('GU', 'Guam'), ('HI', 'Hawaii'), ('IA', 'Iowa'), ('ID', 'Idaho'), ('IL', 'Illinois'), ('IN', 'Indiana'), ('KS', 'Kansas'), ('KY', 'Kentucky'), ('LA', 'Louisiana'), ('MA', 'Massachusetts'), ('MD', 'Maryland'), ('ME', 'Maine'), ('MI', 'Michigan'), ('MN', 'Minnesota'), ('MO', 'Missouri'), ('MP', 'Northern Mariana Islands'), … -
Edit image in Django not working
I have created a application form with photo. I have used imagefield for photo. The photo is saved properly in create form and displayed back in the template. The image is not seen in the edit form application. profile=get_object_or_404(Profile, id=pk) form=ProfileForm(request.POST or None, request.FILES or None, instance=profile) form2=EducationForm(request.POST or None, instance=profile.education) form3 = FamilyForm(request.POST or None, instance=profile.family) form4 = OtherForm(request.POST or None, instance=profile.other) if request.method == "POST": if form.is_valid() and form2.is_valid() and form3.is_valid() and form4.is_valid(): profile = form.save(commit=False) for language in request.POST.getlist('languages'): profile.languages.add(language) profile.save() education = form2.save(commit=False) education.profile = profile education.save() family = form3.save(commit=False) family.profile = profile family.save() other = form4.save(commit=False) other.profile = profile other.save() messages.add_message(request, messages.SUCCESS, 'Sucessfully Updated Profile') return HttpResponseRedirect(reverse('vived:index')) -
Using instance attributes conditionally determine ModelAdmin inlines? (Django 2.0)
Context: I am writing an app for distributing company policies to users, for them to read and take a test if the policy mandates they do so. The Policy model includes a 'quiz_required' boolean which I would like to use to determine whether the QuizInLine should be included in the inlines of the PolicyAdmin instance. Similar feeds on this issue advise overriding the get_inline_instances and get_form_sets however this produces a Validation Error: ManagementForm data missing error while formset validation. If anyone knows an optimum way of achieving this aim I would be very grateful for the help. Thanks you. models.py class Policy(models.Model): title = models.CharField(max_length = 100)`enter code here` policy = RichTextField() requires_quiz = models.BooleanField('Quiz', default=False) admin.py class QuizInLine(admin.StackedInline): model = Quiz class PolicyAdmin(admin.ModelAdmin): model = Policy fieldsets = [ ('Policy', {'fields': ['title','policy','requires_quiz',]}), ] inlines = [] quiz_inlines = [QuizInLine,] def get_inline_instances(self, request, obj=None): inline_instances = [] if obj.requires_quiz: inlines = self.quiz_inlines else: inlines = self.inlines for inline_class in inlines: inline = inline_class(self.model, self.admin_site) if request: if not (inline.has_add_permission(request) or inline.has_change_permission(request) or inline.has_delete_permission(request)): continue if not inline.has_add_permission(request): inline.max_num = 0 inline_instances.append(inline) return inline_instances def get_formsets(self, request, obj=None): for inline in self.get_inline_instances(request, obj): yield inline.get_formset(request, obj)