Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nginx 502. Bad Gateway but working with CORS. Should I use CORS in production?
Im trying to dockerize a Django App + React with Nginx and proxy pass the request to my backend with upstream. The issue im having is that if I do not enable cors and allow localhost:4000 within my backend the connection gets refused. Nginx throws: 2021/09/02 21:57:02 [error] 26#26: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.21.0.1, server: , request: "GET /api/users/me HTTP/1.1", upstream: "http://172.21.0.4:8000/api/users/me", host: "localhost:4000", referrer: "http://localhost:4000/" Side Note: I don't know where ... client: 172.21.0.1 ... from the log error above is coming from. I tried to set ALLOWED_HOSTS to ["*"], ["localhost", "localhost:4000", "127.0.0.1", "127.0.0.1:4000"] but it doesn't seem the problem is here. With CORS: CORS_ALLOWED_ORIGINS = [ "http://localhost:4000", "http://127.0.0.1:4000", ] It works just fine. I haven't tried to deploy the app with cors to test it in production So my questions are: Is this the right way of allowing traffic through my web server? Is it okey to have cors in production if it Here is my Nginx.conf: upstream backend { server backend:8000; } server { listen 8080; #mapping port 4000:8080 from docker-compose error_log /var/log/nginx/api.error.log; location /api { proxy_set_header host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-forward-for $proxy_add_x_forwarded_for; proxy_pass http://backend; } location /staticbe/ … -
import declarations may only appear at top level of a module and disallowed MIME type
I'm trying to load a script that includes an import statement, but Firefox shows the "import declarations..." error in the console. The import in my script looks something like this: import { foo } from './path/to/js/file'; I can get rid of this error by including type="module" as an attribute of the script tag in my HTML, but then I get a different error in the console: "Loading module from “http://localhost:8000/path/to/js/file” was blocked because of a disallowed MIME type (“text/html”)." It also shows a 404 in the console for the script I'm trying to import. Interestingly, I can get rid of both of these by appending .js to my import statement: import { foo } from './path/to/js/file.js'; But since file.js is part of a larger library with its own import statements, all subsequent import statements raise MIME type errors and 404s. I'm using Django as my backend framework and the application is in a docker container. What am I doing wrong? -
How to turn off django logging INFO to console?
For some reason I cannot figure out how to get django to stop spamming INFO level information to the console. I've tried logging.disable(logging.CRITICAL) in settings.py, as well as this dict in settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'root': { 'handlers': ['console'], 'level': 'INFO', 'propagate': False }, } Can anyone help me with this? Thanks! -
Django how can I redirect after post request result
def postDataRequest(request): if request.method == 'POST': username = request.POST['username'] userid= request.POST['userid'] if(userid== "21310"): context = { "result" : Dataengine(username,userid).dataFunc() } messages.add_message(request, messages.SUCCESS, context) return render(request, 'pages/dataresult.html', context) I show some data to users with post request.What I want to do is redirect 'pages/index.html' within 30 seconds after the user sees the result on the 'dataresult.html' page. How can I do that? -
Iterate over variable and insert additional rows Postgres
Just to note, yes I have seen similar questions on here but none quite close enough for the particular issue. I have a table (let's call it 'table 1') in postgres with three columns based on a django model, 'ID' (auto incrementing value), 'affiliation', and 'entry'. What I need to do is take every entry where affiliation = 52, and then add an additional row with entry = query.entry and affiliation = 48 (just to reiterate, I need additional rows, not changed values). I also need to make sure that the entry + affiliation pair don't already exist. No matter what I do I get a syntax error! Any help? The latest call was: do $$ declare id_array int[]; begin insert into id_array table_1.entry where table_1.affiliation = 52; for id in id_array loop if not exists (select entry from table_1 where affiliation = 48) then insert into table_1 (affiliation, entry) values (48, id); else raise notice "already exists"; end if; endloop; end; $$ Any ideas? I'm at a complete loss...This is by far the most complex query I've ever ran. -
How to use register users in django that are register in Laravel?
The website is develop in Laravel. I want to add some functionalities in it. Kindly help me to that how can i get Users in django that are register in Laravel? -
Django/Python change content.innerHTML to a src page
I am running a page that on a click, replaces the content in an iFrame. The JS in index.js looks like this: if (page == 'stationData') { content.innerHTML = '<h1>Station Data</h1>'; content.innerHTML += '<iframe class="site_data_tab" src="stationDataHTML.html"></iframe>'; } The old iFrame data goes away and the text "Station Data" appears as expected, but I can't figure out how to get the stationDataHTML.html page to appear in the iFrame. I've tried something like this: index.js: if (page == 'stationData') { content.innerHTML = '<h1>Station Data</h1>'; content.innerHTML += '<iframe class="site_data_tab" src="{% url \'data-stationData\' %}"></iframe>'; } urls.py: urlpatterns = [path('', AboutView.as_view(template_name="stationDataHTML.html")),] views.py: class AboutView(TemplateView): template_name = "stationDataHTML.html" When I run, and I click the button to change the iframe content, I recevie and error Not Found: /data/stationDataHTML.html [02/Sep/2021 16:02:04] "GET /data/stationDataHTML.html HTTP/1.1" 404 6279 Is there a a way to change the iframe content to a locally hosted page? (stationDataHTML.html) -
DRF Viewset - Return a 400 if object exists and a 200 if it doesn't
Using Django Rest Framework, I'm trying to create an API endpoint to determine if a given name of an item, already exists. If it does, then we should let the frontend app know by returning a 400 Bad Request. If it does not exists, then we send a positive 200 OK request. I find that I can send a 400 just fine but if the item doesn't exist, I get a 404 that I can do nothign about. views.py from rest_framework import viewsets,status from rest_framework.response import Response from .serializers import * class ItemCheckViewSet(viewsets.ModelViewSet): """ The views that are returned when we peform checks against the items """ lookup_field = 'name' queryset = Item.objects.all() def get_serializer_class(self): return ItemSerializer def retrieve(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance) if len(serializer.data) > 0: return Response("Item already exists", status.HTTP_400_BAD_REQUEST) return Response("Item does not exist", status.HTTP_200_OK) serializers.py from rest_framework import serializers from .models import Item class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = "__all__" -
Django objects.get for loop issue
I'm trying to do a for loop 1 through 100 into a primary key (pk) for an objects.get in django. I keep getting a matching query does not exist. I assume the django isn't reading the output as an int. def f_factory(i): def f(offset): nonlocal i i += offset return i for i in range(3): an = djangonote.objects.get(pk=i) print(an.id) -
How to override div wrapper class of ckeditor Django?
Cant find a way to override ckeditor base wrapper div class. By default it has html template like this: https://i.stack.imgur.com/8gZUJ.png Is there a way to change class name "django-ckeditor-widget" to something else? Was trying to do: class PostAdminForm(forms.ModelForm): content = forms.CharField(widget=CKEditorWidget(), attrs={'class': 'MyCustomClass}) class Meta: model = Post But this dosnt work -
When to run a command in docker compose and when in dockerfile?
I am somehow newbie in docker, so bear with me for a potentially stupid question. From what I understood, if I want to have a running container and not an executable, you end it up with a "command". Okey. So if what I want is a container serving a django app, I have to add something like: python manage.py runserver 0.0.0.0:8000 Now the question is: Do we add this at the end of the dockerfile that defines the image? Or do I add this command in the docker compose that uses the image, like this? services: web: build: . command: python manage.py runserver 0.0.0.0:8000 [...] -
Is it possible to send a request to django rest api to run a script?
I installed Django and Django Rest Api. I want to send some data to rest api. Rest api will take the data and run a script with this data and get a result. Then send this result back to me. There won't be database usage. Like this, request : http://testerapi.com:8000/search?q=title:xfaster564CertVal9body:A%22&fl=id Response : {validation : true} Is it possible? -
How to append specific html to a Django code block using only Python/Django?
I have a form I'm working with in Django. I have a built in error message I'm trying to get to render on the form. My first step is to get the error message to render on the form and then I will go into the function and tweak when it shows up. My problem emerges when it comes to doing it in python. Normally, my preferred way would be to JQuery for the footer and use JavaScript to append/prepend the HTML. Then set it to show/hide based on conditionals. However, for this I am wanting to do it in Python to make it easier for the people working w/ me. Here's an example of the error message HTML I would like to use for appending to something else in JS. error_field.append('<em for="name" class="form-error-message text-danger">'); Here is an example of the Django Code Block I would like to add it within {% block form-footer %} {{ block.super }} {% endblock %} What is the easiest way to accomplish this within Python/Django? To be clear, I can figure out the conditional stuff myself. Just the rendering of the specific HTML/CSS error class I have already created. I should be able to … -
How to dynamically change Django Form field type (e.g. `forms.CharField` to `forms.ChoiceField`) without changing the data member variable?
TL;DR How can I change the search term CharField (of any of the rows in the image below) to another field type (e.g. ChoiceField, DateField, etc) based on the type of the selected database field (in the first select list on that row - see screenshot below)? Long version I have a cool hierarchical advanced search interface, e.g.: Each row specifies a search term/condition and reads as a search, like: <field> <condition> <term> e.g. age > 5 where the form field names are: fld (for "database field") ncmp (for "negatable comparison type") val (for the search term) There is a hidden field called pos for the hierarchy and group type data, but that's irrelevant to my question. Rows and subgroups can be dynamically added/removed to/from the hierarchy and can be and-ed or or-ed together. It works great. But the problem I want to solve is that it is somewhat limited by field type. I would like to be able to dynamically change the contents of the condition select list (ncmp) and the type of search term field (val) based on the selected database field (fld) (or the selected condition, e.g. if isnull: hide the term field). Here are some examples … -
Use Django's login_required decorator code inside a view function?
I want to write a view in Django (3.2) that allows any user to enter a value, and only after that has been submitted to require login (or signup!). Something like follows: def my_view(request): if request.GET.get('val', None): # now login is required to do something # can we use the login_required decorator here # to forward to login, and then back here after login? else: # login is not yet required # ... a form to gather up 'val' Can I re-use the login_required decorator in some clean way in the middle of the function? I could copy and paste its code (and the code of user_passes_test), but copy-and-paste seems unfortunate. -
Django Rest Framework, How do I grab a foreign key value and add it to my serializer or view to create a new object?
models.py User model it the import auth user model from django class Profile(models.Model): username_id = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) phone_number = PhoneNumberField(blank=True, null=True) image_url = models.ImageField(blank=True, null=True) address = models.CharField(max_length=30) update = models.DateTimeField('Updated at', default=timezone.now()) def __str__(self): return self.username_id.__str__() views.py @api_view(['POST']) def profile_create(request, pk): request serializer = ProfileCreateSerializer(data=request.data) # print(serializer) if serializer.is_valid(): serializer.save() else: return Response(serializer.errors) return Response(serializer.data) serializers.py class ProfileCreateSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['phone_number', 'image_url', 'address'] I want to create a new profile for a user put I don't know where or how to pass the foreign key value to the serializer or view to create a new profile error django.db.utils.IntegrityError: null value in column "username_id_id" of relation "users_pr ofile" violates not-null constraint DETAIL: Failing row contains (, , HELLLfwfwefwf, 2021-09-02 20:08:58.53219+00, null). -
Stripe Django no such price
I have a problem with my Django Stripe Checkout. I tried to make checkout with pricing of items from my e-commerce website but i get an error from Stripe. ERROR: Request req_wfYpUxo6bE40lR: No such price: '2.00' Models.py class Item(Visits, models.Model): title = models.CharField(max_length=150) price = models.DecimalField(max_digits=6, decimal_places=2) image = models.ImageField(upload_to='pictures', default='static/images/man.png') description = models.TextField(default="Item") visits = models.IntegerField(default=0) views.py @csrf_exempt def create_checkout_session(request): if request.method == "GET": try: item = Item.objects.get(title='Kola') checkout_session = stripe.checkout.Session.create( line_items=[ { # TODO: replace this with the `price` of the product you want to sell 'price': item.price, 'quantity': 1, }, ], payment_method_types=[ 'card', 'p24', ], mode='payment', success_url=request.build_absolute_uri(reverse('success-page'))+ '?session_id={CHECKOUT_SESSION_ID}', cancel_url= request.build_absolute_uri(reverse('cancel-page')), ) except Exception as e: return HttpResponse(e) return redirect(checkout_session.url, {'item': item}, code=303) -
AttributeError: module 'htmlmin.middleware' has no attribute 'MarkRequestMiddleware'
Trying to deploy my Django Application in Heroku Platform including htmlmin and gzip the application crashed with H10 error code. Inspecting log looks like that the error is related to AttributeError: module 'htmlmin.middleware' has no attribute 'MarkRequestMiddleware' Running locally works perfect (I don´t know why), but after deployment in Heroku Platform the Application doesn´t work. Here is the settings.py code: MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", 'django.middleware.gzip.GZipMiddleware', "htmlmin.middleware.HtmlMinifyMiddleware", "htmlmin.middleware.MarkRequestMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ... HTML_MINIFY = True Here is my requirements.txt file: django django_compressor htmlmin gunicorn django-heroku pip==21.0.1 numpy==1.19.1 wordcloud==1.8.1 requests==2.24.0 urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 matplotlib==3.3.4 wikipedia-API==0.5.3 livereload>=2.6.1 whitenoise>=5.0 Here is the Tail Log in Heroku App. 2021-09-02T18:56:35.730191+00:00 app[web.1]: mod = importlib.import_module(module) 2021-09-02T18:56:35.730191+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module 2021-09-02T18:56:35.730192+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2021-09-02T18:56:35.730192+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import 2021-09-02T18:56:35.730193+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load 2021-09-02T18:56:35.730193+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked 2021-09-02T18:56:35.730193+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked 2021-09-02T18:56:35.730194+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 850, in exec_module 2021-09-02T18:56:35.730194+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed 2021-09-02T18:56:35.730194+00:00 app[web.1]: File "/app/biblestatistic/wsgi.py", line 16, in <module> 2021-09-02T18:56:35.730194+00:00 app[web.1]: application = get_wsgi_application() 2021-09-02T18:56:35.730195+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/wsgi.py", line 13, in … -
Sort a tsv by date with python script
How can I reorder the arrangement of values in my TSV to be sorted by date. The current arrangement is by the first column, but I want to overwrite the file with the same data only arranged by date. The current format is as shows: param1 | param2 | param3 | date | param5 | param6 | Sample content: 1000045|sample 1|10-Q|2021-02-11|edgar/data/1000045/0001564590-21-005399.txt|edgar/data/1000045/0001564590-21-005399-index.html 1000045|sample 1|4/A|2021-02-12|edgar/data/1000045/0001398344-21-003309.txt|edgar/data/1000045/0001398344-21-003309-index.html 1000045|sample 1|4|2021-02-08|edgar/data/1000045/0001496701-21-000001.txt|edgar/data/1000045/0001496701-21-000001-index.html 1000045|sample 1|4|2021-02-09|edgar/data/1000045/0001398344-21-002769.txt|edgar/data/1000045/0001398344-21-002769-index.html 1000045|sample 1|8-K|2021-01-25|edgar/data/1000045/0001564590-21-002004.txt|edgar/data/1000045/0001564590-21-002004-index.html 1000045|sample 1|8-K|2021-02-03|edgar/data/1000045/0001564590-21-003940.txt|edgar/data/1000045/0001564590-21-003940-index.html 1000045|sample 1|8-K|2021-03-08|edgar/data/1000045/0001564590-21-011365.txt|edgar/data/1000045/0001564590-21-011365-index.html 1000045|sample 1|SC 13G/A|2021-02-08|edgar/data/1000045/0001104659-21-013485.txt|edgar/data/1000045/0001104659-21-013485-index.html 1000045|sample 1|SC 13G/A|2021-02-11|edgar/data/1000045/0001037389-21-000122.txt|edgar/data/1000045/0001037389-21-000122-index.html 1000045|sample 1|SC 13G/A|2021-02-12|edgar/data/1000045/0000354204-21-000071.txt|edgar/data/1000045/0000354204-21-000071-index.html 1000097|sample 2|13F-HR|2021-02-16|edgar/data/1000097/0001000097-21-000004.txt|edgar/data/1000097/0001000097-21-000004-index.html 1000097|sample 2|SC 13G|2021-01-11|edgar/data/1000097/0000919574-21-000165.txt|edgar/data/1000097/0000919574-21-000165-index.html 1000177|sample 3|SC 13G/A|2021-01-29|edgar/data/1000177/0000834237-21-004594.txt|edgar/data/1000177/0000834237-21-004594-index.html I tried using bash but it needs to run at the same time as the script I will use. The current script I have is like this: def edgar_filings_download(date): try: # code to rearrange the file with open(edgar_path + filename, 'r') as file: tsv_file = list(csv.reader(file, delimiter='|')) _CHECK = datetime.datetime.strptime(date, "%Y-%m-%d") start_date = datetime.datetime.strptime(tsv_file[len(tsv_file) - 1][3], "%Y-%m-%d") end_date = datetime.datetime.strptime(tsv_file[0][3], "%Y-%m-%d") if start_date <= _CHECK <= end_date: logger.debug('pass') else: logger.debug('no pass') except Exception as e: logger.error(e) As you may see, I am using the first and last lines as the range of the dates I want to check so I don't have to check line by line. Any help is … -
Django, GraphQL, Mongo - graphene-mongo the only possibility?
I was planning on building a new software using 3 popular technologies: Python, MongoDB and a GraphQL API (Frontend with Angular, but that is not the focus of this post). Although a combination of these three technologies should not be that rare it seems as though the support is extremely limited. The only framework combining these technologies that I have found graphene-python. The support for flask is super limited, the support for django is okay. BUT: I am not sure as to what is happening right now. The last release of graphene-python was more than one year ago. Issues are not answered for multiple weeks. Using it I have experienced multiple issues that seem to have been fixed partially in the repository but not in the official package. Am I missing something? This is not meant to be critique, I am just not sure as to whether I should base our new architecture on that framework. Is there a different framework for that techstack? I know that developing a graphql API could also be done manually but it just doesn't sit right with me. -
How can I properly request.POST of a form with one-to-one relationship?
I'm still getting an error "ModelForm has no model class specified." although I already specified the model in class Meta in DetailForm. How can I properly request.POST of a form with one-to-one relationship? #model.py class Component(models.Model): partnumber = models.CharField(max_length=100) maker = models.ForeignKey(Maker, on_delete=models.RESTRICT, null=True) class Description(models.Model): component = models.ForeignKey(Component, on_delete=models.CASCADE, related_name='descriptions') text = models.CharField(max_length=300) def __str__(self): return self.text #form.py class ComponentForm(forms.ModelForm): class Meta: model = Component fields=['partnumber','maker', 'description'] class DetailForm(forms.ModelForm): class Meta: models = Detail fields=['modelseries'] #form.py @login_required def edit(request,id): #Get the current component to edit comp = Component.objects.get(pk=id) comp_detail = comp.detail if request.method == 'POST': c_form = ComponentForm(request.POST, instance=comp) cd_form = DetailForm(instance=comp_detail) if c_form.is_valid and cd_form.is_valid: c_form.instance.author = request.user c_form.save() messages.success(request, f'Component has been updated!') return redirect('component-index') else: c_form = ComponentForm(instance=comp) cd_form = DetailForm(instance=comp_detail) context ={ 'c_form':c_form, 'cd_form':cd_form } return render(request, 'component/edit.html',context) -
Django filter by date range but exclude the year
I know that if I want to filter results by date range, I just use something like Sample.objects.filter(birthday__range=(start_date, end_date)) But how would I filter by a date range that excludes the year? -
Which version of django should I start learning? [closed]
Currently supported versions: I read that there may be some problems due to the version. -
django item have bigger len after applying another filter
As showned bellow, I try to apply new filter to my idmatch queryset. But it return a new queryset with more objects than in the first one. idmatch = IdMatch.objects.filter(idsport=idsport) idmatchcount = idmatch.count() idmatch_liematch = idmatch.filter(match__isnull=False) count = idmatch_liematch.count() print(idmatchcount, count) 605 634 I don't understand how it can be possible that I got a bigger lenght after applying a new filter. The relation between IdMatch and Match is : class IdMatch(models.Model): match = models.ManyToManyField(Match) Ps : I check the 'idmatch_liematch' queryset and it got some pk witch are double... Do someone know why and if it is possible to do the same without any double pk. Thanks -
How to change required = false to an input that is required
My html file has a select, with three different options. If you select one it will display different inputs depending on what option you choose, but this inptus are required by default, and I can't send the form if I don't fill all the inputs. js function yesnoCheck(that) { if (that.value == "1") { document.getElementById("ifStudent").style.display = "block"; } else { document.getElementById("ifStudent").style.display = "none"; } if (that.value == "2"){ document.getElementById("ifAcademic").style.display = "block"; } else { document.getElementById("ifAcademic").style.display = "none"; } if (that.value == "3"){ document.getElementById("ifWorker").style.display = "block"; }else{ document.getElementById("ifWorker").style.display = "none"; } } This is on HTML file <div class="select"> <select onchange="yesnoCheck(this);" name = "school_role" required> <option value="">--------</option> <option value="1">Student</option> <option value="2">Academic</option> <option value="3">Employee</option> </select> </div> <div id="ifStudent" style="display: none;"> <label class="label">Account number</label> <input class="input" type="text" name="account_number" value="{{ studentform.account_number.value }}" placeholder="Account number"> <div class="help is-danger"> {% for error in studentForm.account_number.errors %}{{ error }}{% endfor %} </div> <div id="ifEmployee" style="display: none;"> <label class="label">Employee Number</label> <input class="input" type="text" name="employee_number" value="{{ employeeForm.employee_number.value }}" placeholder="Employee number"> <div class="help is-danger"> {% for error in employeeForm.employee_number.errors %}{{ error }}{% endfor %} </div> <div id="ifAcademic" style="display: none;"> <label class="label">Academic number</label> <input class="input" type="text" name="academic_number" value="{{ academicForm.academic_number.value }}" placeholder="Academic number"> <div class="help is-danger"> {% for error in academicForm.academic_number.errors %}{{ error …