Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django _mysql.connection.query(self, query) django.db.utils.OperationalError: (1050, "Table 'gaur' already exists")
I don't want to use Fake app migrate option for the solution Please suggest any other method for this problem Do check my code Models - from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Delhi(models.Model): account_id = models.IntegerField() type_code = models.CharField(max_length=200) sub_type_code = models.CharField(max_length=200) name = models.CharField(max_length=200) credit_amount = models.IntegerField() debit_amount = models.IntegerField() # parent = TreeForeignKey('self', null = True, related_name = 'strctr', on_delete = models.CASCADE) class Meta: managed = True db_table = 'gaur' def __str__(self): return self.type_code class Ranchi(MPTTModel): node_name = models.CharField(max_length = 100) parent = TreeForeignKey('self', null = True, related_name = 'strctr', on_delete = models.CASCADE) def __str__(self): return self.name Serializer - from rest_framework import serializers from .models import Delhi, Ranchi class DelhiSerializer(serializers.ModelSerializer): class Meta: model = Delhi fields = "__all__" class RanchiSerializer(serializers.ModelSerializer): class Meta: model = Ranchi fields = "__all__" View - from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import generics from rest_framework import status class CreateView(generics.ListCreateAPIView): """This class defines the create behavior of our rest api.""" queryset = Delhi.objects.all() serializer_class = DelhiSerializer def perform_create(self, serializer): """Save the post data when creating a new bucketlist.""" serializer.save() class DetailsView(generics.RetrieveUpdateDestroyAPIView): """This class handles the http GET, PUT and DELETE requests.""" queryset = Delhi.objects.all() serializer_class = … -
How can I deploy my django website on multiple server, that is how can I make it distributed?
I have my django website, which I want to make distributed, I know all the concept of system design and distributed system but still cannot figure out how can I serve it using multiple server. Can someone suggest how to make my system distributed. How can I install load balancer and direct the request to my servers. I cannot find any resource to learn about making my django website distributed and install various distributed system software concept on it? How can I make my django website serve from different server with a centralised database. Can someone explain me the steps to do so? Or point me to any learning material cuz I can't find any resource online. -
How to edit default django home page and new page
I am beginner to Django. I just install the django & there is default home page appearing. I want to edit the default home page content & create new extra pages. Please can any one help me how to add the new pages with using the template. -
How join annotate value of QuerySet and property field of Model to one logic in Django?
I have this situation. I calculate a diameter in two ways: annotate of QuerySet and property in Model. class CircleQuerySet(models.QuerySet): def annotate_diameter(self): return self.annotate(diameter=models.F('radius')*2) class Circle(models.Model): radius = models.DecimalField(max_digits=11, decimal_places=2) objects = CircleQuerySet.as_manager() @property def diameter(self): return self.radius * 2 How can I join this two ways to one? Is it exists? -
Django - how to perform delete object using a view
This is my code in my html {% for summary in psummary %} <tr> <td colspan="3" class="tdcell">{{summary.Description}}</td> <td colspan="2" class="tdcell">{{summary.Start_Grading_Period}}</td> <td colspan="2" class="tdcell">{{summary.End_Grading_Period}}</td> <td colspan="2" class="tdcell">{{summary.Method}}</td> <td colspan="3" class="tdcell"><span style="text-align: right;font-weight: 600;" class="close" onclick="deleteRow(this)"><a href="url:delete_view">&times;</a></span></td> </tr> {% endfor %} this is how it looks like this is my views.py def function(request,part_id =None): object = gradingPeriodsSummary.objects.get(id=part_id) object.delete() print(object) return render(request, 'admin/Homepage/view.html') urls.py path('delete/(?P<part_id>[0-9]+)/$', Homepage.views.function, name='delete_view'), i just want that if the teacher click the close button it will delete the record in the database i followed the instruction here, but its not working Django - How to delete a object directly from a button in a table -
How to handling "We are unable to register the default service worker" when already using https?
I have a project using django and firebase. I need notification feature of firebase so that I create a service worker file in templates folder and my view.py like : ... class ServiceWorkerView(View): def get(self, request, *args, **kwargs): return render(request, 'whizper_apps/firebase-messaging-sw.js', content_type="application/x-javascript") my urls.py like : url(r'firebase-messaging-sw.js', views.ServiceWorkerView.as_view(), name='service_worker') When I running my project from localhost, it work fine. I get the token and can get notification. Then, I'm trying deploy my project to server using gunicorn, supervisor, nginx and using https (the documentation to set up https in nginx : https://www.linode.com/docs/web-servers/nginx/enable-tls-on-nginx-for-https-connections/#configure-the-http-block). When I run my project, i get error like this I follow https://jee-appy.blogspot.com/2017/01/deply-django-with-nginx.html as documentation to deploy my project. What I have to do so the service worker can work and I get the notification token. Thank's before. -
MarkItUp Supports Alignment Option or Not
I am using Django_Markdown app for my project. I just wanted to know whether Markitup supports Alignment options or not? If not, then how can i add this alignment tool in my text body? I have tried writing the text under the tag but it's not working. Thanks in advance. -
Best way to pass variable to remote (Golang) app from Django View
I'm creating a web application where a server will register itself via curl to the rest framework. When the POST is executed in the view.py of the django app it'll will kick off a remote command to a Golang app that'll change the server's port VLAN and start a Docker container. That piece I can figure out, but the execution from POST to ensure the Golang is handling this participial server I'm not sure on. My thought is to use a option parser because the payload from the server will have server serial, mac, ip info that'll be saved in the database. When the Golang app runs, something like <Go app> -s <serial Number> will then perform a GET call based on the provided serial number then start doing its thing. Would that be the best way to get this done or is there a better way? -
Error: failure to route to my newly created app
So I'm following the django tutorial at https://docs.djangoproject.com/en/2.2/topics/http/urls/ i reached the point where i should be able to navigate to the polls url instead I get a 404 error Page not found (404) Request Method: GET Request URL: http://localhost:8000/polls/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ The current path, polls/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. my folder structure is D:. | db.sqlite3 | manage.py | +---mysite | | settings.py | | urls.py | | wsgi.py | | __init__.py | | | \---__pycache__ | settings.cpython-37.pyc | urls.cpython-37.pyc | wsgi.cpython-37.pyc | __init__.cpython-37.pyc | \---polls | admin.py | apps.py | models.py | tests.py | urls.py | views.py | __init__.py | \---migrations __init__.py I have modified the mysite/urls.py as from django.contrib import admin from django.urls import path, include urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] added a urls.py file inside polls folder and filled it with from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index') ] and finally adjusted the polls/views.py file to … -
Performant way to validate numerics or range of numerics with RegexValidator in Django
The problem I have a model that has a CharField field, where the field can only accept numerics or a range of numerics. The numerics must either have a leading zero if they are decimal and are <1, and if they are a whole number, they cannot have a trailing period unless the trailing period has a trailing zero. The ranges are delineated using a hyphen and must not contain any spaces. I'm using Django's RegexValidator to validate the field. Note: I don't care if the ranges are reversed (e.g. 6-3, 10.3-0.13) These are some examples of values that should pass in the validator: 5 0.42 5.0 5-6 5-6.0 0.5-6.13 5.1-6.12 13.214-0.1813 These should be invalid values for the validator: 5. 5.1.3 5.13.215 5-13.2-14 .13-1.31 5-6. 5 - 6 My current solution my_field = models.CharField( ... validators=[ RegexValidator( r'^[0-9]+([.]{1}[0-9]+){0,1}([-]{1}[0-9]+([.]{0,1}[0-9]+){0,1}){0,1}$', message='Only numerics or range of numerics are allowed.' ) ] ) What I need help at As you can see, this is a pretty gnarly regex pattern, and I'm not so sure if this pattern is performant. I'm not a regex guru so I'd appreciate if someone offers a better solution. -
Data added in Request session lost when using HttpResponseRedirect between views
I have an API, in which if the user is not permitted to access it, am redirecting it to another view along with a user message adding to request session and using that info am using django message framework to display the message in templates. In this process the session data passed from one view is lost while I look in the redirected view. And this is happening only in Production environments. Here is the code. Views - def data_asset_alert_track(request, edf_data_asset_id): data_asset = EdfDataAsset.objects.get(data_asset_id=edf_data_asset_id) x_app_role = access_control.get_xapp_role(request) roles = access_control.get_roles(x_app_role) user = User.objects.get(username=request.user) is_edit_permitted = (access_control.has_edit_all_access(roles, 'edfdataasset'))\ or (True if data_asset.owner_id and data_asset.owner.owner_id == user.username else False)\ or (access_control.is_auth_user(data_asset.owner, user) if data_asset.owner_id else False) if not is_edit_permitted: request.session['message'] = 'Unauthorized Action: Edit DataAsset - %s not permitted'%data_asset.data_asset_name return HttpResponseRedirect(reverse('data_assets')) if data_asset.alert_fl is False: data_asset.alert_fl = 'True' else: data_asset.alert_fl = 'False' data_asset.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) Redirected to view- def data_assets(request): if 'message' in request.session: logr.info("There is a message") messages.add_message(request, messages.ERROR, "A trial message") data_asset_list = EdfDataAsset.objects.select_related('provider').order_by('data_asset_name') field_filter = DataAssetFilter(request.GET, queryset=data_asset_list) context = {'data_asset_list': data_asset_list, 'filter': field_filter, } return render(request, 'edf/data_assets.html', context) This works completely fine in all dev and test environments. What could be the issue? I tried adding these two … -
Django Webpack React: Plugin/Preset files are not allowed to export objects, only functions
I'm trying to configure my react with django. but for some reason whenever I try to npm run start I get this error: Plugin/Preset files are not allowed to export objects, only functions. I've tried: npm install @babel/preset-react npm install babel-preset-react --save-dev npm install -D babel-loader @babel/core @babel/preset-env webpack but did nothing. Django version: 2.2.6 Webpack config: var path = require('path'); var webpack = require('webpack'); var BundleTracker = require('webpack-bundle-tracker'); module.exports = { entry: path.join(__dirname, 'assets/src/js/index'), output: { path: path.join(__dirname, 'assets/dist'), filename: '[name]-[hash].js' }, plugins: [ new BundleTracker({ path: __dirname, filename: 'webpack-stats.json' }), ], module: { rules: [ { test: /\.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, options: { presets: ['react'] } }, ], }, } settings: WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'dist/', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), } } .babelrc: { "presets": [ "es2015", "react" ] } package.json: { "name": "collegeapp", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "./node_modules/.bin/webpack --config webpack.config.js", "watch": "npm run start -- --watch" }, "repository": { "type": "git", "url": "git+https://github.com/FendyPierre/collegeapp.git" }, "author": "", "license": "ISC", "bugs": { "url": "https://github.com/FendyPierre/collegeapp/issues" }, "homepage": "https://github.com/FendyPierre/collegeapp#readme", "devDependencies": { "@babel/core": "^7.7.4", "@babel/preset-env": "^7.7.4", "babel-cli": "^6.26.0", "babel-core": "^6.26.3", "babel-loader": "^8.0.6", "babel-preset-env": "^1.7.0", "babel-preset-es2015": "^6.24.1", … -
benefit of Django REST Framework when using django with API like calls?
reading This question it looks like I can setup DRF within an existing django project. That got me thinking... I have a django application that uses ajax calls which return very simple view partials which quickly display on the page, and then a few seconds later another ajax call is made to return another view. (you can think of it like the Whac-a-mole games, but each mole is a different view partial being returned from the server.) so essentially I have 30-50 calls per minute to mysite.com/ajax_new_mole with a view similar to (just made this up on the fly, ignore any errors) ... def ajax_new_mole(request): random_id = get_random_mole_id() random_mole = Mole.objects.get(id = random_id) return render(request, 'partials/_mole_photo.html, {'mole':random_mole}) ... and the _mole_photo.html template {% load load_cloudfront %} <div class="img-wrapper" id="{{ photo.id }}"> <span class="album-title" id="album-title">Title: {{ mole.name }}</span> <img src='{% load_cloudfront_medium mole.name %}' id="image{{ photo.id }}"/> </div> Now to my question. In this situation. Would Django REST Framework offer any performance benefits in the reduced overhead for responding to and rendering this content? -
Django filter to check if there are any other booking between the given dates
I am trying to make a hotel booking app. So I have two models, i.e., Room and Booking. # models class Room(models.Model): name = models.CharField(max_length=50) class Booking(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) booked_for_datetime = models.DateTimeField() booked_till_datetime = models.DateTimeField() How can I lock the room A, so the room will not be available to book if there is already another booking for a room A. Eg: Room 101 was booked between 01-12-2019 to 04-12-2019. I would like to block the booking if someone's trying to book the same room (101) between 29-11-2019 to 01-12-2019 between 29-11-2019 to 02-12-2010 between 01-12-2019 to 04-12-2019 between 02-12-2019 to 03-12-2019 between 04-12-2019 to 07-12-2019 I am working with django rest framework, so I will have to apply these validation on the create and update method, maybe something like this: # serializers def roomAvailable(validated_data): available = False # ... # validation check here... # ... return available class BookingSerializer(serializers.ModelSerializer): class Meta: model = Booking fields = '__all__' def create(self, validated_data): if roomAvailable(validated_data): return Booking.objects.create(**validated_data) else: raise serializers.ValidationError({ "detail": "Room is not available for these dates." }) def update(self, instance, validated_data): if roomAvailable(validated_data): ... instance.save() else: raise serializers.ValidationError({ "detail": "Room is not available for these dates." }) return … -
django.urls.exceptions.NoReverseMatch: Reverse for 'user-list' not found. 'user-list' is not a valid view function or pattern name
Tutorial 5: Relationship and Hyperlink API Errors Tutorial link address is:https://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/ I tried query-related solutions, and encountered similar problems on stackoverflow, but after testing, I still couldn't use them. views.py class SnippetList(generics.ListCreateAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) def perform_create(self, serializer): serializer.save(owner=self.request.user) class SnippetDetail(generics.RetrieveDestroyAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly) class UserList(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer class UserDetail(generics.RetrieveAPIView): queryset = User.objects.all() serializer_class = UserSerializer @api_view(['GET']) def api_root(request, format=None): return Response({ 'users': reverse('user-list', request=request, format=format), 'snippets': reverse('snippet-list', request=request, format=format), }) class SnippetHighlight(generics.GenericAPIView): queryset = Snippet.objects.all() renderer_classes = [renderers.StaticHTMLRenderer] def get(self, request, *args, **kwargs): snippet = self.get_object() return Response(snippet.highlighted) urls.py urlpatterns = format_suffix_patterns([ path('', views.api_root), path('snippets/', views.SnippetList.as_view(), name='snippet-list'), path('snippets/<int:pk>/', views.SnippetDetail.as_view(), name='snippet-detail'), path('snippets/<int:pk>/highlight/', views.SnippetHighlight.as_view(), name='snippet-highlight'), path('users/', views.UserList.as_view(), name='user-list'), path('users/<int:pk>/', views.UserDetail.as_view(), name='user-detail'), ]) urlpatterns += [ path(r'api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] serializers.py class SnippetSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html') class Meta: model = Snippet fields = ['url', 'id', 'highlight', 'owner', 'title', 'code', 'linenos', 'language', 'style'] class UserSerializer(serializers.HyperlinkedModelSerializer): snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True) class Meta: model = User fields = ['url', 'id', 'username', 'snippets'] -
Possible to escape or otherwise pass a value that includes / in Django URL
I'm building a tool using Django that works with the part numbers that my company uses, one set of part numbers includes /'s which I didn't realize when I set up the url to access the part summary. Now when try to pass one of those part numbers it breaks things, is there a way to work around this? I'd like to avoid changing the part number or adding a unique id with no other meaning to the model. an example part number that causes the problem is P-030-P-401/ND the url pattern is /parts/ Thanks in advance -
How to save search result to a model
Models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() comment = models.TextField() date_posted = models.DateField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) patient = models.ForeignKey(User, on_delete=models.CASCADE, related_name='patient') def __str__(self): return self.title def get_absolute_url(self): return reverse('public:post-detail', kwargs={'pk': self.pk}) HTML search <div class="content-section"> <form method="GET" action="{% url 'public:home' %}"> <input name ="q" value="{{request.GET.q}}" placeholder="search.."> <button class="btn btn-success" type="submit"> Search </button> </form> </div> VIEWS.py class SearchResultsView(ListView): model = User template_name = 'all_users/doctor/search.html' def get_queryset(self): # new query = self.request.GET.get('q') object_list = User.objects.filter(Q(username__icontains=query)) return object_list I want to save this object_list in "patient" model. How can i save search result to model. Is there any different method to search user and save to model? -
I continue getting an error whenever I run my Django program
I started building an application using Django but whenever I run it I always get this error message. django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is p robably caused by a circular import. I currently have three files: mysite/urls.py : from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^account/', include('accounts.urls')) accounts/urls.py : from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.home), ] and views.py : from django.shortcuts import render, HttpResponse def home(request): return HttpResponse('Home page') This should theoretically print "Home page" on my ip but the error message continues arising in cmd when I run : python manage.py runserver 127.0.0.1:8080 (I cd'd it too) This is a simplified version of my hierarchy: Mysite accounts urls.py views.py mysite urls.py I have been following a tutorial and checked that everything is correct. Can someone help me find a solution? (Please don't beat me up if I messed something very obvious up. I am new and quite inexperienced) -
Cannot resolve keyword 'active' into field. Choices are... Django
I'm following a tutorial online. but now is driving me crazy. i'm trying to update a view. but honestly after a couple of days i can not find the issue. i have been following the trace, but i can get it. i get the Cannot resolve keyword 'active' into field. Choices are: activate, cart, cart_id, id, product, product_id, quantity message After click the button to get the details of the product and create a new or add a product to a cart the message show up lookups, parts, reffed_expression = self.solve_lookup_type(arg) File "C:\Users\k-her\OneDrive\Escritorio\New\env\lib\site-packages\django\db\models\sql\query.py", line 1049, in solve_lookup_type _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta()) File "C:\Users\k-her\OneDrive\Escritorio\New\env\lib\site-packages\django\db\models\sql\query.py", line 1419, in names_to_path raise FieldError("Cannot resolve keyword '%s' into field. " django.core.exceptions.FieldError: Cannot resolve keyword 'active' into field. Choices are: activate, cart, cart_id, id, product, product_id, quantity [28/Nov/2019 02:18:14] "GET /cart HTTP/1.1" 500 106045 [28/Nov/2019 02:18:26] "GET /cart/add/5 HTTP/1.1" 302 0 Internal Server Error: /cart Traceback (most recent call last): File "C:\Users\k-her\OneDrive\Escritorio\New\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\k-her\OneDrive\Escritorio\New\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\k-her\OneDrive\Escritorio\New\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\k-her\OneDrive\Escritorio\New\store\views.py", line 51, in cart_detail cart_items = CartItem.objects.filter(cart=cart, active=True) File "C:\Users\k-her\OneDrive\Escritorio\New\env\lib\site-packages\django\db\models\manager.py", line … -
Emails not sending through Django Contact Form
I created a Contact form on my website built in Django but emails sent from the form do not seem to actually send. Here is my form code in forms.py: class ContactForm(forms.Form): email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) Here is the code in my views.py: def contact(request, success=""): submitted = False template_name = "main/contact.html" if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['markbekker1998@gmail.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect("success/") if success != "": submitted = True context = {"form": form, "submitted": submitted} return render(request, template_name, context) And finally here is the forms html code: {% load crispy_forms_tags %} <h1>Contact Us</h1> <form method="post"> {% csrf_token %} {{ form|crispy }} <div class="form-actions"> <button type="submit" class="btn btn-primary mb-2">Send</button> </div> </form> If any other code is needed to help debug please let me know and I will include it. Thank you. -
Django: Defining an Admin Action when the Queryset has been modified
If I have some ModelAdmin that defines a custom queryset like: def get_queryset(self, request): queryset = super().get_queryset(request) queryset = queryset.annotate( other_amount=Sum('other__amount'), delta = Sum(-1*F('amount') - F('other__amount')), ) return queryset When I go to create an admin action like: def makeReimbursableUnsubmitted(modeladmin, request, queryset): queryset.update(updated_status='RU') and then go to run the action, I get the following error: Cannot resolve keyword 'delta' into field. Choices are: <fields defined in the model> How can I update my action to work again? -
URL, GET, POST parameters in Django
I am super fresh in Django, I might need some help. Case: I made endpoint in urls.py. There will be pass latitude and long to his endpoint as parameters. router.register( r'name', views.NameView, base_name='name') urlpatterns = [ path('name/', views.NameView.as_view(), name='getLocation') ] What I want to achieve: View connected to the endpoint take the parameters and passes it to the '.../product' API and it receive the data and return the data to front end. I have read a lot about request, but I am confused. This is my view: class NameView(views.ModelViewSet): def getLocation(Location): # here I want to GET with params in URL r = requests.get(url, params=Location) # POST to URL and next should receive data and send to front r = requests.post(url, params=Location) I used Location, beacuse I have definied class in model Location with lat and long params. I will appreciate any help -
Don't know how to convert the Django field (<class 'django.contrib.gis.db.models.fields.MultiLineStringField'>)
I am trying to do a query to my graphql api and I get the next error when i do a query to my api using postman. I understand that the error says it doesn't know how to convert the MultiLineStringField field route=models.MultiLineStringField() in my Route Model, and I think I should do it manually but I don't know where or how. The graphql api is buildins using django 2.2.7, graphene 2.1.8. This is the error: Exception at /graphql Don't know how to convert the Django field routes.Route.route (<class 'django.contrib.gis.db.models.fields.MultiLineStringField'>) Request Method: POST Request URL: http://localhost:8000/graphql Django Version: 2.2.7 Exception Type: Exception Exception Value: Don't know how to convert the Django field routes.Route.route (<class 'django.contrib.gis.db.models.fields.MultiLineStringField'>) Exception Location: /home/jccari/code/gosip-server/venv/lib/python3.6/site-packages/graphene_django/converter.py in convert_django_field, line 95 Python Executable: /home/jccari/code/gosip-server/venv/bin/python Python Version: 3.6.8 Python Path: ['/home/jccari/code/gosip-server', '/home/jccari/code/gosip-server/venv/lib/python36.zip', '/home/jccari/code/gosip-server/venv/lib/python3.6', '/home/jccari/code/gosip-server/venv/lib/python3.6/lib-dynload', '/usr/lib/python3.6', '/home/jccari/code/gosip-server/venv/lib/python3.6/site-packages'] Server time: Thu, 28 Nov 2019 00:30:29 +0000 Route model: from django.contrib.gis.db import models class Route(models.Model): name = models.CharField(max_length=50) route = models.MultiLineStringField() def __str__(self): return self.name This is my queries.py import graphene from graphene_django.types import DjangoObjectType, ObjectType from ..models import Route class RouteType(DjangoObjectType): class Meta: model = Route class Query(ObjectType): route = graphene.Field(RouteType, id=graphene.Int()) routes = graphene.List(RouteType) def resolve_route(self, info, **kwargs): id = kwargs.get('id') … -
Django: Nothing happens when I run 'py manage.py runserver'
I am following the tutorial on the Django website. I have changed the directory to where mysite is and nothing happens when I run the script from the tutorial in the Command Prompt. It just goes to the next line with no errors. I read from previous responses it has to with Environment Variables but when I added the directory it still did not work. I have the latest version of Python and Django. -
dockerized django gunicorn nginx doesn't find static files when i add URL to urls.py
This is really weird and i've tried fixing it for over 20 hours over the past few days, but no luck. This is a project that i'm trying to dockerize and it's almost done except for being able to show static files. My issue is that the static files aren't being served when I add the URL to the urls.py file that is creating a path to my index app. Basic urls.py (main project urls.py) from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), ] If I visit http://localhost:8000 the admin static files are shown perfectly with no issues at all with the config above. If I then add the URL to my index app like the following inside urls.py (main project urls.py) from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('index.urls', namespace="index",)), ] And once again I navigate to http://localhost:8000 and this time the static files aren't being shown! I am baffled and honestly have no idea. I have the full source code available on Github. Feel free to take a look in there, clone the project and try for yourself.