Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to group by with left function (sql) on django?
I have a table with a column that has the period in this format: vcPeriodo 201801 201801 201802 201802 201802 Model: class Trapptoinflacion(models.Model): vcperiodo = models.CharField(db_column='vcPeriodo', primary_key=True, max_length=6) So what i want to do is one of this query sql to django: SELECT LEFT(vcPeriodo,4) Anio FROM dbo.traPptoInflacion GROUP BY LEFT(vcPeriodo,4) SELECT DISTINCT LEFT(vcPeriodo,4) Anio FROM dbo.traPptoInflacion Right now i have this: Trapptoinflacion.objects.values(anio =Substr('vcperiodo', 1, 4)) -
Redirect to previous page after login in view.py : Django 2
I build a signup and login page and I want that user after has been signed up or logged in redirect to the page that was been. this is my views.py : def signup(request): if request.method == 'POST': try: try: user = User.objects.get(username=request.POST['username']) return render(request, 'accounts/SignUp.html', {'error': 'This UserName Has Already Exist, Pleas Try Another UserName.'}) except: user = User.objects.get(email=request.POST['email']) return render(request, 'accounts/SignUp.html', {'error': 'This Email Has Already Registered, Pleas Try Another Email.'}) except User.DoesNotExist: user = User.objects.create_user(username=request.POST['username'], email=request.POST['email'], password=request.POST['pass'], first_name=request.POST['fname'], last_name=request.POST['lname']) auth.login(request, user) return render(request, 'StartPage/StartPage.html', {'error': 'Conjurations! You have Signed Up ' 'Successfully.'}) else: return render(request, 'accounts/SignUp.html') now how can I make redirect to the page that user has been before clicked for signup? In addition, I'm sorry for writing mistakes in my question. -
IOT dashboard using Django
I'd like to create an IOT dashboard for some weather data and pump controls using a Django based website. The current system architecture is: ESP8266 <--> Mosquitto MQTT server <--> Node-Red Dashboard I'd like to replace the Node-red dashboard with some more customizable website. Therefore I'd like to use the Django framework. The communication beween ESP8266 and Mosquitto is json based. Requirements: - connection to MQTT server - reading and writing MQTT messages - logging of MQTT data - display the data in some kind of "dashobard" format in a website for office and mobile usage. - local installation on Raspberry Pi (where also the Mosquitto server runs) Is Django the right framework for this project? How can I start with this project? Which additional toolboxes / frameworks do I need to establish these features? Can you suggest other(better) tools/applications/frameworks to fulfil my requirements? I know this is a similar question to this, but it was not really helpful for me. -
Using Grid Layout or Flex Layout for Amp-Only Page (Production)?
If I'm making a Django backed up website with amp-only pages then what should I use, Flex or Grid Layout. I will cover the js part with js available by ampproject, but what about the layout functionality, will I be able to cover up most of the functionality by using grid or flex. -
'Python 'SyntaxError: 'return' outside function
from django.shortcuts import render from . import forms # Create your views here. def index(request): return render(request,'basicapp/index.html') def form_name_view(request): form = forms.FormName() if request.method =='POST': form =forms.FormName(request.POST) if form.is_valid(): # do smth code print("VALIDATION SUCCESS!") print("NAME: "+form.cleaned_data['name']) print("EMAIL: "+form.cleaned_data['email']) print("TEXT: "+form.cleaned_data['text']) return render(request,'basicapp/form_page.html',{'form':form}) -
how to revise field_to_native in Django/Rest FrameWork
Recently, I am moved a django app from Django 1.4 to Django 1.11. I met a problem about field_to_native. I appreciate very much for any hints. The original code: class LoopgroupDqHyperlinkedIdentityField(relations.HyperlinkedIdentityField): def field_to_native(self, obj, field_name): # copied from superclass request = self.context.get('request', None) format = self.format or self.context.get('format', None) view_name = self.view_name or self.parent.opts.view_name # new lgdq_attrs = 'loopgroup_id', 'year', 'month' view_kwargs = dict((X, getattr(obj, X)) for X in lgdq_attrs) return RF_reverse(view_name, kwargs=view_kwargs, request=request, format=format) class LoopgroupDqSerializer(HyperlinkedModelSerializer): url = LoopgroupDqHyperlinkedIdentityField() class Meta: model = LoopgroupDq fields = tuple(X.name for X in LoopgroupDq._meta.fields) + ('url',) The system returns the following error File "/srv/projects/python/dotfreewaydata/dataquality/serializers.py", line 43, in LoopgroupDqSerializer url = LoopgroupDqHyperlinkedIdentityField() File "/srv/virtual_environments/dotfreewaydata/local/lib/python2.7/site-packages/rest_framework/relations.py", line 408, in init assert view_name is not None, 'The view_name argument is required.' AssertionError: The view_name argument is required. I google this error message and found that field_to_native has been deprecated in Django Rest Framework 3.0. In http://www.django-rest-framework.org/topics/3.0-announcement/ They mentioned 1)The field_from_native() and field_to_native() methods are removed. 2)Now if you need to access the entire object you'll instead need to override one or both of the following: Use get_attribute to modify the attribute value passed to to_representation(). Use get_value to modify the data value passed to_internal_value(). The website … -
django create row on user creation
class Student(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) dob = models.DateField(blank=True, null=True) student_rank = models.OneToOneField( StudentRankSignoff, on_delete=models.CASCADE, null=True) def __str__(self): return self.user.username` When a Student signs up, i want to have the StudentRankSignoff table contain a blank row. How do I go about doing this? -
Django - Can I view R Dataframe in Django?
This is my piece of code : filterdataahp = pd.DataFrame(list(Bowlers.objects.all().values('ave','econ','matches','totalovers','sr','wkts'))) return HttpResponse(filterdataahp.to_html()) r_dataframeahp = pandas2ri.py2ri(filterdataahp) I want to display this r_dataframe in webpage same like I did with pandas. Can I do that? Or is there any other way to view the contents in variable 'r_dataframe' -
django circular import solutions
Please help me. There is a Django project with cycural import. Project's applications are connected only one side. But there is functions that use other model without params (for using in tempalte) and it make impossible to move the function. And i was find two solutions First way is import model inside function. And another way move two models in one file. Both solutions work without problem but, which one is better class InitialArticle(models.Model): by = models.ForeignKey(get_user_model(), null=True, on_delete = models.SET_NULL) category = models.ForeignKey(ArticleCategory, null=True, on_delete=models.CASCADE) keywords = models.CharField(max_length = 110, unique = True) def get_articles_of_initialarticle(self): from article.models import Article return Article.objects.filter(initial = self) Please help find better way. Maybe there is another solution? Thanks a lot -
Stop Celery from importing views.py
Sorry if it is trivial - new to Django and especially Celery. So, I have a Python interface to some instrument i am trying to control with a Django based Web-Application. I generate an instance of the interface-class in my views.py of the single app i have in my django project. At this point i would like to use Celery - which i have managed to set up. However, it appears that Celery is importing views.py for each workers it generates which means that each worker in Celery has its own instance of the interface-object - which causes tremendous problems. I tested this, because when i remove importing the interface module in views.py, the workers no longer generate their instances of the interface. I have checked for circular imports - could not find any. I am also not running autodiscover_tasks so i see no reason why Celery would import views.py upon generating a worker. Also, my celery tasks do not interact with the interface-object in any way shape or form. I would like to prevent Celery importing views.py for the workers, because it is not needed and it breaks my code. Is it at all possible - and why does … -
Uploading multiple files from a list in Django
I am working on an app where users can upload files. They need to be able to either upload a file one by one, or upload an Excel file that, among other things, contains a list of paths to files to be uploaded. I am currently stuck on the second part. I am able to compile a list of the paths just fine, but I am not sure how to access those files on the user's computer so they can be processed and uploaded. -
create and save object IntegrityError django
I'm getting an object from a json response and I want to use create method on it so I can save it in the database. response = requests.get( settings.BASE_URL, headers=headers, params=payload, ) user_info = response.json() example_model = ExampleModel.objects.create(api_key=user_info.get('id')) example_model.save() the model is: class ExampleModel(models.Model): """ """ user = models.OneToOneField(User) example_id = models.CharField(max_length=225, blank=True, null=True) api_key = models.CharField(max_length=225, blank=True, null=True, validators=[validate_klean_token_syntax]) Follow up is that I'm receiving Exception Type: IntegrityError at /user-information/ Exception Value: (1048, "Column 'user_id' cannot be null") Can someone please help me understand why am I getting this error, thanks. -
uWSGI spooler cannot import my application
I have a django application with following simplified structure: in_web_server/ ├── in_web_server/ │ ├── __init__.py │ └── wsgi.py ├── in_web_app/ | ├── __init__.py | └── views/ | └── ... └── manage.py Here is wsgi.py content: from django.core.wsgi import get_wsgi_application application = get_wsgi_application() And here in_web_server/__init__.py: from uwsgi_tasks import set_uwsgi_callbacks set_uwsgi_callbacks() The application is runing within docker container with following uwsgi.ini file: [uwsgi] http = 0.0.0.0:8000 # Django-related settings # the base directory (full path) chdir = /app # Django's wsgi file module = in_web_server.wsgi:application static-map = /static=/app/static # process-related settings # master master = true # maximum number of worker processes processes = 10 # clear environment on exit vacuum = true # spooler setup spooler = /spooler spooler-processes = 2 spooler-frequency = 10 I'm trying to run asynchronous function using the uWSGI spooler. The problem is that when the function is invoked, I get following exception: Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/uwsgi_tasks/tasks.py", line 70, in manage_spool_request return task.execute_now() File "/usr/local/lib/python3.7/site-packages/uwsgi_tasks/tasks.py", line 361, in execute_now result = super(SpoolerTask, self).execute_now() File "/usr/local/lib/python3.7/site-packages/uwsgi_tasks/tasks.py", line 218, in execute_now setattr(self.function, self.attr_name, self) File "/usr/local/lib/python3.7/site-packages/uwsgi_tasks/tasks.py", line 209, in function self._function = load_function(self.function_name) File "/usr/local/lib/python3.7/site-packages/uwsgi_tasks/tasks.py", line 62, in load_function return import_by_path(func_name) File "/usr/local/lib/python3.7/site-packages/uwsgi_tasks/utils.py", line 25, … -
Redhat Apache test page shows instead of app, tcpdump+wget return nothing
I have an app on EC2 that I start up by ssh'ing into the VM, activating the env and then running manage.py runserver. The Django app starts without any errors on 127.0.0.1:8000. The server files within /etc/httpd were migrated from an Apache 2.2 setup, using instructions from the official Redhat migration instructions. From within the VM, I send a request to the same address using wget http://127.0.0.1:8000. The response was: --2018-08-06 15:30:16-- http://127.0.0.1:8000/ Connecting to 127.0.0.1:8000... connected. HTTP request sent, awaiting response... Next, I took a tcpdump using very verbose and zero snapshots and all it produced Got 0 responses. When I navigate to the ip address either on the https or http it only shows me the Redhat Enterprise Linux Test Page. The apache configuration file is copied below. I have configured my VHOSTS in a separate file. Could this all be due a permissions issue? Do I need to provide some sort of permissions on the /etc/httpd and /var/www/app folders as defined in the configuration file? ServerTokens OS ServerRoot "/etc/httpd" PidFile run/httpd.pid Timeout 60 KeepAlive Off MaxKeepAliveRequests 100 KeepAliveTimeout 5 Include conf.modules.d/*.conf <IfModule prefork.c> StartServers 8 MinSpareServers 5 MaxSpareServers 20 ServerLimit 256 MaxRequestWorkers 256 MaxConnectionsPerChild 4000 </IfModule> <IfModule … -
Difference to declare variable in class or via dispatch method?
class PermissionMixin: user = None # Variant 1 def dispatch(self, request, *args, **kwargs): self.user = None # Variant 2 # ... some other code class SampleClass(PermissionMixin): # ... some other code Is there a difference if I declare a variable directly in the class or in a method via self? -
How should I store a list of two different types of IDs
I'm trying to store a list of model ID's to keep an ordered list. Both models are just variations, one designated to store more information. The model IDs come in int and of course there are overlaps, so I need to be able to differentiate the two within the list. The approach I was originally going with is just to change the types so I can do a for loop and check the type: [TypeA_ID, TypeA_ID, [TypeB_ID], TypeA_ID] But I'm reading how type checking is a pretty bad idea, and was wondering if there is a better approach. -
Django 2 form in modal
Im tries to open in Django the user edit form in Bootstrap modal. But the form is empty, only the save button is shown. But I don't understand how I can make the connection. If I call the edit page directly, then I can edit the user 127.0.0.1:8000/account/edit/ index.html, includes the referral to the form {% extends 'base.html' %} {% block head %} {% endblock %} {% block body %} <div class="container-fluid"> <div class="row"> <div class="col-sm-12 col-md-6"> <div class="panel panel-default"> <div class="panel-body"> {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} <form action="{% url 'account:edit_profile' %}"> <input type="submit" value="Edit" /> </form> <form action="{% url 'account:change_password' %}"> <input type="submit" value="Change Login" /> </form> <br> <a href="#" role="button" data-toggle="modal" data-target="#edit-profile-modal">Open Modal</a> <br> <div class="control-label col-sm-2"> First name: </div> <div class="col-sm-2"> {{ user.first_name }} </div><br> <div class="control-label col-sm-2"> Last name: </div> <div class="col-sm-2"> {{ user.last_name }} </div><br> <div class="control-label col-sm-2"> Email: </div> <div class="col-sm-2"> {{ user.email }} </div> </div> </div> </div> </div> </div> <div class="modal fade" id="edit-profile-modal" > <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header" align="center"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span class="glyphicon glyphicon-remove" aria-hidden="true"></span> </button> </div> <div id="div-forms"> {% include "account/edit_profile.html" with form=form %} </div> </div> </div> </div> {% endblock %} edit_profile.html … -
Container with the django channels is not reloaded after change a code
I start began to understand with django-channels and an error occurred.M My project is run across the docker-compose and after chenge code, container not reloaded for accept changes. Is it possible to specify a reload = true how in the gunicorn? I set volumes for project, but not is reload after changes in code: - ./main:/data/app:rw Any idea? -
Wagtail: Creating a custom API endpoint
I've created a Snippet called "Spotlights," and I'm wondering how I can create a custom endpoint for Snippet data with the Wagtail API. My best guess would be: api_router.register_endpoint('Spotlights', BaseAPIEndpoint) Is the first arg there establishing the name of the endpoint, or referencing something? -
Django show a message until user takes an action upon the message
I would like to display a dashboard notification in the view until user prefers to close it. It should stay there every time the user logs in. But if he clicks the close button on the notification, then the notification shouldn't be shown thereafter. How to implement this in django using messages? Is there any other way? -
Using redirect sends me to /tag/?search=input instead of /tag/input (Django URL argument from form)
I have a page where there is a path /tag/name_of_tag and you can see all posts tagged with that tag. Inside the page, you can also select another tag in a form and go to that tag. The problem is that instead of going to /tag/searched_tag, it goes to /tag/?search=searched_tag How can I change it doesn't leave the ?search= part? urls.py: url(r'tag/(?P<input_tag>\w+)$', views.tag_view, name='tag'), views.py: def tag_view(request, input_tag): form = TagSearchForm() if request.method == 'GET': form = TagSearchForm(request.GET) if form.is_valid(): input = form.cleaned_data['search'] print(input) return redirect('fortykwords:tag_view', input) else: form = SearchForm() latest_post_list = Post.objects.filter(tags=input_tag, status__exact="published") paginator = Paginator(latest_post_list, 3) page = request.GET.get('page') posts = paginator.get_page(page) context = {'latest_post_list': latest_post_list, 'page_tag': input_tag, 'form': form} return render(request, 'fortykwords/tag.html', context) forms.py: class TagSearchForm(forms.Form): search = tagulous.forms.SingleTagField( tag_options=tagulous.models.TagOptions( autocomplete_view='fortykwords:post_tags_autocomplete' ), label='Tags', required=True, help_text=_('Filter by lead tags. You can organize leads by any tag you want.'), ) tag.html: {% extends "base_generic.html" %} {% block content %} <form action="." method="get"> {{ form }} <input type="submit" value="Submit" /> </form> <h3>Posts with the tag {{ page_tag }}</h3> {% if latest_post_list %} <ul> {% for post in latest_post_list %} <li> {{ post.author }} {{ post.pub_date }} <br> <a href="{% url 'fortykwords:detail' post.id %}">{{ post.title }}</a></li> {% for tag in … -
What does django admin add_view here do?
I fount the document about admin.add_view is quite ambiguous. What does it do and what does it return? I read code and met one function like this: def crudmatic(request, themodel, url, goto_on_save=None, admin=None): """ GET: presents an admin form but outside of the admin application. POST: validates, saves and relocates or if there are errors then it presents the form again Returns: an HTTP response using the admin options defined and registered for the admin site for this model. optionally you may supply an Admin Usage: # in your view: return crudmatic(request,YourModelClass,url) crud = create replace update delete this does create only. it was intended to support all stages. see editmatic """ if not admin: try: admin = site._registry[themodel] except KeyError: admin = DefaultAdmin(themodel, site) else: admin = admin(themodel, site) # some breakage in django # there is supposed to be a root path set, # but I'm not running an admin site here # if hasattr(admin,'admin_site'): admin.admin_site.root_path = "/admin/" return admin.add_view(request, url) -
Django - how to submit multiple forms
I have a page with 5 different 'tabs' (implemented using "Materialize CSS"). Each tab has its own form (I have 5 different forms, I guess it's not a good idea to have one form for all the different tabsa). What I want to do is, when I click "submit" button, all the forms/tabs that are filled out should be submitted (and all the empty ones should not do anything). Any suggestions how should I implement this? Thanks! -
First time working with Foreign Key leads to Error
Hey there I'm new to Django trying to work with a Foreign Key in my models.py: from django.db import models from django import forms from django.contrib.contenttypes.fields import GenericForeignKey import datetime # Create your models here. CITIES = (('item_1', 'Standort 01'), ('item_2', 'Standort 02'), ('item_3', 'Standort 03'), ('item_4', 'Standort 04'), ) class Teacher(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Student(models.Model): name = models.CharField(max_length=255) standort = models.CharField(max_length=30, choices=CITIES, default='item_1') teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) start = models.DateField() birthday = models.DateField() def __str__(self): return self.name which led me to this Error: line 947, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: '---' After trying to figuring out about some time what my mistake could have been, I'm hoping if someone here can help me out? -
Python Selenium use arg string for variable name and return variable
I’m trying to test that focused element is correct as you TAB through a form. Since I want to then input text into the box, I am trying to save some of the work by finding the element a second time. If that’s confusing, hopefully the code below will help. def active_element_is_correct(self, element_id): active_element = self.browser.switch_to.active_element desired_element = self.browser.find_element_by_id(element_id) self.assertEqual(active_element, desired_element) return desired_element self.active_element_is_correct(‘first_name’) # should return first_name_element first_name_element.send_keys(‘My First Name’)