Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to resolve SMTP error while sending email in django?
I have deployed my django project successfully on a server but i have having an issue, Whenever i register new user, It returns the following traceback: Traceback (most recent call last): File "/home/ubuntu/dotescrow/myprojectenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/ubuntu/dotescrow/myprojectenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/dotescrow/myprojectenv/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/home/ubuntu/dotescrow/myprojectenv/lib/python3.8/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/home/ubuntu/dotescrow/dotescrow_main/accounts/views.py", line 51, in post user.email_user(subject, message) File "/home/ubuntu/dotescrow/myprojectenv/lib/python3.8/site-packages/django/contrib/auth/models.py", line 380, in email_user send_mail(subject, message, from_email, [self.email], **kwargs) File "/home/ubuntu/dotescrow/myprojectenv/lib/python3.8/site-packages/django/core/mail/__init__.py", line 61, in send_mail return mail.send() File "/home/ubuntu/dotescrow/myprojectenv/lib/python3.8/site-packages/django/core/mail/message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/ubuntu/dotescrow/myprojectenv/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages new_conn_created = self.open() File "/home/ubuntu/dotescrow/myprojectenv/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 69, in open self.connection.login(self.username, self.password) File "/usr/lib/python3.8/smtplib.py", line 734, in login raise last_exception File "/usr/lib/python3.8/smtplib.py", line 723, in login (code, resp) = self.auth( File "/usr/lib/python3.8/smtplib.py", line 646, in auth raise SMTPAuthenticationError(code, resp) Exception Type: SMTPAuthenticationError at /accounts/signup/ Exception Value: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbt\n5.7.14 pHaElEUTuIMKjGk_0IzO_HxLrVh9yMT7UqnNvrxOgU3my55CdagEe5S1ajgmVozLXO5Tm\n5.7.14 5cgniqTT9lFr3rhyMprFMkfuoOoCKfFGkUx5y9JKEaGr1VkXLIMdb6IFo_gjEoXT>\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 z16sm9400103pgj.51 - gsmtp') locally everything is working fine but on the server this is happening , I dont understand whats the matter , … -
Update Jquery Nestable List In Django View
I have an application on Django and I had some information about JQuery Nestable List. When I change to drag or drop the item it will give output like in Django console : [{'name': 'Home', 'id': 264}, {'name': 'About', 'id': 265, 'children': [{'name': 'Product', 'id': 266}]}] So I just want to update my Django-MTTP model in my view. How can I make connections between Jquery Nestable List children and the MTTP parent field? My MODEL class Menu(MPTTModel): name = models.CharField(max_length=50) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') def __str__(self): return str(self.name) JQUERY jQuery.noConflict()(function ($) { $(document).ready(function(){ var csrftoken = getCookie('csrftoken'); var updateOutput = function(e){ var list = e.length ? e : $(e.target),output = list.data('output'); json_response = JSON.stringify(list.nestable('serialize')); $.post('myurl/menu/create_menu',{data:json_response,'csrfmiddlewaretoken':csrftoken}); }; $('#nestable').nestable({ group: 1, maxDepth: 2, }) .on('change', updateOutput); updateOutput($('#nestable').data('output', $('#nestable-output'))); }); }); MY VİEW def create_menu(request): data = json.loads(request.POST.get('data', '')) print(data) return HttpResponse("Ok") -
How do you create a model using opencv in django?
Anybody know who to integrate django and opencv(cv2) together. My goal is to create an model that can store the user and a picture of them. I first tried just using UserPicture.objects.create(user=request.user, picture=image) but that wouldn't work because the function was not taking request as a parameter. Should I create an APIView somehow? Anyways, here is the code I am using for the opencv class: def __init__(self): self.video = cv2.VideoCapture(0, cv2.CAP_DSHOW) def __del__(self): self.video.release() def create_facial_boundary(self, image, cascadeClassifier, color, emotion): grayScaled = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) face = cascadeClassifier.detectMultiScale(grayScaled, 1.1, 10) coords = [] for (x, y, w, h) in face: cv2.rectangle(image, (x, y), (x + w, y + h), color) roi_gray = grayScaled[y : y+h, x: x+w] cv2.putText(image, emotion, (x, y-4), cv2.FONT_HERSHEY_PLAIN, 2, (255, 255, 255)) coords = [x, y, w, h] self.update_time() return coords, image def detect_face(self, image, cascadeClassifier): color = {"green" : (0, 145, 25)} coords, image = self.create_facial_boundary(image, cascadeClassifier, color["green"], "ExText") image = cv2.flip(image, 1) return image def update_time(self): time.sleep(5) def get_user_face(self): success, frame = self.video.read() # img_file = "User-Face.jpg" frame = self.detect_face(frame, cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')) new_frame = cv2.flip(frame, 1) _, image = cv2.imencode(".jpg", new_frame) return image def get_user_emotion(): pass def get_frame(self): success, frame = self.video.read() image_flip = … -
Can not get my static style sheet to connect to my html using django
so i am having weird issue with my static css in the newest django. It is only changing to color on my <h1> the rest is totally unchanged. The static folder is in the root of the project. here is my css h1{ color: red; text-align: center; background-color: black; margin-left:150px; } body{ background-color: lightblue; } .container{ width:100%; } .products{ display: inline-block; width: 30%; } h5{ color:red; } here is the html i am trying to change {%extends "base.html"%} {%block content%} <div class="container"> <!-- for loop to render each product --> {%for product in product_list%} <!-- <h1>test</h1> --> <div class="products"> <ul> <h5>{{product.title}}</h5> <li>Price:{{product.price}}</li> {% if product.available %} <li>In stock</li> <li> Amount in Backstock:{{product.quantity}}</li> <li>Sell by Date:{{product.date}}</li> {%else%} <li>Out of Stock</li> {% endif %} <a type="button" class="btn btn-secondary"href='/product/{{product.id}}/update'> update </a> <a type="button" class="btn btn-danger" href='/product/{{product.id}}/delete'> delete </a> </ul> </div> {%endfor%} </div> {%endblock%} here is my static and static_dir STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", '/var/www/static/', ] -
Why fields are missing in django while using forms
I want to add data to my model through a form For that purpose my I have created the following form file in forms.py class Organization_Profile_Form(forms.ModelForm): class Meta(): model = Organization_Profile fields = ['organization_profile_pic', 'organization_slogan', 'organization_bio', 'organization_email', 'organization_contact', 'Service_type', 'category', 'city', 'status', 'scale'] This form is using the model class Organization_Profile(models.Model): organization = models.OneToOneField(Organization,on_delete=models.CASCADE,primary_key=True, related_name='Organization') organization_profile_pic=models.ImageField(default='default.jpg', upload_to='organization_profile_pics') organization_slogan=models.CharField( max_length=100) organization_bio=models.CharField( max_length=400,null=True) organization_email = models.EmailField(max_length=254,null=True) organization_contact = models.IntegerField(null=True) Service_type = models.CharField(max_length=50,choices=SERVICE, default='PART',blank=True) category = models.CharField(max_length=50,choices=CATEGORY, default='LABOUR_AGENCY',blank=True) city= models.CharField(max_length=200,null=True) date_created = models.DateTimeField(auto_now_add=True, null=True,) status = models.CharField(max_length=200, default='Pending', choices=STATUS) scale = models.CharField(max_length=200,default='SMALL', choices=SCALE) I have created options for status scale etc, not showing it because of extra detailing My view for this form is @login_required def Organization_Profile_View(request): if request.user.is_organization==False: return HttpResponse('Sorry!! This page requires organization previlidge') else: profile_submitted = False organization = request.user.Organization if request.method=='POST': form = Organization_Profile_Form(request.POST) if form.is_valid(): upload = form.save(commit=False) upload.organization = organization upload.save() profile_submitted=True else: form = Organization_Profile_Form() return render(request, 'organization/organization_profile_form.html', {form:'form', profile_submitted:'profile_submitted'}) and the html file this view is reffering to is {% extends "organization/index.html" %} {% load crispy_forms_tags%} {% block content %} <form method="POST"> <h1>Organization Profile Form</h1> {% csrf_token %} <fieldset> {{ form|crispy }} </fieldset> <button type="submit">Submit</button> </form> {% endblock content %} Now the problem is I … -
is a Django model with 800 fields bad design?
This is more of a database design question. I have a Django application that manages consumer data, so, there is 800+ data points on a given consumer. I am not sure what the best way to translate this into a django model is? The current option I have implemented is: class Consumer(models.Model): name=models.CharField(max_length=100, unique=True) address=models.CharField(max_length=100, unique=True) state=models.CharField(max_length=100, unique=True) country=models.CharField(max_length=100, unique=True) income=models.CharField(max_length=100, unique=True) owns_vehicle=models.BooleanField() # 800+ more fields This way works well, as it is easy to filter using Django Filters and there are few table joins so it is performant. However, I am wondering if there would be a better, more performant, or more maintainable way to accomplish this? Maybe using a JSONField and ForeignKey relationships? class Consumer(models.Model): name=models.CharField(max_length=100, unique=True) address=models.CharField(max_length=100, unique=True) state=models.CharField(max_length=100, unique=True) country=models.CharField(max_length=100, unique=True) class DataPoint(models.Model): consumer = models.ForeignKey(Consumer, on_delete=models.CASCADE) column_name = models.CharField(max_length=100, unique=True) value = models.JSONField() However, this is an API, that is reliant on filtering through URL calls, and this method would create more work in building custom filters since the dataset should be able to be filtered by each data point. What is the best way to Translate consumer data with more than 800 columns into a Django model? -
Django functional testing access production database
Is it somehow possible to access my production database in Django selenium functional testing? Let's assume that I have created a library app. In the app there is a button allowing the user to check number of books available. This function will then check with the database the number of available books. In the Django functionality test, can I test this functionality. If I use the test database there will be no books in it. I can of cause, in the test, added books to the test database but I would still like to know if I access the production database? -
Overload of logs from Django-Docker
I'm usually watching the the logs of my Django-Docker by using docker logs django_web_1 -f. Which would only display the set logging and errors, yet (probably due to an upgrade) I'm receiving an overly unusual amount of all kinds of messages which won't stop being outputted and I have difficulties to categorize. The Django-Docker is only used by me and not to be accessed from the internet. At this point it's just running idle, so there's no request coming from me. I can't post the entire log as it exceeds a few Megabytes on each call. Doing an ordinariy start-up of the docker by docker-compose up gives me the regular logs: web_1 | INFO:django.utils.autoreload:Watching for file changes with StatReloader web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). web_1 | January 22, 2021 - 20:07:39 web_1 | Django version 3.1.3, using settings 'DjangoMoP.settings' web_1 | Starting development server at http://0.0.0.0:9900/ web_1 | Quit the server with CONTROL-C. The new logs are also presnet in the specified Django-Handlers. What is the background of these logs and why am I getting them? INFO:django.server:"GET / HTTP/1.1" 200 33226 WARNING:django.request:Not Found: /client/ ---------------------------------------- Exception happened during processing … -
Loading fixture after migrating from auto-generated primary keys to slug primary keys. AttributeError: Problem installing fixture
I've updated my models to use slugfields as primary keys. I've modified the fixtures for the models so they are pointing to the correct field/model for any ManyToMany fields and ForeignKeys. Ie: app.model.settings is a ManyToMany field referencing another model that now uses SlugField as PK. // Before { "model": "app.model", "pk": "Test", "fields": { "settings": [ 8, 9, 10, 11 ] } }, // After { "model": "app.model", "pk": "Test", "fields": { "settings": [ "slug-value8", "slug-value9", "slug-value10", "slug-value11" ] } }, However I'm running into an issue when I try to load the fixture. AttributeError: Problem installing fixture '/project/app/fixtures/app.json': 'ManyToManyField' object has no attribute '_m2m_reverse_name_cache' I've searched everywhere I can think of an I'm not sure where this issue is coming from. I'm assuming it is directly related to the ManyToMany fields I have, but other than that I haven't found much on the error. -
Django Microsoft Authentication Backend not succeeding on new deployments
I have an app deployed in many places and it uses Django Microsoft Authentication Backend. Starting yesterday when we deploy the app the auth is now not working. We get back Failed to authenticate you for an unknown reason. Please try again later. We can see in the azure logs that the login was successful. We have the same version of Django Microsoft Authentication Backend installed, but for some reason on newly built boxes it is failing but older ones it is succeeding. What could be causing this? What can we check to track down what the issue may be? -
How can I download the file linked with the post?
I'm quite new to using Django and I am trying to develop a website where the user can download file at the end of the post. Post model: class Article(models.Model): title = models.CharField(max_length=30) content = models.TextField() pub_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) file = models.FileField(upload_to='code_files/') def __str__(self): return self.title I have a views: def download(request): response = HttpResponse(open(f"media/code_files/tests.py", 'rb').read()) response['Content-Type'] = 'text/plain' response['Content-Disposition'] = f'attachment; filename=tests.py' return response How can I download the file linked with the post? -
Django ajax comment reply
Please answer the bellow question: Django jquery ajax comment reply create multiple values -
Django 3, how to tell ModelViewSet that a certain field is not required?
So I have a reservation modelviewset, which calls a serializer that takes a user, room, start time and end time and when I run it it keeps saying the user is required. I think this is Django processing the request data and stopping, but if it actually ran my code it would realize i actually fetch that required field when creating (I fetch the logged in user, so I don't need the request to specify it) How do i tell django that the user is not required in the data of the request? If code actually needed for this I can post, but I'm thinking it's a quick fix? -
How to execute insert into in django with raw sql commands from a html form
I'm using Django and I have a form in html which gets the data to store in the database, I would like to know how can I insert this data without using ORM, just pure SQL commands. Do I have to create a model? Does anyone have any example? -
function in Django behaves differently
I have a function named localtime(ltz, /) to calculate users' local time. Outside of Django it works, but I get localtime takes 0 positional arguments but 1 was given error inside of Django. Here's the function UTILITY.PY def localtime(ltz, /): utc_now = datetime.datetime.now(tz=pytz.UTC) return utc_now.astimezone(pytz.timezone(ltz)) VIEWS.PY .... qs = Users.objects.filter(id=self.request.user).values() for val in qs: local_time = localtime(val['time_zone']) print(local_time) .... Can anyone help figure out why I'm getting localtime takes 0 positional arguments but 1 was given error in Django? Thank you in advance. -
How to configure Microsoft Pylance to not use stub files (.pyi) for django?
I am doing Django development using visual studio code on mac os with microsoft's pylance extension installed. Following is the version specification of my eco system : OS -> MacOS Mojave django -> 3.1.5 visual studio code -> 1.52.1 Microsoft Pylance -> 2021.1.2 Release (latest) We use JSONField from django's 3.1.5 version. Pylance use stub files for django located at extensions/ms-python.vscode-pylance-2021.1.2/dist/bundled/stubs/djano/db/models/__init__.pyi I can clearly see that stubs file mentioned is not up-to-date. Because of that, vscode is not able to resolve reference to models.JSONField. While for other libraries like jsonschema , it simply relies on their __init__.py. That's what I want. I checked what all can be configured on official page of Pylance but I did not find any suitable configuraiton. https://marketplace.visualstudio.com/items?itemName=ms-python.vscode-pylance I am considering following options : Delete stubs file/directory for django, I don't know what will be repercussions. Manually setting python.analysis.extraPaths to my virtualenv path. I am looking for a more organic solution and I'll provide the result of the above experiments in the comments. Thanks ! -
Django application Logs not showing in Heroku
I have a Django application deployed on Heroku. I am using the default logging module, and my logs show normally in development, both when DEBUG is True and False. Though, I am unable to see the logs when deployed to heroku with the command heroku logs --tail. Here is the content of my settings.py file: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '{levelname} [{asctime}] module:{module} - {message}', 'style': '{', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'simple', 'stream': sys.stdout, }, }, 'loggers': { # I tried replacing this with 'root' '': { 'handlers': ['console'], 'level': 'DEBUG', }, } } In my files such as views.py: import logging logger = logging.getLogger(__name__) logging.debug('something...') And finally, in my Procfile: release: python manage.py migrate --settings=myapp.deploy_settings web: gunicorn myapp.wsgi --log-file - I also tried with web: gunicorn myapp.wsgi --log-file=- as mentioned in a StackOverflow post, without success. What is causing this? -
How to provide requested user in initial values with django ModelForm and assign the form in django admin
I'd like to create articles with ModelForm and generic CreateView without choosing my user as author. Author should be the requested user. I know it can be solved in multiple ways, but I'd like to solve it with a form that I can use everywhere (django-admin and views). So far, I've tried this: models.py class Article(TimeStampedModel): ... author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = RichTextUploadingField(config_name='default') status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') ... forms.py class ArticleCreateForm(forms.ModelForm): class Meta: model = Article fields = [ 'title', 'featured_image', 'content', 'status' ] author = forms.IntegerField(widget=forms.HiddenInput) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) user_field = kwargs.get('instance') self.fields['author'].initial = user_field.id views.py class ArticleCreateForm(forms.ModelForm): class Meta: model = Article fields = [ 'title', 'featured_image', 'content', 'status' ] author = forms.IntegerField(widget=forms.HiddenInput) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) user_field = kwargs.get('instance') self.fields['author'].initial = user_field.id It renders the form, but instead of saving the article, it throws this error: File "/home/tareq/Desktop/PERSONAL/Blog/blog/blog/articles/forms.py", line 19, in __init__ self.fields['author'].initial = user_field.id AttributeError: 'NoneType' object has no attribute 'id' ERROR 2021-01-23 00:58:31,533 log 85374 140159710901824 Internal Server Error: /new/ Traceback (most recent call last): File "/home/tareq/.local/share/virtualenvs/Blog-i5phkViF/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/tareq/.local/share/virtualenvs/Blog-i5phkViF/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/tareq/.local/share/virtualenvs/Blog-i5phkViF/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, … -
Dropzone.js blocks "return render" call from Django
I am writing a website with drag and drop upload using Dropzone.js and Django. Dropzone.js is blocking somehow the return render call from Django. I tried a lot but couldn't disable it. Any help appreciated. views.py: def upload(request): if request.method == 'POST': uploaded_file = request.FILES['file'] file_obj = File.objects.create(file=uploaded_file) return render(request, 'uploadapp/nextpage.html') return render(request, 'uploadapp/upload.html') upload.html {% extends "base.html" %} {% load static %} {% block title %}Upload{% endblock %} {% block head_scripts %} <script src="{% static 'uploadapp/custom_dz.js' %}" defer></script> <script src="{% static 'uploadapp/dz/dist/dropzone.js' %}"></script> {% endblock %} {% block content %} <section class="bg-light text-center"> <div class="container"> <div class="row"> <div class="col-xl-10 mx-auto"> <h2 class="mb-4">upload</h2> </div> <div class="col-md-10 col-lg-8 col-xl-9 mx-auto"> <form action="{% url 'upload'%}" method="POST" class="dropzone dz" id="testdropzone" enctype="multipart/form-data"> {% csrf_token %} <div class="fallback"> <input name="file" type="file"> <button type="submit">Upload</button> </div> </form> <br> </div> </div> </div> </section> {% endblock %} custom_dz.js Dropzone.autoDiscover = false; const myDropzone = new Dropzone("#testdropzone", { maxFiles: 1, maxFilesize: 20, }) So the POST request is running, everything works, file is saved, but then this line (return render(request, 'uploadapp/nextpage.html')) from the views.py is not working. I did try to solve it by adding this function to custom_dz.js which is working, but then I can't pass variables and so … -
Getting error=H14 on Django-Heroku App using gunicorn
I'm trying to deploy my django-react app to heroku. Deployment goes smoothly but on heroku open I'm greeted by an application error. heroku logs --tail reveals the following in short: error code H14 "No web process running" in detail: > 2021-01-22T18:12:32.000000+00:00 app[api]: Build started by user > johndoe@gmail.com 2021-01-22T18:13:42.032970+00:00 app[api]: > Deploy f905f66c by user johndoe@gmail.com > 2021-01-22T18:13:42.032970+00:00 app[api]: Running release v3 > commands by user johndoe@gmail.com > 2021-01-22T18:13:42.786292+00:00 app[api]: Starting process with > command `/bin/sh -c 'if curl $HEROKU_RELEASE_LOG_STREAM --silent > --connect-timeout 10 --retry 3 --retry-delay 1 >/tmp/log-stream; then 2021-01-22T18:13:42.786292+00:00 app[api]: chmod u+x /tmp/log-stream > 2021-01-22T18:13:42.786292+00:00 app[api]: /tmp/log-stream /bin/sh -c > '"'"'python manage.py migrate --no-input'"'"' > 2021-01-22T18:13:42.786292+00:00 app[api]: else > 2021-01-22T18:13:42.786292+00:00 app[api]: python manage.py migrate > --no-input 2021-01-22T18:13:42.786292+00:00 app[api]: fi'` by user johndoe@gmail.com 2021-01-22T18:13:50.874352+00:00 > heroku[release.2135]: Starting process with command `/bin/sh -c 'if > curl > https://heroku-release-output.s3.amazonaws.com/log-stream?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAJ3LIQ2SWG7V76SVQ%2F20210122%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20210122T181342Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Signature=5fc1b225b8a71466d45518b4029f165af938e8c5d766033b8a335481d6a46e84 > --silent --connect-timeout 10 --retry 3 --retry-delay 1 >/tmp/log-stream; then 2021-01-22T18:13:51.619515+00:00 heroku[release.2135]: State changed from starting to up > 2021-01-22T18:13:54.000000+00:00 app[api]: Build succeeded > 2021-01-22T18:13:55.388498+00:00 app[release.2135]: > /app/.heroku/python/lib/python3.6/site-packages/environ/environ.py:630: > UserWarning: /app/recipemanager/.env doesn't exist - if you're not > configuring your environment separately, create one. > 2021-01-22T18:13:55.388523+00:00 app[release.2135]: "environment > separately, create one." % env_file) 2021-01-22T18:13:56.208813+00:00 > app[release.2135]: Operations to perform: > 2021-01-22T18:13:56.208840+00:00 … -
Unable to hide server name in django based website hosted in azure webapp
Django based website is hosted in azure webapp (python 3.8). As part of the security measure, I am trying to hide the server name from the response header. By default, it is gunicorn/20.0.4. In the Django app, I have implemented the middleware layer and added the following code class testMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) response["Server"] = "dummyserver" response["X-XSS-Protection"] = 1 return response In the local env, this setting is working. In the response header, the server name was dummyserver. But once it is deployed in the Azure web app the server name is displayed as gunicorn/20.0.4 in the response header, but strangely the other setting like X-XSS-Protection is working as expected. It looks like the Azure web app by default replace the Django server name. Is there any way we can handle this? Thanks for your help. -
Can not display Django models on Homepage
I am new to Django and I am creating a portfolio test site. When I try to import models in home.html from views.py, which I imported from models.py, error displays on my website page (no such column: portfolio_project.title). Help would be greatly appreciated! models.py file from django.db import models class Project(models.Model): title=models.CharField(max_length=100) description=models.CharField(max_length=100) image = models.ImageField(upload_to='portfolio/images/') url = models.URLField(blank=True) views.py file from django.shortcuts import render from .models import Project def home(request): projects = Project.objects.all() return render(request, 'portfolio/home.html', {'projects':projects}) home.html file <h1>This is Home!</h1> {% for project in projects %} {{project.title}} {% endfor %} -
Django - how can users create groups and add other users to see content provided by that group (like on facebook)
I am creating a website with Django and I want My Users to be able to create there own groups (like on Facebook) and give permission to other members to see content only in that group can you give me a general idea of how I can go about coding that. -
Django - joining via the most recent through table row on a many-to-many
If I have a many-to-many relationship, with a custom through table, how can I join via only the most recent through table row? For example: class Price(models.Model): amount = models.DecimalField(max_digits=21, decimal_places=2) class PricingSchedules(models.Model): name = models.CharField(max_length=100) price = models.ForeignKey(Price, on_delete=models.CASCADE) class Product(models.Model): name = models.CharField(max_length=100) pricing_schedulesfd = models.ManyToManyField( PricingSchedules, related_name='pricing_schedule_set', through='ProductPricingSchedule', ) class ProductPricingSchedule(models.Model): created_at = models.DateTimeField(auto_now_add=True) product = models.ForeignKey(Product, on_delete=models.CASCADE) pricing_schedule = models.ForeignKey( PricingSchedule, on_delete=models.CASCADE, ) class Meta: unique_together = ('product', 'pricing_schedule') I realize these models are a little contrived, but the question still stands. Say I want to select all products whose price is equal to "5.00", but I only want to consider the most recent row in the ProductPricingSchedule table, if any exists at all? -
Implement API REST to an existing Django app
I'm looking for a good tutorial that illustrates that how can I Implement API REST to an existing Django app. Because I tried the official docs and other tutorials, and I'm still confusing, I'm unable to build an API for each function that I have. Is there any easy way to implement that? Thanks,