Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how woul i get rid off this error "OSError: [WinError 123] The filename,"
Am creating a project, When I run the server I get the error named "OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect", but before this there is another error which pops up "ModuleNotFoundError: No module named 'dep.urls' ". I have tried this several times by just creating project, an app and mapping to the urls without writting any code and run it but i get the same error above Am using django 2.2.3, python 3.6.8 and mysql 5.7.26. In the previous version of django(2.1.8) was working fine, I have tried to google a lot what I have found is that in the newer version of django there is the new way of mapping to the urls. Am pretty sure that the solution of my problem is in this link. When I open the described file, I don't find where to edit, what is being said is not available in the file. Please help!! urls from django.contrib import admin from django.urls import path,include urlpatterns = [ path('',include('dep.urls')), path('admin/', admin.site.urls), ] -
django filter through object after loop in template
I have a page that displays a snapshot of projects in a list of boxes, each box has project owner, title date, that kind of thing, there is also a window within that separates the updates into 7 categories, the updates are in a separate table. Looping through the projects is fine, but the updates come from all the projects. How do I filter out the other projects? I can post my code, but I have done this 2 or 3 times in the past month with no response so suspecting that my structure is completely wrong -
I need help in converting urlpatterns url to their path equivalents
I am helping a friend with a project and I am having trouble converting urlpatterns url to their path equivalents. Any help? I've managed the first part. `path('store', views.product_list, name='product_list'),` But the rest seems challenging urlpatterns = [ url(r'^store', views.product_list, name='product_list'), url(r'^(?P<category_slug>[-\w]+)/$', views.product_list, name='product_list_by_category'), url(r'^(?P<id>\d+)/(?P<slug>[-\w]+)/$', views.product_detail, name='product_detail'), ] -
Diplay ModelForm in html
I am creating a webapp in which a user can create a project, inside each project he can answer a set of question(in my app, I call them secondquestions). I am trying to use ModelForm to ease the creation of the form by following this guide: https://docs.djangoproject.com/en/2.2/topics/forms/modelforms/ Howver I do not understand how I can display in my html my form. secondquestions/views.py def secondquestionstoanswer(request, project_id): project = get_object_or_404(Project, pk=project_id) if request.method == "POST": form = SecondquestionForm(request.POST) if form.is_valid(): form.save() return render(request, 'secondquestions/secondquestionstoanswer.html', {'project':project}) secondquestions/models.py from django.db import models from django.contrib.auth.models import User from django.conf import settings from projects.models import Project from django.db import models from django.forms import ModelForm class Secondquestion(models.Model): second_one = models.TextField() second_two = models.TextField() second_three = models.TextField() second_four = models.TextField() second_five = models.TextField() second_six = models.TextField() second_seven = models.TextField() second_eighth = models.TextField() second_nine = models.TextField() developer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) project = models.OneToOneField(Project, on_delete=models.CASCADE) class SecondquestionForm(ModelForm): class Meta: model = Secondquestion fields = ['second_one', 'second_two', 'second_three', 'second_four', 'second_five', 'second_six', 'second_seven', 'second_eighth', 'second_nine'] secondquestions/secondquestionstoanswer.html {% extends 'base.html' %} {% block title %}First set{% endblock %} {% block content %} <form method="post"> {% csrf_token %} {{ form }} <button type="submit">Submit</button> </form> {% endblock %} My problem: In my html I just … -
SECRET_KEY settings not empty but returning empty on Wagtail
I just installed wagtail-blog on my project and added blog to the INSTALLED_APPS and url(r'^blog/', include('blog.urls', namespace="blog")), to the main urls.py. Once I migrated, it returned django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. I double checked my base.py and it has a string on the SECRET_KEY but is still returning the error. Here's the MIDDLEWARE and INSTALLED_APPS INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'global', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'wagtail.contrib.styleguide', 'modelcluster', 'taggit', 'allauth', 'allauth.account', 'allauth.socialaccount', 'bootstrap3', 'copyright', 'landing', 'registration', 'blog', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'wagtail.core.middleware.SiteMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware', ] -
Tablesorter's filter_selectSource removes options not available for current page with server-side pagination and select options preparation
I'm preparing arrays with options for Tablesorter's filter_selectSource in Python/Django. Because initially it worked very strange for me when I switched to server-side filtering. The dropdown options did show up only when I've type one symbol in one of the 'search' filters and then every time it showed select options available one step before. And then I've decided to try and make most of the work on server-side players.views def skaters_averages_json(request, page, sort_col, filt_col, rookie_filt): start = utils.PAGE_SIZE_2*(page - 1) end = start + utils.PAGE_SIZE_2 skaters = Skater.objects.select_related('team') filtering = utils.filter_columns(filt_col) if filtering: skaters = utils.apply_filters(skaters, filtering) if utils.rookie_filter(rookie_filt): skaters = skaters.filter(rookie=True) sorting = utils.sorting_columns(sort_col) one_page_slice = utils.sort_table(sorting, skaters)[start:end] skaters_json = json.loads(serializers.serialize('json', one_page_slice, use_natural_foreign_keys=True)) domain = request.get_host() total_rows = skaters.count() data = utils.process_json(domain, skaters_json, total_rows, page) data['filter_select'] = { **utils.filter_select_opts(skaters, 3, 'position_abbr'), **utils.filter_select_opts(skaters, 4, 'team__abbr'), **utils.filter_select_opts(skaters, 5, 'nation_abbr'), } return JsonResponse(data, safe=False) players.utils def filter_select_opts(skaters_query, col_number, field_name): uniques = list(skaters_query.values_list(field_name, flat=True).distinct()) return {col_number: sorted(uniques, key=lambda x: (x is None, x))} So my JSONResponse looks like this. Page 1 { "total": 41, "rows": [ [row 1] ... [row 25] ], "filter_select": { "3": [ "C", "D", "LW", "RW" ], "4": [ "ANA", "BOS", "BUF", "CAR", "CBJ", "CGY", "CHI", "COL", "DAL", "EDM", … -
distinct doesn't work when I'm use order_by
How to solve this problem? Without sorting everything works. With sorting - no. I found similar questions, read the documentation, but could not be resolved. Here, as I tried. credits = credits.filter(hot=False).order_by('creditpayment__rate', '-creditpayment__period_to').distinct() credits = credits.filter(hot=False).order_by('creditpayment__rate', '-creditpayment__amount_to', '-creditpayment__period_to').distinct('creditpayment__rate', 'creditpayment__period_to') https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.distinct -
django modal not showing up
modal not showing up JS file $(function () { $(".js-create-node").click(function () { $.ajax({ url: 'create/', type: 'get', dataType: 'json', beforeSend: function () { $("#modal-book").modal("show"); }, success: function (data) { $("#modal-book .modal-content").html(data.html_form); } }); }); }); url file path('create/', mainapp.nodeCreate, name='node_create'), view file def nodeCreate(request): form = NodeForm() context = {'form': form} html_form = render_to_string('includes/partial_node_create.html', context, request=request, ) return JsonResponse({'html_form': html_form}) there is no error, it just doesnt show the modal up i am just trying to imiate https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html steps -
Android - Handling different types of JSON data from Django backend
I get the following output from a request: { "allposts": [ { "created": "2019-07-08T12:25:34.732217Z", "description": "My First ImagePost", "id": 1, "imagepostdata": "http://127.0.0.1:8000/media/Images/None/placeholder.jpg", "owner": "http://127.0.0.1:8000/users/getUserById/1/", "profilePhotoOfUser": "http://127.0.0.1:8000/media/Images/None/placeholder.jpg", "type": "ImagePost", "url": "http://127.0.0.1:8000/posts/getImagePostById/1/" }, { "audio": "http://127.0.0.1:8000/media/Audios/None/placeholder.3gp", "clique": "http://127.0.0.1:8000/cliques/getCliqueById/1/", "created": "2019-07-08T12:25:56.748829Z", "id": 2, "image": "http://127.0.0.1:8000/media/Images/None/placeholder.jpg", "owner": "http://127.0.0.1:8000/users/getUserById/1/", "profilePhotoOfUser": "http://127.0.0.1:8000/media/Images/None/placeholder.jpg", "text": "My First TextPost", "type": "TextPost", "url": "http://127.0.0.1:8000/posts/getTextPostById/2/", "video": "http://127.0.0.1:8000/media/Videos/None/placeholder.mp4" } ] } The first item in the JSON array represents an image post and the second item represents a text post. I have image and text posts as post type. Here, you can see that the server gives the requesting client the different types collected as one output. The fields of the items can be different. For ex.: imagepostdata vs. textpostdata. Now, I am not sure how to define the model classes in my Android project. I use Retrofit as networking library combined with Gson. My question: It is enough to write the ImagePost and TextPost model classes separately and let Retrofit/Gson handle the rest ? Or should I copy/paste the output to http://www.jsonschema2pojo.org/ and get only one model class for the different items. I am asking because in the callback methods for the Retrofit request, I have to provide also the model … -
How to fix mixed content error in Swagger?
I am running Django RF backend application on Gunicorn. When trying to fetch data from Swagger I get "TypeError: Failed to fetch" In console this error is reported: Mixed Content: The page at 'https://****.com/swagger/' was loaded over HTTPS, but requested an insecure resource 'http://****.com/v2/products/'. This request has been blocked; the content must be served over HTTPS. I tried everything I found and could think of including: Adding secure_scheme_headers = { 'X-FORWARDED-PROTOCOL': 'ssl', 'X-FORWARDED-PROTO': 'https', 'X-FORWARDED-SSL': 'on'} to Gunicorn and USE_X_FORWARDED_HOST = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') to Django settings. But nothing helps. Swagger for Django: drf-yasg==1.12.1 -
nested serializer (depth/level 3) is it possible to connect 2 already connected serializer to another
trying to add 3rd nested serializer using django rest framework how to add 3rd nested realation in given code given below #models.py class Category(models.Model): cate_id = models.AutoField(primary_key=True) cate_name = models.CharField(max_length=45) class Meta: managed = False db_table = 'category' class SubCategory(models.Model): sub_cate_id = models.AutoField(primary_key=True) sub_cate_name = models.CharField(max_length=45) sub_fk = models.ForeignKey('Category', models.CASCADE, db_column='sub_fk') class Meta: managed = False db_table = 'sub_category' class Products(models.Model): pro_id = models.AutoField(primary_key=True) pro_name = models.CharField(max_length=45) description = models.CharField(max_length=45, blank=True, null=True) price = models.IntegerField() quantity = models.IntegerField() pro_cate_fk = models.ForeignKey('Category', models.CASCADE, db_column='pro_cate_fk') pro_sub_fk = models.ForeignKey('SubCategory', models.CASCADE, db_column='pro_sub_fk') image = models.CharField(max_length=205) class Meta: managed = False db_table = 'products' #serializer.py why cant they provide proper info from rest_framework import serializers from .models import Category,SubCategory,Products class ProductsSerializer(serializers.ModelSerializer): # x= ChildTable.objects.all().values class Meta: model = Products fields = ('pro_id','pro_name','description','price','quantity','image') class SubCategorySerializer(ProductsSerializer): products_set = ProductsSerializer(many=True, read_only=True) class Meta: model = SubCategory fields = ('sub_cate_name','sub_cate_id','products_set') class CategorySerializer(SubCategorySerializer): subcategory_set = ProductsSerializer(many=True, read_only=True,) # pro_subcate_set = SubCategorySerializer(many=True, read_only=True) class Meta(): model = Category fields = ('cate_name','cate_id','subcategory_set') got this error while attempting is it possible to connect 2already connected serializer to another serializer Got AttributeError when attempting to get a value for field `pro_name` on serializer `ProductsSerializer`. The serializer field might be named incorrectly and not match … -
Ajax call on Save in Django Admin
How to call Ajax on save and continue in the Django admin model? Any hack or third party for calling ajax on saving the model with all type of fields in Django admin? -
Unable to import some variables from django settings
I have set the DJANGO_SETTINGS_MODULE to be my settings file. Some sample lines of this settings file follow: TEST = { 'CLIENT': os.environ.get("CLIENT_NAME", "unknown"), 'ENVIROMENT': os.environ.get("ENVIROMENT", "unknown") } client_name = os.environ.get("CLIENT_NAME", "unknown") enviroment = os.environ.get("ENVIROMENT", "unknown") I then try to import the django settings by using from django.conf import settings as django_settings I am then able to print the value of the django_settings.TEST['CLIENT'] but not of the django_settings.client as I get 'Settings' object has no attribute 'client' What am I missing? To my the only difference is that TEST is a dict while client is a variable of string type. -
Passing string to server
I need to send string to the Django server. and after doing some operations with this line and return string, navigating to the page without reloading it. I did this with the help of a redirect to another page, I didn’t figure it out with Ajax server, who can tell you what is the best way to do it? -
Deploying Django for free
I created a project with django,and I want to deploy it. I prefer not to spend any money on webserver, host... Is it possible? How can I do that? By the way, I can't use Heroku. -
django clear GPU memory
I have NLP models which I am running it on GPU. Now I load the model at first django API call and keep it in the memory, as it takes time to load the model and I have to run it on multiple files. This works fine by setting the loaded model in global variable. I want to free the memory once I am done. How would I do that. I tried to do this but it didnt work as I see the same memory used when I do TOP class Unload_model(views.APIView): def post(selfself, request): global model del model torch.cuda.empty_cache() return Response([], status = status.HTTP_200_OK) I am setting up the gloabl variable like this: model = None class Predict(views.APIView): # init random seed random.seed(555) def post(self, request): for entry in request.data: # load the model global model serialization_dir = entry["serialization_dir"] params = Params.from_file(entry["config_file_path"]) if model == None: model = loadAllenNLPModelFromDisk("vocabulary", "best.th", params) cuda_device = 0 model = model.cuda(cuda_device) -
How to use ModelChoiceField in django rest framework?
I am trying to convert my form that was written earlier to django rest serializer but it does't work. Could you help me to solve this problem please? this is my form: class TripSearchForm(forms.Form): departure = PlaceModelChoiceField( queryset=Place.objects.places_for_segment(), widget=autocomplete.ModelSelect2(url="autocomplete") ) destination = PlaceModelChoiceField( queryset=Place.objects.places_for_segment(), widget=autocomplete.ModelSelect2(url="autocomplete") ) my serializer: class SearchSerializer(serializers.Serializer): departure = serializers.RelatedField(queryset=places_models.Place.objects.all(), label='departure') destination = serializers.RelatedField(queryset=places_models.Place.objects.all(), label='destination') -
Why is selenium-webdriver (LiveServerTestCase) still pointing at the wrong database?
I'm using Selenium to run some integration tests for a Django app (using postgres for the development database). I set-up the tests by creating a Model object. The tests then interact with the object through the browser (selenium-webdriver), or directly through database queries. The tests that use webdriver cannot access the Model object. The database queries can. I've come to the conclusion that webdriver is not being pointed at the correct database. I've tried using LiveServerTestCase both explicitly giving it the port and URL I want to use (localhost:8001) and using live_server_url to allow it to decide for itself. Neither have worked. Here's the form being tested - it's a simple select from a list of objects. forms.py class FooForm(form.Form): foo = forms.ModelChoice.Field( required=False, label='select', queryset=Foo.objects.all(), widget=forms.Select(), ) Here's the DB settings. settings.py DATABASES = { 'default':{ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'app', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '', } } Here are the tests. test.py from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.select import Select from django.test import LiveServerTestCase from app.models import Foo class BasicTestCase(LiveServerTestCase): def setUp(self): foo = Foo.objects.create(name='test_foo') self.selenium = webdriver.Firefox() super(BasicTestCase, self).setUp() def tearDown(self): self.selenium.quit() super(BasicTestCase, self).tearDown() def test_can_interact_via_db_query(self): self.assertEqual(Foo.objects.get(id=1).name, 'test_foo') def test_can_interact_via_webdriver_query(self): self.selenium.get('%s%s' … -
Best practice when add a new unique field to an existing django model
I have an existing model that looks somewhat like the following... class Resource(models.Model): id = models.AutoField(primary_key=True) We have been using this for some time, and now have ~1M instances of these Resource objects (and associated ForeignKey/else usages) in our database. I now have a need to track another ID on this model, one that I want to enforce is unique. other_id = models.IntegerField(unique=True) This other_id information is currently stored in some external CSVs, and I want to (at some point in the process) load this information in to all existing Resource instances. After adding the above field, Django's makemigrations works just fine. However when I go to apply said migration against an existing database I get an error indicating that I need to provide a default to use for all existing Resource instances. I'm sure many of you have seen something similar. What is the best approach to getting around this limitation? Some methods I have thought of... Remove the unique=True requirement apply the migration externally load in the other_id value to all existing models (through some management command, or 1-off script) add the unique=True back in and apply the migration Dump all existing data to JSON flush all tables … -
Specifiy one use allowed to edit
I am Developing a website which has a group of users that are accessing a room and only one of them can do some opeations like editing,adding I am trying to implement it with django-channels When a user send a POST or PUT request.It should be first asked if he can edit. -
Django & React behind PM2 and Gunicorn combined with Nginx
I am quite new to Django and React and to Web Development at all, I hope the following does not sound too stupid: I am using Django as a backend and React for a frontend. I am starting the react frontend using PM2 and accessing the Django backend via PM2. I also installed Nginx as a reverse proxy to redirect querys to * mydomain.toplevel/admin to the django admin * mydomain.toplevel/ to the react frontend The backend and frontend communicate via a REST api, using the DJANGO REST framework and Axios for React. My main question at the moment is: Is it possible to let the frontend and the backend communicate directly on the server, in order of not exposing the API to the internet? I guess not, because react, as a JS frontend, is executed on the client side - correct? Does this also hold if the React frontend is not served as static files (npm run-server build) but via PM2? -
How to serialize queryset result below?
I use django rawquery to get result from database: class arizakestirimi_func(ListAPIView): serializer_class = arizakestirimiserializer def get_queryset(self): queryset = isyeriarizabilgileri.objects.raw("""SELECT M.id as id,M.isyeri,DATE_PART('day',(M.tarih)::timestamp - (D.mindate)::timestamp) * 24 + DATE_PART('hour',(M.tarih)::timestamp - (D.mindate)::timestamp) + DATE_PART('minute',(M.tarih)::timestamp - (D.mindate)::timestamp) / 60 as datediff FROM arizakestirimi_isyeriarizabilgileri M INNER JOIN (SELECT DISTINCT ON (isyeri) isyeri, tarih as mindate, id as id FROM arizakestirimi_isyeriarizabilgileri ORDER BY isyeri, tarih ASC) D ON M.isyeri=D.isyeri WHERE M.durustahmini='MEKANIK ARIZA' AND M.isyeri='15400001'""") return queryset Serializer class for query result class arizakestirimiserializer(serializers.Serializer): isyeri = serializers.CharField(max_length=30) datediff= serializers.FloatField() The result json.I use ListAPIView to show json: [ { "isyeri": "15400001", "datediff": 2520.0 }, { "isyeri": "2520.0", "datediff": 700.0 }, { "isyeri": "15400001", "datediff": 704.0 } ] I want to get json: { "15400001":[ {"2520.0"}, {"700.0"}, {"704.0"} ] } -
How to send error responses back to client in django rest framework?
I am newbie to Django rest framework and trying to send custom error messages back to client, where I am using VueJS. I followed the answer given here but I am unable to receive error message on client side. client-side auth.phoneVerification(this.fullName, this.mobileNo, this.email) .then((response)=>{ console.log(response.data) }) .catch((error)=>{ console.log("Error is ", error) }) server-side serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = InterestedUser fields = ('full_name', 'phone_no', 'email') def __init__(self, *args, **kwargs): super(UserSerializer, self).__init__(*args, **kwargs) self.fields['full_name'].error_messages['required'] = 'Please provide your full name.' self.fields['phone_no'].error_messages['required'] = 'Please provide your mobile number.' self.fields['email'].error_messages['required'] = 'Please provide your email id.' views.py class UserView(GenericAPIView): serializer_class = UserSerializer def post(self, request): serializer = self.get_serializer(data=request.data) print("requested data is ", request.data) if not serializer.is_valid(): raise serializers.ValidationError(serializer.errors) print("serialiser errors are ",serializer.errors) In console I am unable to receive the message as provided by serializer.errors -
How to allow inactive user to login?
I use a custom user model(AbstractBaseUser). How to allow inactive user to login?. Model fields are email , active, admin,..... By default active= false. For email confirmation activation. But I want to allow user to login both with active= true or false. -
Can i do like this (django populate manytomanyfield)
I have 2 field for players team1player and team2player Also, i have winner and loser fields and I want to fill winner and loser fields with team1player field or team2player field Can I do it the shortest way? or should I write such code again. winner=models.ManyToManyField(Player,related_name='winner') team1player=models.ManyToManyField(Player,related_name='team1player') team2player=models.ManyToManyField(Player,related_name='team2player') winner=models.ManyToManyField(select team1player or team2player) loser=models.ManyToManyField(select team1player or team2player)