Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django permission not working when variable in Axios request
I ran into a really strange error today while setting up restrictions on some of my Vue pages. I'm attempting to make this GET request: try { let actors = await $axios.$get(`/api/v1/users/${loggedInUser.id}/`); return { actors }; } catch (e) { return { actors: [] }; } }, I get back an empty actors [] object, but if I swap out ${loggedInUser.id} with just 1: try { let actors = await $axios.$get(`/api/v1/users/1/`); return { actors }; } catch (e) { return { actors: [] }; } }, I get back the actors: [] object I want. ({{loggedInUser.id}} returns 1 in the template). In Django I have the permission for this user's group set to myapp|user|Can View user Is there some reason that the variable in the Axios call is messing with the perms? I've tried already something like : const id = loggedInUser.id and await $axios.$get(`/api/v1/users/id/`) -
How can I solve my connection error in mysql
I've tried to connect my db. All db settings in settings.py is checked and they are correct. When I run the server, I face an error which is shown below. I searched at internet and I find solutions but all them is working for lower python version. I am using the newest python version. My error is that: System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 453, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 73, in applied_migrations if self.has_table(): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/base/base.py", line 256, in cursor return self._cursor() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/base/base.py", line 233, in _cursor self.ensure_connection() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/base/base.py", line 197, in connect self.init_connection_state() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 231, in init_connection_state if self.features.is_sql_auto_is_null_enabled: File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res … -
Check if a string has a capital letter in Django?
If I have a string "Hello", how do I check if the string has at least one capital letter and one lowercase letter in Django? -
Django pagination request page given context
Is there a clever way to request a specific page from Django pagination if I know the content I want. e.g. article = Article.objects.get(pk=10) articles = Article.objects.all() paginator = Paginator(articles, 10) paginator.get_page_containing(article) Note. get_page_containing doesn't exist but illustrates what I'd like to do. -
Using primary keys in Django and connecting multiple CBVs in database
I am incredibly new to Django and I'm struggling to get something to work in my project even after extensive research (I've been trying this over and over for about 2 days straight now and I'm sure I'm not finding the right answer because I'm probably not looking for the right question). When I try and add a class based model (Artifacts) to another model in my database (Exhibit), it successfully adds the artifact data to the database but does not show up in the front end as I expect. The Exhibit view is already connected to another view (Case) and that all seems to work fine. model.py: class Artifact(models.Model): exh_ref = models.ForeignKey(Exhibit, on_delete=models.CASCADE, null=True) art_type = models.CharField(max_length=50) description = models.CharField(max_length=100) source = models.TextField(max_length=500) notes = models.TextField(max_length=1000) def get_absolute_url(self): return reverse('exhibit_detail', kwargs={'pk': self.pk}) def __str__(self): return self.art_type + " - " + self.description and class Exhibit(models.Model): case = models.ForeignKey(Case, on_delete=models.CASCADE) exh_ref = models.CharField(max_length=20) exh_pic = models.ImageField(upload_to='exhibit_pics', blank=True, null=True) exh_type = models.CharField(max_length=50) exh_make = models.CharField(max_length=50) exh_model = models.CharField(max_length=50) exh_PIN = models.IntegerField() exh_periph = models.TextField() exh_condtn = models.TextField() special_cat = models.BooleanField(default=False) def get_absolute_url(self): return reverse('case_list') def __str__(self): return self.exh_ref + " Make: " + self.exh_make + " Model: " + self.exh_model Views.py: … -
Why i can't save data in mutiple query?
I read several posts here on this subject, I tried to apply them but I still have this lack of backup in my database and i don't know why. my code : models.py class Noms (models.Model) : n_soza = models.CharField(max_length=20) nom = models.CharField(max_length=100) particule = models.CharField(max_length=20, null=True, blank=True) prenom = models.CharField(max_length=100) .... def __str__ (self): return self.n_soza class Conjoint (models.Model) : c_soza = models.ForeignKey(Noms, on_delete=models.CASCADE, null=True, blank=True) conjoint1 = models.CharField(max_length=100, null=True, blank=True) conjoint2 = models.CharField(max_length=100, null=True, blank=True) conjoint3 = models.CharField(max_length=100, null=True, blank=True) def __str__ (self): return str(self.c_soza) import_xls.py noms = Noms( n_soza=nom_list[0], nom=nom_list[2], particule= nom_list[3], prenom=nom_list[4], .... ) noms.save() conjoint = Conjoint( c_soza = Noms.objects.get(n_soza=nom_list[0]), conjoint1 = nom_list[8], conjoint2 = nom_list[9], conjoint3 = nom_list[10], ) conjoint.save() I have an excel that I acquire as a list and part of the list fields go to a specific location in my database. when I run my code, "Noms" fills up correctly but the "Conjoint" remains completely empty. I tried : conjoint = Conjoint.objects.create( conjoint1=nom_list[8], conjoint2=nom_list[9], conjoint3=nom_list[10] ) conjoint.c_soza = Noms.objects.get(n_soza=nom_list[0]) conjoint.save() but without "conjoint.save()" instancies are create but not for field "c_soza" (it's normal) and with "conjoint.save()" my queryset "Conjoint" is empty I don't know why one works (Noms) and not the … -
ModuleNotFoundError: No module named 'Django-Banking-App.settings' when migrating my Django app to Heroku
I have been trying for two days to deploy my django app to heroku but stuck with the modulenotfound error. Think it might have something to do with my static files but I am not sure. I would forever appreciate someone helping me out with this Here is the error: $ heroku run python manage.py migrate Running python manage.py migrate on ⬢ bb-bank... up, run.4227 (Free) Traceback (most recent call last): File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 82, in wrapped saved_locale = translation.get_language() File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/translation/__init__.py", line 254, in get_language return _trans.get_language() File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/translation/__init__.py", line 57, in __getattr__ if settings.USE_I18N: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'Django-Banking-App.settings' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, … -
Django: add row to formset within template
I have a template that renders a formset where the user can add rows. I added a "add" button for the user to add row. However, I am not very familiar with javascript but clicking the button does not render anything. here is what the javascript code look like: function updateElementIndex(el, prefix, ndx) { var id_regex = new RegExp('(' + prefix + '-\\d+)'); var replacement = prefix + '-' + ndx; if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement)); if (el.id) el.id = el.id.replace(id_regex, replacement); if (el.Id) el.Id = el.Id.replace(id_regex, replacement); if (el.Date) el.Date = el.Date.replace(id_regex, replacement); if (el.Quantity) el.Quantity = el.Quantity.replace(id_regex, replacement); if (el.NetAmount) el.NetAmount = el.NetAmount.replace(id_regex, replacement); } function cloneMore(selector, prefix) { var newElement = $(selector).clone(true); var total = $('#id_' + prefix + '-TOTAL_FORMS').val(); newElement.find(':input:not([type=button]):not([type=submit]):not([type=reset])').each(function() { var Id= $(this).attr('Id').replace('-' + (total-1) + '-', '-' + total + '-'); var Date= $(this).attr('Date').replace('-' + (total-1) + '-', '-' + total + '-'); var Quantity= $(this).attr('Quantity').replace('-' + (total-1) + '-', '-' + total + '-'); var NetAmount= $(this).attr('NetAmount').replace('-' + (total-1) + '-', '-' + total + '-'); var id = 'id_' + Id; $(this).attr({'Id': Id, 'id': id, 'Date': Date, 'Quantity': Quantity, 'NetAmount': NetAmount}).val('').removeAttr('checked'); }); newElement.find('label').each(function() { var forValue = $(this).attr('for'); if (forValue) { forValue … -
how to see attributes of User model when creating a model that has one to one relation?
I have a model for example Doctor model that has one to one relation to User model. When creating an instance of Doctor model, django says choose between existing users or create new user by clicking on plus button and create a new one. How to create user and a doctor at one time. I mean how can I show User form and Doctor form in a single page. (in the django administration panel) -
How do I get my handle function to run with the right arguments, (Django, bootstrap script)
Here is my code: class Command(BaseCommand): def handle(self, *args, **options): main_api_header = "https://pokeapi.co/api/v2/" specific_pokemon = f"{main_api_header}pokemon/" for name in pokemon_names: pokemon_stats = f"{specific_pokemon}{name}" response = requests.get(pokemon_stats).json() Pokemon.objects.create( [ Pokemon(name=f"{pokemon_stats}{['name']}"), Pokemon( front_normal_image=f"{pokemon_stats}{['sprites']}{['front_default']}"), Pokemon( front_shiny_image=f"{pokemon_stats}{['sprites']}{['front_shiny']}"), Pokemon( hp=f"{pokemon_stats}{['stats']}{[0]}{['base_stat']}"), Pokemon( attack=f"{pokemon_stats}{['stats']}{[1]}{['base_stat']}"), Pokemon( defense=f"{pokemon_stats}{['stats']}{[2]}{['base_stat']}"), Pokemon( speed=f"{pokemon_stats}{['stats']}{[5]}{['base_stat']}"), Pokemon( ability_One=f"{pokemon_stats}{['abilities']}{[0]}{['ability']}{['name']}"), Pokemon( ability_Two=f"{pokemon_stats}{['abilities']}{[1]}{['ability']}{['name']}"), Pokemon( type_One=f"{pokemon_stats}{['types']}{[0]}{['type']}{['name']}"), Pokemon( base_experience=f"{pokemon_stats}{['base_experience']}") ] ) With the above, I am getting the data I need, but if I run it like this, it says: TypeError: create() takes 1 positional argument but 2 were given (self, *args) gives me: TypeError: handle() got an unexpected keyword argument 'verbosity' (self) gives me: TypeError: handle() got an unexpected keyword argument 'verbosity' I think you get the idea, but I've been trying different arguments, and none of them work. Is it my syntax? Or is this not the way I can make this happen? -
Django: Best Practice for Storing Images (URLField vs ImageField)
There are cases in a project where I'd like to store images on a model. For example: Company Logos Profile Pictures Programming Languages Etc. Recently I've been using AWS S3 for file storage (primarily hosting on Heroku) via ImageField uploads. I feel like there's a better way to store files than what I've been doing. For some things (like for the examples above) I think it would make sense to actually just get an image url from a more publically available url than take up space in my own database. For the experts in the Django community who have built and deployed really professional projects, do you typically store files directly into the Django media folder via ImageField? or do you normally use a URLField and then pull a url from an API or an image link from the web (e.g., go on any Google image, right click and copy then paste image URL)? Hope this makes sense. Thanks in advance! -
Instead of form.save() update entry if already exists
So I'm building an auction site where users can bid on active listings. The lister can then choose to close the listing and all the bids that have been placed will appear and they can choose a winner. After a lot of tweaking, I've managed to get my placebid view set up and I'm quite happy with how it is working. The problem is if a user has already placed a bid, rather than a new bid is placed I want that existing bid to be located and then updated. What is currently happening is when I click to close the bid I am seeing several bids placed all by the same user which isn't very helpful. My functioning views.py looks like this: def placebid(request, id): listing_bid = get_object_or_404(Listing, id=id) highest_bid = Bid.objects.filter(bid_item_id=id).aggregate(Max('bid_input'))['bid_input__max'] or Decimal('0') currentHighest = Bid.objects.filter(bid_item_id=id).aggregate(Max('bid_input'))['bid_input__max'] listing = Listing.objects.get(pk=id) if request.method == "POST": bidform = BidForm(request.POST) if bidform.is_valid() and highest_bid == 0: bid_placed = bidform.cleaned_data['bid_input'] if bid_placed <= listing.start_price: messages.error(request, 'Make sure your bid is greater than the start price') return HttpResponseRedirect(reverse("listing", args=(id,))) else: newbid = bidform.save(commit=False) newbid.bidder = request.user newbid.bid_input = bidform.cleaned_data['bid_input'] newbid.bid_item = listing_bid newbid.time = timezone.now() newbid.save() messages.success(request, 'Bid placed succesfully') return HttpResponseRedirect(reverse("listing", args=(id,))) if … -
How can I change the name(s) of folders in my Django project without destroying its ability to find its own parts?
I'm reading through Two Scoops of Django and the authors note that best practices involve having a config folder and an apps folder. I've been building a Django project for the last few months here & there and want to get in the habit of complying with these practices, but when I change the name of my <project_name> folder (with the wsgi, settings, etc.), Django can't seem to find the contents of the folder anymore. How do I change this folder name and put the project apps into an app folder without breaking the connections they have? -
Do it exist a helper function how data_get (Laravel) in Django?
The data_get function retrieves a value from a nested array or object using "dot" notation: $data = ['products' => ['desk' => ['price' => 100]]]; $price = data_get($data, 'products.desk.price'); // 100 More detail in Laravel Doc -
Django How can I log client ip address?
I save the logs to the file with this configuration. But I could not log the client ip address. I also want to keep logs for 1 day. Is there a simple method for this? Does anyone have an idea about this? django-requestlogging I tried this library but failed. I do not know if it is up to date. Thanks LOGGING ={ 'version':1, 'loggers':{ 'django':{ 'handlers':['file','file2'], 'level':'DEBUG' } }, 'handlers':{ 'file':{ 'level':'INFO', 'class': 'logging.FileHandler', 'filename':'./logs/info.log', 'formatter':'simpleRe', }, 'file2':{ 'level':'DEBUG', 'class': 'logging.FileHandler', 'filename':'./logs/debug6.log', 'formatter':'simpleRe', } }, 'formatters':{ 'simpleRe': { 'format': ' {asctime} {levelname} {message} ', 'style': '{', } } } -
Django restframework nested serializing
A Django beginner here. My problem simplified: I have models Vocabulary and Transaltion and I want endpoint .../api/vocabulary/pk to return something like: { "name": "some vocabulary", ...other fields "translations": [ {"word": "some word", "tarnslation": "the word in other language"} {"word": "some word2", "tarnslation": "the word2 in other language"} ... ] } My current code: View: @api_view(["GET"]) def vocabulary(request, pk): vocab = Vocabulary.objects.get(id=pk) serializer = VocabularySerializer(vocab, many=False) return Response(serializer.data) Serializers: class TranlationSerializer(serializers.ModelSerializer): class Meta: model = Translation fields = "__all__" class VocabularySerializer(serializers.ModelSerializer): translations = TranslationSerializer(many=True) class Meta: model = Vocabulary fields = ("name", ...other fields, "translations") -
Django failed to load resuorcese of static file (net::ERR_ABORTED 404 (Not Found))
I have changed settings of the base directory(telusko) of my Django framework and also added {%load static%} in index.html but then also the console of chrome shows GET http://127.0.0.1:8000/static/plugins/OwlCarousel2-2.2.1/owl.carousel.css net::ERR_ABORTED 404 (Not Found) code snippet of setting.py sitetravello contains all the HTML, CSS, js files and I have created assets for all the static file through cmd python manage.py collectstatic # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' STATICFILILE_DIRS = [ os.path.join(BASE_DIR, 'sitetravello') ] STATIC_ROOT = os.path.join(BASE_DIR,'assets') the main index.html file code is {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>Travello</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="Travello template project"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="{% static 'styles/bootstrap4/bootstrap.min.css' %}"> <link href="{% static 'plugins/font-awesome-4.7.0/css/font-awesome.min.css' %}" rel="stylesheet" type="text/css"> ERROR IN CHROME Failed to load resource: the server response with the status of 404(not found) ERROR IN CHROME CONSOLE GET http://127.0.0.1:8000/static/plugins/OwlCarousel2-2.2.1/owl.carousel.css net::ERR_ABORTED 404 (Not Found) -
Custom Drop-down into the Wagtail editor
How can i add the custom drop-down options, on click of which wagtail editor adds the option to the editor text ? -
Access Pgadmin4 in Production within dockerized django application
I'm not sure how much sense it would make, but I was learning docker to deploy Django app with Gunicorn + Nginx + AWS. So far, it works fine, where I have unit tested it in production. My question is how can I access pgAdmin4 now? docker-compose.staging.yml version: '3.8' # networks: # public_network: # name: public_network # driver: bridge services: web: build: context: . dockerfile: Dockerfile.prod # image: <aws-account-id>.dkr.ecr.<aws-region>.amazonaws.com/django-ec2:web command: gunicorn djangotango.wsgi:application --bind 0.0.0.0:8000 volumes: # - .:/home/app/web/ - static_volume:/home/app/web/static - media_volume:/home/app/web/media expose: - 8000 env_file: - ./.env.staging networks: service_network: db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.staging.db networks: service_network: # depends_on: # - web pgadmin: image: dpage/pgadmin4 env_file: - ./.env.staging.db ports: - "8080:80" volumes: - pgadmin-data:/var/lib/pgadmin depends_on: - db links: - "db:pgsql-server" environment: - PGADMIN_DEFAULT_EMAIL=pgadmin4@pgadmin.org - PGADMIN_DEFAULT_PASSWORD=root - PGADMIN_LISTEN_PORT=80 networks: service_network: nginx-proxy: build: nginx # image: <aws-account-id>.dkr.ecr.<aws-region>.amazonaws.com/django-ec2:nginx-proxy restart: always ports: - 443:443 - 80:80 networks: service_network: volumes: - static_volume:/home/app/web/static - media_volume:/home/app/web/media - certs:/etc/nginx/certs - html:/usr/share/nginx/html - vhost:/etc/nginx/vhost.d - /var/run/docker.sock:/tmp/docker.sock:ro labels: - "com.github.jrcs.letsencrypt_nginx_proxy_companion.nginx_proxy" depends_on: - web nginx-proxy-letsencrypt: image: jrcs/letsencrypt-nginx-proxy-companion env_file: - .env.staging.proxy-companion networks: service_network: volumes: - /var/run/docker.sock:/var/run/docker.sock:ro - certs:/etc/nginx/certs - html:/usr/share/nginx/html - vhost:/etc/nginx/vhost.d depends_on: - nginx-proxy networks: service_network: volumes: postgres_data: pgadmin-data: static_volume: media_volume: certs: html: vhost: I can access … -
Django Serializer getting attribute from another model
I am working just for my experience and I stacked with the following problem. There are three models: Book, Chapter, and Publisher. Each model is related to one another with the foreign key. class Book(models.Model): name = models.CharField(max_length=64) publisher = models.ForeignKey('Publisher', on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.name class Chapter(models.Model): name = models.CharField(max_length=128) book = models.ForeignKey(Book, related_name='books', on_delete=models.CASCADE) class Publisher(models.Model): title = models.CharField(max_length=128) description = models.TextField() def __str__(self): return self.title class Meta: ordering = ['title'] I want to serialize the data in PublisherDetailSerializer which should show their books and all chapters related to their books. Here are my serializers: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('id', 'name', 'publisher') def to_representation(self, instance): ret = super().to_representation(instance) return ret class ChapterSerializer(serializers.ModelSerializer): id = serializers.IntegerField() name = serializers.CharField(required=False) location = serializers.SerializerMethodField() class Meta: model = Chapter fields = ('id', 'name', 'location') def get_location(self, instance): serializer = BookSerializer(instance.author, context=self.context) return serializer.data class PublisherSerializer(serializers.HyperlinkedModelSerializer): books = BookSerializer(many=True, read_only=True) class Meta: model = Publisher fields = ('id', 'title', 'description', 'books') class PublisherDetailSerializer(PublisherSerializer): chapters = serializers.SerializerMethodField() class Meta: model = Publisher fields = ('id', 'title', 'description', 'books', 'chapters') def get_chapters(self, instance): serializer = ChapterSerializer(Chapter.objects.filter(location=instance.books.name), many=True, context=self.context) return serializer.data def to_representation(self, instance): ret = super().to_representation(instance) return … -
Error code: Unhandled Exception - pythonanywhere
the error log was to logn so I put it on pastebin I am not sure how to fix this at all any help is appriecated! heres the error log https://pastebin.com/raw/eZFSUXnX -
Is there any way I can access Django template variables and URL tags in a JS file so that the user can not inspect the data and links?
I want to excess Django template variables and URL tags from my javascript file. currently, I'm doing it like follows- <script> const addcommentlink = "{% url 'post:add_comment'%}"; const postid = '{{post.id}}'; const deletecommentlink = "{% url 'post:delete_comment' %}"; const editlikelink = "{% url 'post:edit_like' %}"; const profilelink = "{% url 'instagram:profile' 'name' %}"; </script> <script src="{% static 'post/js/post_details.js' %}"></script> but I want to access it directly from the post_details.js file. Is there any way to do that? -
Call function that uses newly created model object (instance) when save model object in DJANGO
class Experience(models.Model): teacher = models.ForeignKey(User, on_delete=models.CASCADE) classroom = models.ForeignKey(Classes, on_delete=models.DO_NOTHING, verbose_name ="Clase") project = models.ForeignKey(Project, on_delete=models.DO_NOTHING, related_name="project_exp", verbose_name ="Experiencia") project_phases = ChainedManyToManyField( ProjectPhases, horizontal=True, verbose_name ="Fases de la experiencia", chained_field="project", chained_model_field="project") created_at = models.DateTimeField(auto_now_add=True, verbose_name = "Creado en") updated_at = models.DateTimeField(auto_now=True, verbose_name = "Actualizado en") class Meta: verbose_name = "Experiencia" verbose_name_plural = "Experiencias" default_related_name = 'experience' ordering = ['id'] def __str__(self): return f'Experiencia {self.id} - {self.project}' def save(self, *args, **kwargs): super(Experience, self).save(*args, **kwargs) ## Call a function with the newly created object @receiver(post_save, sender=Experience) def create_evaluations(sender, instance, **kwargs): if instance: create_experience_evaluation(instance) -
Package not found at IN heroku web application
I have a DJANGO web application which was deployed via heroku, it runs a particular process on media files. Whenever a user submits a form containing a file, the application saves the file in the database hence giving it a particular URL e.g https://my-special-app-name.herokuapp.com/media/documents/2020-10-08/test1.docx. Once the file is saved, the application uses celery to perform some tasks on the saved file which will then be saved in my database. I was able to get celery working by including worker: celery -A myprojectName worker -l info in my Procfile, then heroku ps:scale worker=1 after git push heroku master as stated in the heroku docs. Everything seems to work fine, celery receives tasks from the redis server but it keeps logging the same type of error e.g (Package not found at '/app/media/documents/2020-10-08/test1.docx') and the web application doesn't perform the process.I am able download the file from the server by accessing the url e.g https://my-special-app-name.herokuapp.com/media/documents/2020-10-08/test1.docx, unfortunately I have no idea why celery is receiving the app url with (/app/) preceding everything and not performing the desired process.It worked fine in development with an example url of http://127.0.0.1:8000//media/documents/2020-10-08/test1.docx. I don't know how to fix the error and I will really appreciate your help. enter … -
Display fields from one model in another in Django Admin connected with a Foreignkey
I have two models, one for uploaded files and one for comments. I now want to display the comments in the Admin view of each uploaded file. So for example, if I upload a file TestFile1, once I click on it in the Uploaded view in Django admin, I want to have all of the comments associated with that file. Is this possible? class Uploaded(models.Model): objects: models.Manager() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="users") file = models.FileField(upload_to=user_directory_path) def __str__(self): return f"{self.description} {self.file}" class Comment(models.Model): objects: models.Manager() file = models.ForeignKey('Uploaded', on_delete=models.CASCADE, related_name='comments') text = models.TextField() def __str__(self): return self.text