Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
extending abstract model in Django
I'm using Django 2.x and OAuth Toolkit. I'm writing an application where I need to add ForeignKey pointing to Application model of OAuth Toolkit plugin, which is defined Abstract. According to the documentation. I can extend the ** AbstractApplication** and then add in settings OAUTH2_PROVIDER_APPLICATION_MODEL='your_app_name.MyApplication' In my case, I have created my app and in models.py class CustomOAuthToolkitApplication(AbstractApplication): pass class OAuthToolkitTrackingLog(models.Model): application_model = settings.OAUTH2_PROVIDER_APPLICATION_MODEL application = models.ForeignKey(application_model, on_delete=models.CASCADE, blank=True, default=None, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, default=None) col_1 = models.CharField(max_length=255) created = models.DateTimeField(auto_now_add=True) and in settings.py INSTALLED_APPS = [ ... 'oauth2_provider', 'my_app', 'django_oauth_toolkit_tracking', ] OAUTH2_PROVIDER_APPLICATION_MODEL = 'my_app.CustomOAuthToolkitApplication' But when I run command to generate migration python manage.py makemigrations It gives error as The field oauth2_provider.Grant.application was declared with a lazy reference to 'my_app.customoauthtoolkitapplication', but app 'my_app' isn't installed. The field oauth2_provider.RefreshToken.application was declared with a lazy reference to 'my_app.customoauthtoolkitapplication', but app 'my_app' isn't installed. How can I fix this issue? -
Calling a view from template works for "a" tag, but not for form button
I have the following in my Django template: <form action="{% url 'explorer_api:authorize' %}" method="POST"> <input id="submit" type="button" value="Click" /> </form> <a href = "{% url 'explorer_api:authorize' %}">Authorize</a> Why does clicking on the form button will not do anything, but clicking on the a element will work fine and call the desired view? -
django app not being served on digitalocean droplet
I'm following this tutorial online https://simpleisbetterthancomplex.com/tutorial/2016/10/14/how-to-deploy-to-digital-ocean.html I get to an intermediary step where I want to check if I can access the app on the IP address. I run python manage.py runserver 0.0.0.0:8000 which returns the following: System check identified no issues (0 silenced). November 22, 2018 - 17:41:08 Django version 2.1.3, using settings 'mysite.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. So no errors. Then I navigate to :8000 and I get a timeout. "took to long to respond." Any idea what's going on here? -
How to update Django file from local machine to Ubuntu server(AWS EC2)?
I am developing an app in my local machine(windows OS) and I am using an AWS Ubuntu Server to deploy the code over there. But my problem is that when i am uploading python file through FileZilla Sftp its not make any change on the production server till I reboot production server using "sudo reboot" I am tired of doing this process again and again. I read about git version control can help me with this situation but I don't know how to do it. Please help me I am stuck from 3 days on this. -
Regex with list Comprehension
Sorry if this is not abiding by normal rules. I'm looking for confirmation on if what I'm doing seems like the best way and if not what would best. I'll try to explain as best as I can. I have a database with "definitions" each definition holds a list of "events", these events have a "highlighted" field which stores a regex string. Text files are uploaded to the server which have "sections". Each section is found with a regex string using finditer. I sort the results of the finditer into a list of dicts .groupdict with a list comp. The result of the groupdict is a "title" and "body" of the section. the loop through them. Each iteration in this loop uses splitlines on the section body. sect_re = re.compile(r'\*(?P<title>[^*]+)\*\s\*+\s+(?P<body>(?:.+\s+(?!\*+\n))+.+)', re.MULTILINE) re_results = re.finditer(sect_re, file_field) sections = [sect.groupdict() for sect in re_results] definitions = Definition.objects.all() for section in sections: title = section['title'] body_list = section['body'].splitlines() I then loop through all the definitions, get a the list of events in the definition then loop through those. for d in definitions: events = d.event_set.all() for e in events: in the events loop I compile the stored regex string from the event get … -
Add Dynamic field to DjangoAdmin Model
I have extended the delivered ModelAdmin class on Django, and I am trying to add an image preview property, when my model has this type of field. I was able to get as far as identifying when this happens, but I am failing when I try to add a dynamic property. Here is my class: class RTFAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): for x in obj._meta.get_fields(): if type(x) == models.ImageField: y = mark_safe('<img src="%s" width=400px></img>' % getattr(obj,x.name).url) RTFAdmin.picture = property(lambda self: y) self.readonly_fields = ('picture',) form = super(RTFAdmin, self).get_form(request, obj, **kwargs) return form But then, it fails with: 'SafeText' object is not callable If I define a property like this (code below), it works, but I dont want to define it manually for my models. class MyAdmin(admin.ModelAdmin): model=Ponto readonly_fields=('see_pic',) def see_pic(self, obj): return mark_safe('<img src="%s" width=400px></img>' % obj.pic.url) Any idea on where the problem is? -
Django Advanced Tutorial: Error when trying run server or migrate app after successfully installing own package
I'm following the Advanced Django Tutorial and have managed to package my polls app into another directory outside of mysite directory. I run pip install --user django-polls/dist/django-polls-0.1.tar.gz inside the directory which my django-polls app is at and manage to successfully install it. However, when I try to run python manage.py runserver inside the mysite directory I get the following message on my terminal: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/*USER*/django/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/*USER*/django/django/core/management/__init__.py", line 357, in execute django.setup() File "/Users/*USER*/django/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/*USER*/django/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/Users/*USER*/django/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/Users/*USER*/anaconda3/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'polls.apps' I tried running python manage.py migrate and get the same message. Could someone explain what's happening here? I'm running the latest version of Django. Thanks in advance for your time. -
Problems with CORS in Django
I'm trying to enable CORS in my app (React is front-end and Django is server). I have included this lines: INSTALLED_APPS = [ . . 'corsheaders' . . ] and this MIDDLEWARE = [ . . 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', . . ] Also have added CORS_ORIGIN_ALLOW_ALL = True But it still doesn't work. Access to fetch at 'http://localhost:8000/mentor_list' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. What is wrong? -
Delete a django application
I have an app in my django project that I'd rather do away with. I have removed all models and removed all reference to the app from all other apps but if when I remove the app from my settings.INSTALLED_APPS I get the below error. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000028F0C408C80> Traceback (most recent call last): File "C:\Users\Chidimmo\.virtualenvs\funnshopp-Ze7zokAC\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Chidimmo\.virtualenvs\funnshopp-Ze7zokAC\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check_migrations() File "C:\Users\Chidimmo\.virtualenvs\funnshopp-Ze7zokAC\lib\site-packages\django\core\management\base.py", line 442, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\Chidimmo\.virtualenvs\funnshopp-Ze7zokAC\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\Chidimmo\.virtualenvs\funnshopp-Ze7zokAC\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\Users\Chidimmo\.virtualenvs\funnshopp-Ze7zokAC\lib\site-packages\django\db\migrations\loader.py", line 226, in build_graph self.add_external_dependencies(key, migration) File "C:\Users\Chidimmo\.virtualenvs\funnshopp-Ze7zokAC\lib\site-packages\django\db\migrations\loader.py", line 191, in add_external_dependencies parent = self.check_key(parent, key[0]) File "C:\Users\Chidimmo\.virtualenvs\funnshopp-Ze7zokAC\lib\site-packages\django\db\migrations\loader.py", line 174, in check_key raise ValueError("Dependency on unknown app: %s" % key[0]) ValueError: Dependency on unknown app: service I want to remove every reference to that app from the database as well as removing it from settings.INSTALLED_APPS. I performed a search of django docs but couldn't find anything to that effect. All previous solutions I found here on SO relied on sqlclear which is no longer supported by django. How should I go about it? I'm using Django==2.1.3 -
Saleor Product Bulk upload script
I am new to saleor and is creating a ecommerce platform. I have downloaded saleor and made it up and running. I have 1000+ products to add. To add manually is a big nightmare. Checking if there is any scripts or ways to bulk upload products along with details (like images etc) to the saleor -
TypeError: post() missing 1 required positional argument: 'self' [duplicate]
This question already has an answer here: How can I decorate an instance method with a decorator class? 3 answers So I'm trying to create a proxy decorator that you pass in a helper so I can use it across multiple django views. So proxying is working fine but if I don't want it to proxy and run the view I get a traceback: TypeError: post() missing 1 required positional argument: 'self'. class HttpLocalProxy(object): def proxy(self, *args): if self.proxy_helper.should_proxy(self._get_request_object(*args)): <do proxy stuff> return self.fn(request=*args) def __init__(self, proxy_helper: ProxyInterface) -> None: self.proxy_helper: ProxyInterface = proxy_helper def __call__(self, fn) -> typing.Callable: self.fn: typing.Callable = fn return self.proxy I decorate the django view. class MyView(rest_framework.views.APIView): @iaw_api.helpers.local_proxy.HttpLocalProxy(monitor.helpers.local_proxy.MonitorProxyHelper(django.conf.settings.API_MONITOR_PROXY)) def post(self, request): <rest of code> This is because I don't have an instance of the class to run the post. I tested the theory and I can create an instance and pass it with the args back but it won't always be the same view class so I need to pass it in. I can't create an instance of itself as a class variable and pass it in with the helper so I'm stuck. I've got a feeling there may be a simple solution but I … -
Dropdown Menu in a Django-Tables2 cell
I have a table generated by Django-tables2 which all works fine. The first column is formatted as a button which removes the current line from the table. However I now want to have other functions such as copy etc. I could simply add a new button for each possible function but then I'd end up with a table of buttons and no room for data. So I would like to replace the first button with a dropdown menu of the various functions. It seems fairly straightforward to add the menu header, but I can't work out how or where to add my unordered list for the menu items. Has anyone tried to do this or does anyone know if this is even possible? Code for my button as cell. class TaskTable(ColumnShiftTable): remove = tables.LinkColumn('tasks:deletetask', args=[A('pk')], text='Delete', orderable=False, empty_values=(), attrs={'th':{'class': 'nocolor'},'a':{'class':'btn btn-danger'}}) Code changed to be a menu option class TaskTable(ColumnShiftTable): menu = tables.LinkColumn(text='Options', attrs={'th':{'class': 'nocolor'},'a':{'href':'#','class':'dropdown-toggle','data-toggle':'dropdown'}}) How do I expand the second lot of code above to incorporate my menu items list. -
Django, form.save(), doesn't save on the admin page.
I don't know why the variables from the register form doesn't store in django admin page! I'm confused. Thank you for read this, I really appreciate this. :) //htmlsnippet.html {% block content %} <h1>Sign up</h1> <form class ="site-form" action="register/" method="post"> {% csrf_token %} {{form}} <input type="submit" value="Signup"> </form> {% endblock %} //home.html {% extends "register/header.html" %} {% block content %} {% include "register/includes/htmlsnippet.html" %} {% endblock %} //views.py from django.shortcuts import render,redirect from django.http import HttpResponse from django.contrib.auth.forms import UserCreationForm # Create your views here. def index(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect("/personal") else: form = UserCreationForm() return render(request, 'register/home.html',{'form':form}) -
How to use restored schema in postgres for a multi tenant djangon application?
I got the database (postgres) dump from production and restored on development of a multi tenant django application. I created a new database and edited settings. But when every time I run the application on dev, I am getting below error. Case is same for every migration command (e.g. makemigrations, migrate, migrate_schema etc.) "python manage.py <<....>>". django.db.utils.ProgrammingError: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... Can anyone help how I can use restored data on development server? -
Is there a way to debug javascript files in a Django project using VS code?
I have a django project that uses some React apps (via bundling from Webpack) besides the usual javascript files. I would like to debug these javascript files (both type of them) inside Visual Studio Code (without using DevTools F12 from the browser). There are some sites that explain how to debug javascript files using the Debugger for Chrome extension, but I could not find anywhere how to set this for a django project. I have followed the steps indicated in Cannot debug in VSCode by attaching to Chrome, but instead of running serve -p 8080, I run python manage.py runserver (by default it runs in port 8000). Then, I have added the following launch option: { "version": "0.2.0", "configurations": [ { "type": "chrome", "request": "launch", "name": "Launch Chrome against localhost", "url": "http://localhost:8000", "webRoot": "${workspaceRoot}" } } However, when I launch it, it does not catch any breakpoint set in the javascript files. PS: ${workspaceRoot} points to the root of my django structure. -
Add a column from another object to an existing listview
I have an existing listview and I want to add a new column(contactDate) from another object which will be soratble. my objects are: class Left(models.Model): ref = models.CharField(max_length=16, blank=True) customer = models.CharField(max_length=100, blank=True) days = models.PositiveIntegerField(blank=True, null=True) business_classification = models.CharField(max_length=15, blank=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __unicode__(self): return u'%s in %s (%d days)' % ( self.customer, self.days_in_delay ) class Action(models.Model): left = models.ForeignKey(Left, related_name='actions') personal_use = models.ForeignKey(User, related_name='actions') phone_calls = models.BooleanField(default=False) next_contact_date = models.DateTimeField(blank=True, null=True) description = models.CharField(max_length=100) def __unicode__(self): return self.description As a newbie in python I haven't found a good example till now that fits my solution. Any orientation is well-appreciated. -
Django Rest Framework how to post date field
I want to post JSON request with field date: { "date":"2015-02-11T00:00:00.000Z" } It's the string is automatically converted from Datetime object and I don't want to crop the part T00:00:00.000Z manually at frontend. But if I post such request, Django Rest Framework validator of DateField will say me, that date has invalid format. What is the right way to solve this problem? -
not getting results in django search
I created a simple django blog where i want to provide a search option. so , I tried and didnt even get any error. but the problem is I didn't even get any search results too. its showing empty page even if there is a post related to that query. help me out guys. Here my code goes...... views.py class home_view(ListView): model = home_blog_model template_name = "home.html" context_object_name = "posts" paginate_by = 8 ordering = ['-date'] def search(request): query = request.GET.get("key") if query: results = home_blog_model.objects.filter(Q(title__icontains=query)) else: results = home_blog_model.objects.filter(status="Published") return render(request , "home.html" , {"query":query}) urls.py from django.urls import path from . import views from django.contrib.auth.views import LoginView , LogoutView urlpatterns = [ path("" , views.home_view.as_view() , name="blog-home"), path("posts/<int:pk>/" , views.detail_view , name="detail"), path("admin/login/" , LoginView.as_view(template_name="admin-login.html") , name="admin-login"), path("admin/logout/" , LogoutView.as_view() , name="admin-logout"), path("admin/post/create/" , views.create_post_view , name="create_post"), path("post/search/" , views.search , name="search_post"), ] models.py from django.db import models class home_blog_model(models.Model): title = models.CharField(max_length=100) summary = models.CharField(max_length=300) content = models.TextField() date = models.DateTimeField(auto_now=True) def __str__(self): return self.title home.html <div align="right"> <form class="form-group" method="GET" action="{% url 'search_post' %}"> <input type="text" name="key" placeholder="search........" value="{{request.GET.key}}"> <button class="btn" type="submit">Search</button> </form> </div> thanks in advance ! -
How do I retain selected option after submit?
Is there a way to retain the selected option from a drop down list that is using a for loop? views.py: ... queryC = request.GET.get('clientList', '') queryT = request.GET.get('topicList', '') topicList = Topic.objects.all().order_by('Name') clientList = ClientDetail.objects.all().order_by('Client_name') ... return render(request, 'app/search_es20.html', { "responses": responses, "query": q, "queryR": queryR, "noOfResults": resultsCount, "username": username, "topicList": topicList, "clientList": clientList, "queryC": queryC, "queryT": queryT, }) html: Topic <select name="topicList"> <option value="empty"></option> {% for element in topicList %} <option value={{element.Name}}>{{ element.Name }}</option> {% endfor %} </select> Client <select name="clientList"> <option value="empty"></option> {% for element in clientList %} <option value={{element.Client_name}}>{{ element.Client_name }}</option> {% endfor %} </select> I have tried using IF statements but it's not doing it properly -
unsupported operand type(s) for -: 'NoneType' and 'datetime.datetime'
is giving this error, but before it was not, I do not know what happened Model.py class MovRotativo(models.Model): checkin = models.DateTimeField(auto_now=False, null=False, blank=False) checkout = models.DateTimeField(auto_now=False, null=True, blank=True) valor_hora = models.DecimalField(max_digits=5, decimal_places=2) veiculo = models.ForeignKey(Veiculo, on_delete=models.CASCADE) pago = models.BooleanField(default=False) def horas_total(self): return math.ceil((self.checkout - self.checkin).total_seconds() / 3600) def total(self): return self.valor_hora * self.horas_total() def __str__(self): return self.veiculo.placa views.py @login_required def movrotativos_novo(request): form = MovRotativoForm(request.POST or None) if form.is_valid(): form.save() return redirect('core_lista_movrotativos') -
How to get contents of curl uploaded file in django
I'm using Django 2.1.1 and would like to upload a file using this curl command: curl -i -b cookies.txt -c cookies.txt -e https://neon/accounts/login/ \ --cert client.crt --key client.key -F "name=@afile" \ -H "X-CSRFToken: 9rQMPHGdPJHLVbSEmhwXLc1m9i1KIQVVenRPqP2JkqrldKgWX4GMahOET7pk5cnw" \ -H "Content-type: multipart/form-data" \ -X POST -F 'test=blaat' https://neon/test/ the url goes to the following view: def test(request): response = pprint.pformat(request.FILES, indent=4) return HttpResponse(response) The result of curl is: HTTP/1.1 100 Continue HTTP/1.1 200 OK Server: nginx/1.10.3 (Ubuntu) Date: Thu, 22 Nov 2018 14:37:03 GMT Content-Type: text/html; charset=utf-8 Content-Length: 72 Connection: keep-alive X-Frame-Options: SAMEORIGIN Strict-Transport-Security: max-age=63072000; includeSubdomains X-Frame-Options: DENY X-Content-Type-Options: nosniff { 'name': <InMemoryUploadedFile: afile (application/octet-stream)>} So how can I get the contents of 'afile' in a str variable in Django... I tried request.FILES['file'].chunks() but don't really have an idea of what I am trying here. Also writing the contents to a file on the server: no idea. The main thing is to get it into a variable so I can for example parse JSON from that file. The login, SSL certificates and authentication all works fine. That's not an issue. -
Django show exchange rate via xml file
I want to show the US dollar currency on my website. There is have xml file for currency; http://www.tcmb.gov.tr/kurlar/today.xml But I have no idea how to get this information in. For example, how I can take USD and EUR data on my website. (I would be very happy if you give the sample code.) Thank you very much in advance. Perhaps it may be better to print this information into mysql on a daily. And after this i can read this informations in mysql -
Allow to create mutilple model from foreign key in one view (with generic createview)
With django, I'm looking for a way to create easily a model which point to another models using Foreign Key in only one view using the generic create view. with an example, it should be easier to understant.. models.py # models.py from django.contrib.auth.models import User class Group(models.Model): name = models.CharField( _("Group name"), max_length=128, blank=False, null=False) comment = models.TextField(max_length=512, blank=False, null=False) def get_absolute_url(self): return reverse('group_detail', kwargs={'pk': self.pk}) def __str__(self): return _("%(name)s Group") % {'name': self.name} class UserAcl(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group, blank=True, null=True, on_delete=models.SET_NULL) comment = models.CharField( _("comment"), max_length=128, blank=False, null=False) views.py enter code here # views.py class SettingsView(LoginRequiredMixin, UserPassesTestMixin, generic.ListView): model = UserAcl template_name = 'my_app/settings.html' When I display that view, I would like to access to all fields from User django class, all fields from Group class and of course all fields from UserAcl class. So 3 objects will be created : - User - Group - and finally the UserAcl. Whereas currently, only 3 fields are visible (those from UserAcl with the choice of User/group already in DB. Then when I post it, 3 object are saved ( User db (django), Group and UserAcl) How can I do that? since, didn't find it. Thx -
Optional pk argument for CREATE in Django's DRF ModelViewSet
I have a regular ModelViewSet for one of my models, but I want to have the option to specify a specific PK to create a new instance. E.g. if I would post: { "name": "Name" } It would get a random pk. But if I posted: { "id": "123", "name": "Name" } I want it to have the specified pk (id). Similar to this person, what I did is adding the id field to my ModelSerializer like this: class ConversationSerializer(serializers.ModelSerializer): id = serializers.CharField() # Instead of serializer.ReadOnlyField() class Meta: model = Conversation fields = '__all__' While this works for the create method, it causes issues for the update and partial_update ones, where id is now a required argument as a query string parameter and in the request body like this (from the docs): update PUT /conversations/{id}/ Update existing conversation. Path Parameters The following parameters should be included in the URL path. Parameter Description id (required) A unique value identifying this conversation. Request Body The request body should be a "application/json" encoded object, containing the following items. Parameter Description id (required) access_token username password app_user_id name How can I fix this such that the id parameter is only optional for the … -
django reverse in formModel
In my views.py I have a class who take a (CreateView) and in the form_class take a Testform in forms.py The problem is when in my forms.py I use the def save(...) method, it save correctly the data but the is no way to reverse after that it say to me no matter what I try to return it says "No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model." ok, so I've tried everywhere to put this method but no way, it allways gives me this error