Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Importing from different directories in Python
I'm trying to build a very simple Web Scraper that scrapes from popular Job Boards and posts the jobs in a simple Django website. In my Scrapy spider, I am trying to create a Django model object for every job scraped. But I'm having trouble importing the model in my Scrapy spider file. This is my folder structure: F:. │ db.sqlite3 │ manage.py │ ├───jobs_board │ asgi.py │ settings.py │ urls.py │ wsgi.py │ __init__.py │ ├───main │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ 0001_initial.py │ │ __init__.py │ │ │ └───templates │ └───main │ home.html │ └───scraper │ scrapy.cfg │ t.py │ testing.md │ └───scraper │ items.py │ middlewares.py │ pipelines.py │ settings.py │ __init__.py │ └───spiders indeed.py __init__.py What I want to do is, if I run the spider "indeed.py", I want it to be able to import the main/models.py file. How would I achieve this? Thank you for your help! :) -
get details from database equals to value passed by url
class Assets(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30, null = False) model = models.CharField(max_length=30) serial = models.CharField(max_length=60) tag = models.CharField(max_length=30, unique=True, null = False) location = models.CharField(max_length=30) assignto = models.CharField(max_length=30, null = False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) authorize = models.ForeignKey(User, on_delete= models.DO_NOTHING) def __str__(self): return self.tag class Meta: verbose_name_plural = "Assets" class PCDetail(models.Model): id = models.AutoField(primary_key=True) tag = models.OneToOneField(Assets, on_delete = models.CASCADE) ram = models.IntegerField() card = models.CharField(max_length=10) board = models.CharField(max_length=30) authorize = models.ForeignKey(User, on_delete= models.DO_NOTHING) urlpatterns = [ path('', views.assets, name='assets'), path('details/ <str:tag>/', views.details, name='details'), ] def assets(request): assets = Assets.objects.all() return render(request, 'pcassets.html', {'assets':assets}) def details(request, tag): details = PCDetail.objects.get(tag=tag) return render(request, 'details.html',{'details':details}) ValueError at /details/sn-pc-10001/ Field 'id' expected a number but got 'sn-pc-10001'. Request Method: GET Request URL: http://127.0.0.1:5000/details/sn-pc-10001/ Django Version: 3.1.6 Exception Type: ValueError Exception Value: Field 'id' expected a number but got 'sn-pc-10001'. -
How to redirect user based on their previous options click in HTML CSS JS
I am trying to make a quiz application which works in a flow chart format . So if u press A then your next question could be A1 and if u press B it would be B1 and so on ... But I want to have a common “NEXT” button for all options So if they press A first and then press next they would be redirected to A1.html And if they press B first and then next they would be redirected to B1.HTML I want to make a next button which redirects the user to their next question (which would be different based on your previous options) ... but I am not able to figure out how to use href here ! -
Django Insert to MSSQL database is not working
first of all i am new to django , and it's my first project using django . So the project basically does inserting of dat from UI to datbase table . but whatever i try am not getting any error but the value is not getting inserted . so the below is my code : Views.py def pg3(request): conn = pyodbc.connect('Driver={SQL Server};' 'Server=ABC\Aurora;' 'Database=hi;' 'Trusted_Connection=yes;') if request.method == 'POST' : print('hi') myfile = request.FILES['myfile'] #myfilename=request.post.get('myfile') PatchVersion=request.POST.get('PatchVersion') cursor5 = conn.cursor() cursor5.execute( "insert into PatchInstallers values('" + PatchVersion + "')") cursor5.commit() fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'tech/pg3.html', { 'uploaded_file_url': uploaded_file_url }) context = { 'result': result, 'result4': result4, } return render(request, 'tech/pg3.html', context) here i wanted to store PatchVersion inside dbtable , so here is my html / pg3.html <label for="patchversion">PatchInstaller Version:</label> <input type="text" id="fname" name="PatchVersion"> and here is my table headers :[![table Headers][1]][1] i made required changes in settings.py too . but in vain [1]: https://i.stack.imgur.com/VUpcb.png -
Custom Django All-auth signup form not sending confirmation email after signup
So I have a custom user that extends the base user. class CustomUser(AbstractUser): uuid = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True) is_renter = models.BooleanField(default=False) This is my custom user creation form - makes the user a renter if they use this form. class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ('email', 'username') def save(self, commit=True): user = super().save(commit=False) user.is_renter = True if commit: user.save() return user class RenterSignupPageView(generic.CreateView): model = CustomUser form_class = CustomUserCreationForm success_url = reverse_lazy('home') template_name = 'account/renter_signup.html' This is my view right now, but it doesn't send the confirmation email as if I used the default signupform. The email only get sent if I attempt to login with the account... Is this the proper way to implement different user types? Should I be using SignUpForm? if so, can that allow different user types, views, and urls? -
NoReverseMatch when referencing ModelViewSet and DefaultRouter URLs
I am using Django REST Framework, and am having difficulty using reverse to resolve URLs defined in ModelViewSet—which I imagine works the same way with ViewSet. I've tried using the URL patterns described here, but I still get a NoReverseMatch error. I started a new project with app places to troubleshoot, but the issue persists. In settings.py, I have added places and rest_framework to INSTALLED_APPS and made no other changes. project urls.py from django.contrib import admin from django.urls import re_path, include urlpatterns = [ re_path(r'^v1/', include(('places.urls', 'places'))), re_path(r'^admin/', admin.site.urls), ] places app urls.py from django.urls import re_path, include from rest_framework import routers from . import views router = routers.DefaultRouter(trailing_slash=False) router.register('places', views.PlaceViewSet) urlpatterns = router.urls models.py from django.db import models class Place(models.Model): title = models.CharField(max_length=120) def __str__(self): return self.title tests.py from django.urls import reverse from rest_framework.test import APITestCase from .models import * class TestPlaces(APITestCase): def setUp(self): Place.objects.create(title='Manhattan Mansion') def test_list(self): response = self.client.get(reverse('place-list')) Traceback (.env) $ ./manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). E ====================================================================== ERROR: test_list (places.tests.TestPlaces) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/matt/test/places/tests.py", line 12, in test_list response = self.client.get(reverse('place-list')) File "/home/matt/test/.env/lib/python3.9/site-packages/django/urls/base.py", line 87, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, … -
Reset forloop counter in django template
How to reset the forloop counter in django template? So I have something like this: {% for major in majors %} {% for minor in minors %} {% if minor.major_name == major %} {{forloop.counter}} {{minor}} {% endif %} {% endfor %} {% endfor %} Current output: major 1 minor 2 minor major 3 minor 4 minor 5 minor ... I want it to display something like: major 1 minor 2 minor major 1 minor 2 minor 3 minor ... -
python cant open file 'manage.py' - "heroku run python manage.py migrate command input"
Hi I have finished my Django pycharm project and I'm now trying to upload it to heroku/ host it on heroku. I have followed this link https://medium.com/@qazi/how-to-deploy-a-django-app-to-heroku-in-2018-the-easy-way-48a528d97f9c which has actually successfully worked for me in the past. When I get to the step were you put this command in however 'heroku run python manage.py migrate' I continue to get this error message 'Running python manage.py migrate on ⬢ radiant-retreat-19016... up, run.6371 (Free) python: can't open file 'manage.py': [Errno 2] No such file or directory' Im not that much of a beginner so I know that my manage.py file is in the right place especially cause I can run ' python manage.py runserver '. I will attach the code to my procFile below along with my manage.py code and settings. I have looked everywhere on the internet for the problem and some people have it but nothing has worked for them. I will attach any other code if you need it. I even transferred all code to a new project and the same problem occurred. web: gunicorn inspect_list2.wsgi #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'inspect_list2.settings') try: from django.core.management import … -
I use DateTimeField in Django and I can't get it to only show Y/M/D Hour/Min, it shows 2021-02-20T02: 06: 04.674Z. I am showing the data with json
#settings///////// I use DateTimeField in Django and I can't get it to only show Y/M/D Hour/Min, it shows 2021-02-20T02: 06: 04.674Z. I am showing the data with json LANGUAGE_CODE = 'es' TIME_ZONE = 'America/Cordoba' USE_I18N = True DATE_FORMAT='%m/%d/%Y %H:%M:%S' DATETIME_FORMAT='%m/%d/%Y %H:%M:%S' USE_L10N = False USE_TZ = True USE_DJANGO_JQUERY = True -------------------- #model Please help { creation_date = models.DateTimeField(auto_now_add=True)} ------------ #index.js Please help function listadoIncidentes(){ $.ajax({ url: "/incidente/listar_incidentes/", type: 'get', dataType:"json", success: function(response){ $('#tabla_incidentes tbody').html(""); for (let i = 0; i < response.length; i++){ let fila = '<tr>'; fila += '<td>' + response[i]["fields"]['id'] + '</td>' fila += '<td>' + response[i]["fields"]['categoria'] + '</td>' fila += '<td>' + response[i]["fields"]['subCategoria'] + '</td>' fila += '<td>' + response[i]["fields"]['estado'] + '</td>' fila += '<td>' + response[i]["fields"]['titulo'] + '</td>' fila += '<td>' + response[i]["fields"]['fecha_creacion'] + '</td>' fila += '<td><button> EDITAR </button> <button> ELIMINAR </button></td>' fila += '</tr>'; $('#tabla_incidentes tbody').append(fila); ...................... ............................. -
Long Script Stops Running When Deployed - Django on nginx/gunicorn
I have a very long script that ingests a pdf, does a lot of processing, then returns a result. It runs perfectly when running through port 8000 through either python manage.py runserver 0.0.0.0:8000 or gunicorn --bind 0.0.0.0:8000 myproject.wsgi However when I run it via port 80 in "production" the script stops running at a certain point with no errors and seemingly no holes in the logic. What's really causing confusion is that it stops in different places depending on the length/complexity of the processed document. Short/simple ones complete with no issue but a longer one will stop in the middle. I tried adding a very detailed log file to debug the issue. If I process one document, it stops running in the same loop but at different places within the loop (seemingly random), indicating that this isn't a logical flaw (note I'm writing and flushing). Furthermore, if I use a longer/more complex document it mysteriously stops earlier in the process. I'm deploying this using Django via gunicorn/nginx on DigitalOcean Is there some sort of built in protection that stops processes after a certain number of CPU cycles or time as protection against infinite loops in any of the above? That's … -
Django ModelManager not saving the model instance correctly
I am working on an ecommerce project but my OrderManager() class does not saving the instance(i think) When i am clicking on BOOK button i am getting this error which is defined in my view order_amount = order_obj.total * 100 AttributeError: 'NoneType' object has no attribute 'total' But when i refresh the page error goes way and order_obj.total * 100 is calculated, But my question is why i need to refresh the page again and again when i create a new order. Here is my models.py class OrderQuerySet(models.query.QuerySet): def not_created(self): return self.exclude(status='created') class OrderManager(models.Manager): def get_queryset(self): return OrderQuerySet(self.model, using=self.db) def create_or_get_order(self, product): created = None obj = None qs = self.get_queryset().filter(product=product, active=True, status='created') if qs.count() == 1: obj = qs.first() else: self.model.objects.create(product=product) created = True return obj, created class Order(models.Model): order_id = models.CharField(max_length=120, blank=True) product = models.ForeignKey(Product, on_delete=models.CASCADE) total = models.PositiveIntegerField() active = models.BooleanField(default=True) objects = OrderManager() class Meta: ordering = ['-ordered_on', '-updated'] def __str__(self): return self.order_id def check_done(self): # check everything is correct before final checkout order_id = self.order_id total = self.total if order_id and total > 0: return True return False def mark_paid(self): if self.check_done(): self.status = 'paid' self.save() return self.status def pre_save_create_order_id(sender, instance, *args, **kwargs): if not … -
Django display replies to an comment
I have an comment and reply system. I am able to display comments but not replies. Here is my model: class Comment(models.Model): post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField(default='') created_date = models.DateTimeField(default=timezone.now) anonymous = models.BooleanField(default=False) def __str__(self): return self.text class Reply(models.Model): comment_to_reply = models.ForeignKey('blog.Comment', on_delete=models.CASCADE, related_name='replies') author = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField(default='') created_date = models.DateTimeField(default=timezone.now) anonymous = models.BooleanField(default=False) def __str__(self): return self.text My views.py: @login_required def add_reply_to_comment(request, pk): reply_to_comment = get_object_or_404(Comment, pk=pk) author_of_post = reply_to_comment.author post_email = author_of_post.email author = request.user if request.method == "POST": form = ReplyForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.comment_to_reply = reply_to_comment comment.author = author comment.save() return redirect('/home/') else: form = ReplyForm() return render(request, 'blog/add_reply_to_post.html', {'form': form}) And my template: {% for comment in post.comments.all|slice:":2" %} <article class="media content-section"> <div class="container"> <div class="row"> <div class="col-md-8"> <div class="media g-mb-30 media-comment"> <a href="{% url 'user-posts' comment.author.username %}"> <img class="rounded-circle article-img" src="{{ comment.author.profile.image.url }}"> </a> <div class="media-body u-shadow-v18 g-bg-secondary g-pa-30"> <div class="article-metadata"> <div class="g-mb-15"> <h5 class="h5 g-color-gray-dark-v1 mb-0"><a style="text-decoration: none;color: #000;" href="{% url 'user-posts' comment.author.username %}"><span class="notranslate">{{ comment.author }}</span></a><span class="g-color-gray-dark-v4 g-font-size-12"><small class="text-muted"> ~ {{ comment.created_date|date:"F d" }}</small> {% if comment.author == user %} <br><a class="fa" style="color:blue" href="{% url 'comment-update' comment.id %}">&#xf044;</a> <a class="fa" … -
`No Unique Constraint` error on Django ForiegnKey w/ unique PK
There are dozens of similar posts, but typically the OP isn't relying on the built-in, auto-incrementing, and already-unique PK value so they tend to have the same answers. None have answered my question. The Error I get this error when running python manage.py migrate on my (Django/Postgres) production Google Cloud server: django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "api_bookgroup" I understand that the error is saying "Hey! I don't know which record to return, because there's no unique identifier" BUT two things have me scratching my head: Django Docs are pretty clear that "By default, Django uses the primary key of the related object" - so the PK should be the unique constraint that's required. This same code runs perfectly on 3 other dev machines/databases, including our Google Cloud dev instance (Although each other instance has different data in the database) Point #2 makes me wonder if it's possible for Django/Postgres to somehow allow two bookGroup records with the same PK without throwing terrible errors? if that's the case, how would I find those records, and if not, What else could be causing this error? Thanks for your Help! # api.models.py class BookGroup(models.Model): name = … -
django cant create tables
i tried to figure out why i have a problem in my code and after insulation i figured that django cant create tables for 2 of my models for some reason class Race(models.Model): name = models.CharField(max_length=200) attack = models.IntegerField() deffence = models.IntegerField() intelligence = models.IntegerField() agility = models.IntegerField() wisdom = models.IntegerField() charisma = models.IntegerField() def publish(self): self.save() def get_absolute_url(self): return reverse("characters:race_detail",kwargs={'pk':self.pk}) def __str__(self): return self.name class Role(models.Model): name = models.CharField(max_length=200) attack = models.IntegerField() deffence = models.IntegerField() intelligence = models.IntegerField() agility = models.IntegerField() wisdom = models.IntegerField() charisma = models.IntegerField() def publish(self): self.save() def get_absolute_url(self): return reverse("characters:role_detail",kwargs={'pk':self.pk}) def __str__(self): return self.name as far as i cheack i cant see any problem with them but i hope someone will, thanks to anyone who helps -
django rest datatables, search across relationships
I need to filter all Experts by past objectives. I am using https://github.com/izimobil/django-rest-framework-datatables my models are class Expert(models.Model): name = models.CharField(blank=True, max_length=300) class Meeting(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True) expert = models.ForeignKey(Expert, on_delete=models.SET_NULL, blank=True, null=True) objective = models.TextField(null=True, blank=True) my datatables javascript $("#table-analyst-search").DataTable({ serverSide: true, ajax: "/api/experts/?format=datatables", ordering: false, pagingType: "full_numbers", responsive: true, columns: [ { data: "objectives", name: "objectives", visible: false, searchable: true, render: (objectives, type, row, meta) => { return objectives; } }, ], }); My serializer class ExpertSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) objectives = serializers.SerializerMethodField() class Meta: model = Expert fields = ( "id", "objectives", ) def get_objectives(self, obj): request = self.context["request"] request = self.context["request"] meetings = Meeting.objects.filter( analyst_id=request.user.id, expert_id=obj.id ).distinct('objective') if len(meetings) > 0: objectives = meetings.values_list("objective", flat=True) objectives = [x for x in objectives if x] else: objectives = [] return When I begin to type in the datatables.js searchbar I get an error like FieldError at /api/experts/ Cannot resolve keyword 'objectives' into field. Choices are: bio, company, company_id, created_at, description, email, favoriteexpert, first_name, id, is_blocked, last_name, meeting, middle_name, network, network_id, position, updated_at Request Method: GET Request URL: http://localhost:8000/api/experts/?format=datatables&draw=3&columns%5B0%5D%5Bdata%5D=tags&columns%5B0%5D%5Bname%5D=favoriteexpert.tags.name&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=false&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=desc&columns%5B1%5D%5Bname%5D=&columns%5B1%5D%5Bsearchable%5D=false&columns%5B1%5D%5Borderable%5D=false&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns% fwiw, in pure django orm what I want to accomplish would be something like Expert.objects.filter( pk__in=Meeting.objects.filter( … -
Django override model get() method won't work on foreign keys
I have a custom model defined as following, with get() method override class CustomQuerySetManager(models.QuerySet): def get(self, *args, **kwargs): print('Using custom manager') # some other logics here... return super(CustomQuerySetManager, self).get(*args, **kwargs) class CustomModel(models.Model): objects = CustomQuerySetManager.as_manager() class Meta: abstract = True Then I have two models defined as class Company(CustomModel): name = models.CharField(max_length=40) class People(CustomModel): company = models.ForeignKey(Company, on_delete=models.CASCADE) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) If I use get() directly like People.objects.get(pk=1) then it works, "Using custom manager" gets printed, but if I try to get the foreign key info, django still uses the get() method from the default manager, nothing gets printed and the rest of logic defined won't get executed, for example someone = People.objects.get(id=1) # prints Using custom manager, custom logic executed company_name = someone.company.name # nothing gets printed, custom logic does not execute Is the foreign key field in a model using a different manager even though the foreign key model is also using my custom model class? Is there a way to make my custom get() method work for all fields? -
Application error - heroku error log (Django)
[Heroku message][1] [terminal error][2] basically I'm trying to create a application on Heroku. after the git push Heroku master I receive this error message, the git Heroku push master done without problems error message 2021-02-19T22:22:01.961998+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=fusi on-wilmec.herokuapp.com request_id=659ad1a9-1473-450b-b935-29ca0d8b8c3c fwd="177.30.115.253" dyno= connect= service = status=503 bytes= protocol=https 2021-02-19T22:22:02.480455+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico " host=fusion-wilmec.herokuapp.com request_id=8dc9e136-b5c0-4fac-98fc-225dffef5ee4 fwd="177.30.115.253" dyno= conne ct= service= status=503 bytes= protocol=https 2021-02-19T22:31:10.435995+00:00 app[web.1]: [2021-02-19 22:31:10 +0000] [4] [INFO] Reason: Worker failed to boot My Procfile web: gunicorn fusion-wilmec.wsgi --log-file - requirements.txt appdirs==1.4.4 asgiref==3.3.1 certifi==2020.12.5 distlib==0.3.1 dj-database-url==0.5.0 dj-static==0.0.6 Django==3.1.6 django-stdimage==5.1.1 filelock==3.0.12 gunicorn==20.0.4 Pillow==8.1.0 progressbar2==3.53.1 psycopg2==2.8.6 psycopg2-binary==2.8.6 python-utils==2.5.6 pytz==2021.1 six==1.15.0 sqlparse==0.4.1 static3==0.7.0 virtualenv==20.4.2 virtualenv-clone==0.5.4 whitenoise==5.2.0 wsgi.py from django.core.wsgi import get_wsgi_application from dj_static import Cling, MediaCling os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fusion.settings') application = Cling(MediaCling(get_wsgi_application()))``` [1]: https://i.stack.imgur.com/45LyF.png [2]: https://i.stack.imgur.com/rwA9M.png -
Which language does Instagram uses for Direct Messages
Which language does Instagram uses for Direct Messages So I saw, that Instagram uses Python Django Rest Framework for their App and for their Website. Now I am wondering if they're using python for instagram direct messages too. Do you think, or do you know, what language does Instagram uses for their service? -
The way of work explore feature in Instagram and tiktok in Django
The way of work explore feature in Instagram and TikTok or How to create this feature, what the information they collect from the users to let this feature work in Django -
Django template - convert datetime format to string
I need to convert datetime format to string in Django template: <input name="wtn_datetime" type="text" class="form-control datetimepicker" data-date-format="DD/MM/YYYY HH:mm" value="{{ wtn.wtn_datetime }}"> what is the best way to get string in value="{{ wtn.wtn_datetime }} Thank you. -
DataError at /admin/message/messages/add/ django rest framework
hello i am following a tutorial on how to add a chat function in django rest framework which is here: https://steemit.com/utopian-io/@ajmaln/part-1-creating-a-simple-chat-app-with-djangorestframework but when i create a message in the admin panel it comes up with DataError at /admin/message/messages/add/ invalid input syntax for type integer: "test1" LINE 1: ...me_id", "time", "seen", "timestamp") VALUES ('o', 'test1', '... i have follwed the whole tutorial but instead of using id as the pk i have used my username column which is a primary key if you need more data please let me know is there anything i am missing? ^ -
Integrating django-image-cropping to Azure Blob Storage
I am trying to move my media files to an azure file storage, however I'm finding an issue when trying to generate the cropped file as it is not being saved in the azure file storage. Files in model file is as per the below: class ImageShow (models.Model): title = models.CharField(max_length=50) image = models.ImageField(upload_to='homepage/images/') active = models.BooleanField(default=False) cropping = ImageRatioField('image', '1200x400') In template I'm calling it as per the below: <img class="d-block w-100" src="{% cropped_thumbnail images "cropping" scale=1.0 %}"> and the below are the settings specified in setting.py from easy_thumbnails.conf import Settings as thumbnail_settings THUMBNAIL_PROCESSORS = ( 'image_cropping.thumbnail_processors.crop_corners', ) + thumbnail_settings.THUMBNAIL_PROCESSORS As for Azure File Storage I have the below code: In settings.py AZURE_ACCOUNT_NAME = '' AZURE_ACCOUNT_KEY = '' AZURE_CUSTOM_DOMAIN = f'' AZURE_LOCATION = '' AZURE_CONTAINER = '' MEDIA_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{AZURE_LOCATION}/' DEFAULT_FILE_STORAGE = 'storages.backends.azure_storage.AzureStorage' In custom_azure.py from storages.backends.azure_storage import AzureStorage from django.conf import settings class AzureMediaStorage(AzureStorage): location = settings.AZURE_LOCATION file_overwrite = False And in Urls I have the below code: urlpatterns+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Any Ideas please on how to make it work with Azure blob storage. Thanks -
Django {% trans %} not translating new changes
I am trying to run a web-app locally (forked from here ) . I am using the {% trans %} tag to mark strings to be translated. The original piece of code was <h3> Personal data</h3>. However , when I change it to <h3>{% trans "Personal data" %}</h3> , the "Personal data" does not get translated , even though the original text (from the forked repository) in the following line gets translated . The following screenshot highlights the issue : When I make any changes to the text between <html> tags, it gets reflected in my local instance. But when I make changes to strings marked with {% trans %} , it does not get translated in my local instance (even though the rest of the original text gets translated) . Note : Changes made to text without {% trans %} tag are getting reflected in my local instance. The app is run using docker-compose up Why does the {% trans %} tag not work on new changes ? -
django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path.error
hi I'm testing my Django rest framework project on a hosting server. when I open the my site domain my site is without any default django style. my admin panel is just html it doesn't have django admin panel style. I connected to the project on host and when i type the collect static command I have this error: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. this is the admin panel: and this is my project settings.py: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Tehran' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # ckeditor CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/" CKEDITOR_UPLOAD_PATH = "uploads/" -
Does Django Development Web Server Cache Redirects?
I have a Django view that I redirect a user to after they login: # settings.py LOGIN_REDIRECT_URL = 'login-redirect' # account/urls.py urlpatterns = [ path('', include('django.contrib.auth.urls')), ... ] # home/views.py from account.models import Member def login_redirect(request): """ Redirect member to appropriate page when they log in. """ member = Member.objects.get(user__id__exact=request.user.id) if member.has_profile: return redirect('homepage', member_id=member.id) else: return redirect('profile-create', member_id=member.id) If I start Django's development server and execute this code when the condition member.has_profile = True, Django redirects me to the homepage view as expected. But if I then go into the database and set has_profile to False, restart the web server, and execute code again, my website acts as if the code isn't executed. Instead, I'm sent immediately to the homepage view again. I can see this by looking at the terminal console: [19/Feb/2021 ...] "GET /account/login/ HTTP/1.0" 200 4268 # I'm using Django's default login method [19/Feb/2021 ...] "POST /account/login HTTP/1.0" 302 0 [19/Feb/2021 ...] "GET /home/login_redirect/ HTTP/1.0" 200 4599 This happens even though I am restarting the server and clearing my browser's cache. In fact, I can edit the login_redirect function so that it only contains a single line pass and I'm still sent to the homepage after …