Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Interfacing a QR code recognition to a django database
I'm coming to you with the following issue: I have a bunch of physical boxes onto which I still stick QR codes generated using a python module named qrcode. In a nutshell, what I would like to do is everytime someone wants to take the object contained in a box, he scans the qr code with his phone, then takes it and put it back when he is done, not forgetting to scan the QR code again. Pretty simple, isn't it? I already have a django table containing all my objects. Now my question is related to the design. I suspect the easiest way to achieve that is to have a POST request link in the QR code which will create a new entry in a table with the name of the object that has been picked or put back, the time (I would like to store this information). If that's the correct way to do, how would you approach it? I'm not too sure I see how to make a POST request with a QR code. Would you have any idea? Thanks. PS: Another alternative I can think of would be to a link in the QR code to … -
Django: Successive Queryset Filtering Stops Filtering after First Query
The debug session below illustrates what I am trying to say. I have executed this under the Django dev server, Cherrypy server and Werkzeug debugger. Using Django 1.11.10 on Windows 10, MySQL 5.5 back end. The function (at the end of this post) does successive filtering on a QuerySet. I stopped execution to perform some sanity checks. What I found is that the first filter operation worked event_values.count() == 14 but any further attempts to filter would always yield the same results. For example, I filtered on a pk=72 and still all 14 model instances were returned. I tried to use get(pk=72) and got a MultipleObjectsReturned exception. Interestingly, when I perform the successive filtering in the Django shell, I get the results that I am supposed to get. Is this a bug in Django? Am I doing something wrong? Thanks in advance. (Pdb) l 160 event_values = event_values.filter( 161 tsn__gte=tsn_start, tsn__lte=tsn_end) 162 163 import pdb; pdb.set_trace() 164 165 -> if tso_start or tso_end: 166 tso_start, tso_end = resolve_ranges(tso_start, tso_end) 167 168 event_values = event_values.filter( 169 tso__gte=tso_start, tso__lte=tso_end) 170 (Pdb) tsn_start 5800 (Pdb) tsn_end 6000 (Pdb) event_values.count() 14 (Pdb) event_values <QuerySet [<ComplianceEvent: pk: 72 -- 383201 -- 2017-12-11 -- SB>, <ComplianceEvent: … -
How do I import constants from my settings.py file into my Django console?
I'm using Python 3.7 with Django. I have this at the end of my settings.py file MAX_AGE_IN_HOURS = 18 When I fire up my console, how do I get this constant recognized? I have tried teh below, but get an error complaining that the above is not defined. from django.conf import settings (age.seconds / 3600) > MAX_AGE_IN_HOURS Traceback (most recent call last): File "<input>", line 1, in <module> NameError: name 'MAX_AGE_IN_HOURS' is not defined -
Nginx upstream error when trying to upload from cache using Django
I have a web application where one of the features is uploading a file into a specific system. The file is uploaded to a remote API by Django through an Ajax call using the requests python module. This works fine when I run the app locally but when I run it through Nginx I always get the following error when I try to upload the file [error] 22665#0: *254004 upstream prematurely closed connection while reading response header from upstream, client: xxx.xxx.xx.xx, server: redacted.com, request: "POST /report/ajax/upload_file/ HTTP/2.0", upstream: "http://unix:/var/www/webapp.sock:/report/ajax/upload_file/", host: "redacted.com", referrer: "https://redacted.com/report/key/sha256/" And a 502 error in the developer tools POST https://redacted.com/report/ajax/upload_file/ 502 The client side code which makes the ajax call is function handleUploadButton() { $('#upload-button').on('click', function() { var data = new FormData(); var file = $('form input[type=file]')[0].files[0]; data.append('file',file); data.append('sha256', sha256); data.append('api_key', 'key'); console.log(file); $.ajax({ url: '/report/ajax/upload_file/', data: data, processData: false, contentType: false, type: 'POST', success: function(data) { $('#sandboxMessage').text(data.res); $('#uploadResults').slideDown(300); }, error: function(data) { $('#customMessage').text('Sample upload failed'); $('#uploadResults').slideDown(300); }, }); }); } And the server side python code is def upload_file(request): sha256 = request.POST.get('sha256', None) api_key = request.POST.get('api_key', None) uploadFile = request.FILES['file'] headers = {'X-TOKEN-KEY': api_key} res = requests.put(url='https://redacted.com/v1-1/file/' + sha256, headers=headers, data=uploadFile) data = { 'sha256': sha256, … -
Django Rest Framework for network device configuration
I have a network device (switch) with a REST API. Now, I want to create a Django application that can access this API and configures the device. Does it make sense to use the Django Rest Framework for this application? -
How to resolve ERR_CONNECTION_REFUSED when connecting to virtualenv/django running on a server
I have installed virtualenv and Django in my user section on a ubuntu server. Everything appeared to install correctly and when I start the server with python manage.py runserver I get the following message, which seems correct: Performing system checks... System check identified no issues (0 silenced). You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. January 10, 2019 - 16:38:32 Django version 2.1.5, using settings 'form01.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. The problem is when I go to http://127.0.0.1:8000/ in my browser I get an ERR_CONNECTION_REFUSED instead of the Django install success page. I expect to see the Django successful install screen at http://127.0.0.1:8000 but instead get ERR_CONNECTION_REFUSED. -
Quickly get query set of objects related by Foreign key
Here are my models: class A(models.Model): #Some fields class B(models.Model): #Some fields class C(models.Model): a = models.ForeignKey(A) b = models.ForeignKey(B) #Some more fields class Meta: unique_together = ['a', 'b'] Now based on some object of A (say 'a') , I want set of all 'b' for which C.a = 'a' and C.b = 'b' Currently the way I am doing this is: set_c = C.objects.filter(a='a') set_b = [c.b for c in set_c] First of all this gives me a list (a queryset would be preferred). Second, I am concerned about line 2 having list comprehension , as it may take a lot of time for huge data. Is there a better way to achieve this? -
Foreign key feild with to_feild constraint gives duplicate keys error
I have a foreign key to another model with a to_field constraints with points to a field in the model, but when I try to run migrate it gives me this error: django.db.utils.IntegrityError: could not create unique index "disctest_respondent_least_disc_ce7da5e0_uniq" DETAIL: Key (least_disc)=(4,9,1,4,6) is duplicated. Here is the Model: class Combined(BaseRespondent): least_disc = models.ForeignKey(Respondent, to_field='least_disc', related_name="combined_least_disc", on_delete=models.CASCADE) most_disc = models.ForeignKey(Respondent, to_field='most_disc', related_name="combined_most_disc", on_delete=models.CASCADE) and here is the reference model to the foreign key class Respondent(BaseRespondent): least_disc = models.CharField(max_length=256, default='6,0,7,7,4' ,unique=True) most_disc = models.CharField(max_length=256, default='7,5,1,4,7', unique=True) most_personality = models.ForeignKey(Personality, on_delete=models.SET_NULL, null=True, related_name="most_personality") least_personality = models.ForeignKey(Personality, on_delete=models.SET_NULL, null=True, related_name="least_personality") here is also the error I get: django.db.utils.IntegrityError: could not create unique index "disctest_respondent_least_disc_ce7da5e0_uniq" DETAIL: Key (least_disc)=(4,9,1,4,6) is duplicated. How do I go about solving this issue? Thanks in advance for your prompt response. -
Query all database entries for the first day of the month
I am currently trying to use the Django query framework to query the first entry of each month from a database with lots of entries over many years. Is this somehow possible? Suppose I have a database with one entry per day (for some days there might not be an entry). What is an efficient way to query the first entry for each month (or each week) for each of the years. I hop you can help me. Thank you so much in advance! -
Migrate User Passwords from One DB to Another
I'm currently using mongoDB as my application DB and hashing passwords with bcrypt. I'm going to be moving over to a Django application as well as a PostgreSQL DB and will be transferring all my users over to that, and using Django's built in authentication system. I'm not sure how to handle the passwords, however. Is it possible to move users over without requiring all users to reset their passwords? -
django: how to define apps
when I try to define any app in django it always make django server stop (127.0.0.1:8000) and it show me error in cmd like this File "C:\Users\SELL\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 953, in _find_and_load_unlocked File "", line 219, in _call_with_frames_removed File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'homedjango' I just define app by going to setting.py and installed_apps [] and add 'myAppName.apps.MyAppNameConfig', is this right and if it why does server stop and show me errors thank you all. -
Cannot make Python 3.7 work in Ubuntu 18.04
I am learning Python and Django in Ubuntu 18.04 where both Python 3.6.7 and 3.7.2 is installed. Whenever Pyhon3 command is given its showing the prompt of 3.7, but when I use pipenv to create a virtual environment for a project it's still using /usr/bin/python3(Python3.6.7) and not of Python3.7.2. Even Python3.7.2 has been configured as default with highest priority of 2 by using the command: sudo update-alternatives --install /usr/binpython3 python3 /usr/bin /python3.6 1 sudo update-alternatives --install /usr/binpython3 python3 /usr/bin /python3.7 2 sudo update-alternatives --configure python3 and the above command shows the Python3.7 as the default by a "*" symbol, but still pipenv uses Python3.6.7. I want pipenv to use only Python3.7 and 3.6. Don't know what to do. Please help. -
Django form not submitting - problem with form tag
The signup page of my app is exhibiting unexpected behaviour. I'm using the standard django auth. After editing the html a bit, the form stopped submitting altogether. As in nothing would happen when I clicked submit. Similar behaviour to this chap, and this one, and this question. I've fixed it. For some reason, I needed to add an additional opening form tag. I have no idea why. This is what the html looks like now: <form method="POST"> <form method="POST"> {% csrf_token %} {{ form.non_field_errors }} {% bootstrap_form form %} <input type="submit" class='btn btn-primary' value="Sign Up"/> </form> Without the additional form tag at the top, it doesn't work. Can anyone explain what's going on here? I also noticed that in Atom, when I only have the one opening tag, the editor highlights the tag in orange - meaning it's being treated as an attribute not a tag. When I have both opening tags, one still gets highlighted as an attribute. Like I said, it's working now but I would prefer to rectify this if anyone in the community can help. -
Django version 2.1.4 - Exception Type: NoReverseMatch
I am doing Django blog v2.1.4 getting below error. django.urls.exceptions.NoReverseMatch: Reverse for 'login' not found. 'login' is not a valid view function or pattern name. NoReverseMatch at / Reverse for 'login' not found. 'login' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.1.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'login' not found. 'login' is not a valid view function or pattern name. Exception Location: C:\Users\khattab\Anaconda3\envs\myenv\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 622 Python Executable: C:\Users\khattab\Anaconda3\envs\myenv\python.exe Python Version: 3.7.1 Python Path: ['C:\Users\khattab\Desktop\blog_project\mysite', 'C:\Users\khattab\Anaconda3\envs\myenv\python37.zip', 'C:\Users\khattab\Anaconda3\envs\myenv\DLLs', 'C:\Users\khattab\Anaconda3\envs\myenv\lib', 'C:\Users\khattab\Anaconda3\envs\myenv', 'C:\Users\khattab\AppData\Roaming\Python\Python37\site-packages', 'C:\Users\khattab\Anaconda3\envs\myenv\lib\site-packages'] Server time: Thu, 10 Jan 2019 15:46:37 +0000 My URL path('accounts/login/', auth_views.LoginView.as_view()), Thank you -
How to add meta data in a csv using python?
I am trying to create a csv file to export user list. I want to add some meta data like the type of user, author and some other data that should not be displayed in excel sheet. Is it possible to add such meta datas in CSV. if possible can some one help me? -
Django annotate over a subquery
i'm struggling with an aggregation, what I'm trying to do is, to perform some sum over a subquery. Let's assume the following model: +------------------------+-----------+ | Column | Type | +------------------------+-----------+ | customer | fk | +------------------------+-----------+ | total | float | +------------------------+-----------+ | somefield | charfield | +------------------------+-----------+ | issued_on | date | +------------------------+-----------+ | validation_status_code | charfield | +------------------------+-----------+ the subquery is as follow: Invoice.objects.filter(customer_id=4).order_by('issued_on')[:48+1] This is only half of the invoices of a customer, the idea here is to obtain the aggregate over a period of time (this is the subquery). Suppose I want to get the Sum of total, the Sum of the total if the status is "error" and gruop by 'somefield', I've figured it out the SQL query (it's on mysql), I want to know if it's possible to do this via Django ORM. The query is the following: SELECT table1.somefield, SUM(table1.total) AS total_clean, SUM(CASE WHEN table1.validation_status_code = 'error' THEN table1.total ELSE NULL END) AS canceladas, (SUM(table1.total) - SUM(CASE WHEN table1.validation_status_code = 'error' THEN table1.total ELSE NULL END)) AS ventas FROM (SELECT invoice.id, invoice.customer_id, invoice.total, invoice.somefield, invoice.validation_status_code, invoice.issued_on, FROM invoice WHERE invoice.customer_id = 4 ORDER BY invoice.issued_on ASC LIMIT 49) AS table1 GROUP BY table1.somefield -
Django - ajax poll with results on the same page
I'm learning django and I need help with my app. In a page I have a poll: I want that after a user has voted, the poll form disappears and a div #ajaxresults appears with the updated votes for each option. I'm using an ajax call but I can't return the updated votes. If I call directly '/polls/4/results' I can see the right list but I can't include that block on the same page of the form. What am I missing? urls.py app_name = 'polls' urlpatterns = [ path('', views.index, name='list'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] view.py def results(request, question_id): question = get_object_or_404(Question, pk=question_id) #return render(request, 'polls/results.html', {'question': question}) return redirect(question.get_absolute_url()) @require_POST def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) selected_choice = question.choice_set.get(pk=request.POST['selectionId']) selected_choice.votes += 1 selected_choice.save() return render(request, 'polls/results.html', {'question': question}) detail template (extends base.html) <form id="quiz-module" action="#"> <input type="hidden" id="pollId" name="pollId" value="{{question.id}}"> {% csrf_token %} <fieldset> <h2>{{ question.question_text }}</h2> <ul> {% for choice in question.choice_set.all %} <li><input type="radio" name="opt" value="{{ choice.id }}" {% if forloop.first %}required {%endif%}/>{{ choice.choice_text }}</li> {% endfor %} </ul> </fieldset> </form> <section id="quiz-results"> <h3>Your vote</h3> <p id="ajaxresults"></p> <h3>All votes</h3> <dl> {%block updated_results %}{% endblock %} </dl> </section> template vote is … -
add placeholder in views.Login in Django
i use django.contrib.auth.views import Login but i want add css and placeholder to Login views i use python3 Urls : url(r'^login$' , LoginView.as_view(template_name='login.html'), name='Login' , kwargs={"authentication_form": LoginUser}), form : from django.contrib.auth.forms import AuthenticationForm from django.forms.widgets import PasswordInput, TextInput class LoginUser(AuthenticationForm): username = forms.CharField(widget=TextInput(attrs={'style':'font-size : 20px;color:white','placeholder': 'Username'})) password = forms.CharField(widget=PasswordInput(attrs={'placeholder':'Password' , 'style' : 'font-size : 20px;color:white'})) this code don't work i you can please help me -
Trying to post images from reactjs to django using DRF I get an empty queryset
Im trying to post an image from reactjs to my backend using Django Rest Framework but when i print request.data I get an empty querydict <QueryDict: {}>. This is how I post my image reactjs handleFormSubmission = () => { const {phoneNumber, avatar} = this.state; if(!phoneNumber && !avatar) console.log('something!!'); this.setState({ isLoading:false }) let data ={ phone_number:phoneNumber, avatar } let config = { headers:{ 'Content-Type': 'multipart/form-data', 'Accept': 'application/json' } } axios.put('/profile/change', this.state, config ).then(res=>{ this.setState({ isLoading:true }) }) } Then when console.log the image its converted to base64. I am also using multipart/form-data as part of my headers views.py def put(self, request): """ update user pf :param request: :return: """ current_user = Profile.objects.get(user=request.user.id) serializers = ProfileSerializers(current_user, request.data, partial=True) if serializers.is_valid(): serializers.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(status=status.HTTP_400_BAD_REQUEST) I think that my backend basically has no problem because when i post images using postman the images are saved successfully -
Python 3 and Django 2 faster to load or copy object for view?
I am curious as to the most performant way to get large objects into views for Django 2 In views.py I need to load a large object into memory. I have this both pickled as well as a json file. The pickled version is only a marginal improvement at 95% the size of the json version. While I would like to do this once when the serve starts, and then have a view have access to this module level variable, one of my views needs to modify the object to do what it is suppose to do. So if I load it once as a module level variable, (here named persistent), we see that sequential calls use the updated variable -- as expected: views.py ... persistent = {'val': 0} # loaded from pickled / json file def test(request, val): old = persistent['val'] # required information from unmodified object persistent['val'] = val # some computation which is required to modify the object return JsonResponse({'old': old, 'new': val}) ... urls.py ... urlpatterns = [ ..., path('test/<val>/', views.test, name='test') ,... ] api calls localhost:8000/test/10 ---> {'old': 0, 'new': 10} localhost:8000/test/100 ---> {'old': '10', 'new': 100} this is of course expected. However, for my … -
Django Multiselectfield allows to add any value which is not in choice list from shell, How to prevent that?
DEPARTMENT_CHOICE = ( ('BCT','Department Of Electronics and Computer Engineering'), ('BEL','Deparment Of Electrical Engineering'), ('BCE','Deparment Of Civil Engineering'), ('SHE','Deparment Of Science and Humanities'), ('BME','Deparment Of Mechanical Engineering'), ) department = models.CharField (max_length =10 ,choices = DEPARTMENT_CHOICE,blank=True,verbose_name="Department") But if we add eg ZZZ in department, it will be added in database but I want to prevent that. How can I do it to prevent add items which are not in choice tuple? -
Forbidden (CSRF cookie not set) csrf_exempt
I'm returning with a 403 Forbidden (CSRF Cookie not set) error on a CBV with csrf_exempt being called on dispatch either via the csrf_exempt decorator or using CsrfExemptMixin from django-braces. Not quite sure why as other views using CsrfExemptMixin works fine class CaseDeletedView(CsrfExemptMixin, View): def post(self, request, *args, **kwargs): ... return HttpResponse(status=204) With decorator class CaseDeletedView(CsrfExemptMixin, View): def post(self, request, *args, **kwargs): ... return HttpResponse(status=204) @method_decorator(csrf_exempt) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) -
Django widget that depends on model
I am pretty new to django and have a question. I got a ModelForm using Widgets. Since I have a field called discount which I only want to be editable if the displayed model fullfills some requirements, I make it read-only using a widget entry: class Meta: widgets = {'discount': forms.TextInput(attrs={'readonly': True})} Now I want to make it possible to write to this field again, iff the Model (here called Order) has its field type set to integer value 0. I tried to do so in the html template but failed. So my next idea is to make the widget somehow dependent to the model it displays, so in kinda pseudocode: class Meta: widgets = {'discount': forms.TextInput(attrs={'readonly': currentModel.type == 0})} Is there a proper way to do something like this? Thanks in advance -
django emoji with mysql, charset settings
First: DATABASES = { 'default': { 'ENGINE': "django.db.backends.mysql", 'NAME': '<DB_name>', 'USER': '<user_name>', 'PASSWORD': '<password>', 'HOST': '<DB_host>', 'PORT': '3306', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", 'charset': 'utf8mb4', 'use_unicode': True, }, } } Second: DATABASES = { 'default': { 'ENGINE': "django.db.backends.mysql", 'NAME': '<DB_name>', 'USER': '<user_name>', 'PASSWORD': '<password>', 'HOST': '<DB_host>', 'PORT': '3306', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" } } } I found a website that explain First one to use emoji on django application. But I also found that Second one is also working well through using emoji. Which one is correct or good enough for production django application? Which is considerable for production? My database: AWS RDS MySQL 5.7.19 -
Django template translation not working as expected
I am using django 2.1 , here is all the settings related to translation: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', ] LANGUAGE_CODE = 'en' LANGUAGES = ( ('en', _('English')), ('bn', _('Bengali')) ) LOCALE_PATH = ( os.path.join(BASE_DIR, 'locale') ) TIME_ZONE = 'Asia/Dhaka' USE_I18N = True USE_L10N = True USE_TZ = False Template tag that I want to translate: {% load i18n %} <div class="widget widget-about"> <h4 class="widget-title">{% trans "About Us" %}</h4> </div I run both ./manage.py makemessages --all ./manage.py compilemessages commands , also added translation in .po file after makemessages command: # locale/bn/LC_MESSAGES/django.po #: templates/partials/footer.html:8 msgid "About Us" msgstr "আমাদের সম্পর্কে" When I changed the language code from en to bn, template string still rendering the default english "About Us". Here are all the codes that I am using for changing language: <div class="header-dropdown"> {% get_current_language as LANGUAGE_CODE %} {% if LANGUAGE_CODE == 'en' %} <a href="#"><img src="{% static 'image/flag/en.png' %}" alt="flag">ENGLISH</a> {% else %} <a href="#"><img src="{% static 'image/flag/bn.png' %}" alt="flag">বাংলা</a> {% endif %} <div class="header-menu"> <ul> <li><a href="{% url 'change_language' %}?lan=en"><img src="{% static 'image/flag/en.png' %}" alt="USA Flag">ENGLISH</a></li> <li><a href="{% url 'change_language' %}?lan=bn"><img src="{% static 'image/flag/bn.png' %}" alt="Bangladesh Flag">বাংলা</a></li> </ul> </div><!-- End .header-menu …