Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I find the view mapped to certain url in django with pycharm?
I'm debugging multiple apis built with django rest framework , How can I find the views mapped to a certain URL?. I'm currenty using pycharm so is there any plugin than can help EX: in url : /api/users/business-segment/ how can I know the view that maps to this url ? -
is it possible to override a foreign key relation with a custom method/property
Context I'm working on refactoring a Django 2.X app, particularly the core model, CoreModel. There's a single database (Postgres) containing all related tables. Instances of CoreModel will no longer live in Postgres after this refactor, they will live somewhere else but outside the scope of the Django project, let's say some AWS No-SQL database service. There also several satellites models SateliteModel to CoreModel which will continue to live on Postgres, but CoreModelis currently modelled as a foreign key field. class CordeModel(models.Model): pass class SatelliteModel(models.Model): core = models.ForeignKey(CoreModel) def some_instance_method(self): return self.core.calculate_stuff() # <- override self.core! Problem The code is filled with mentions to the CoreModel relation, and I haven't been able to successfully solved this issue. My first naive approach was to implement a @property getter method, that way I had enough flexibility to do something like: @property def core(self): try: # ORM return self.core except CoreNotFound: # External datastore return aws_client.fetch_core() With this snippet I have a circular dependency on the core name, so the idea is out. I could rename the foreign key: but I would much rather not touch the database schema. After all I'm already refactoring the central part of the app, and that's an very … -
HOW TO ISSUE Roll no. slips to SCHOOLS
I am beginner.Learning Django. In project, i taken students data from some schools to take a special exam.NOW HOW TO ISSUE Roll no. slips to SCHOOLS. my School model is onetooneField link with User. And School is parent class of Student Model. Please suggest me what to learn next to achieve it. -
Handling input from an input field or form field with Django
So I'm trying to learn Django by building a very simple single-page site that just takes emails for subscriptions and stores it into djangos backend. I made an html page for the site that has form and input elements, and I've successfully rendered the page by following the documentation. I even built a model called 'subscriptions', to take email strings, but now i'm unsure about how to handle the input from the html page and store the emails in the backend. All the documentation is kind of confusing cause it instructs me to build a separate .html file for the form, and handle it in another views and model page, which just seems unnecessary. Does django necessitate handling input in a separate forms.html file? Or can i just use the index.html, and add views to 'views.py' or revise 'models.py'? I'm pretty confused, all help and examples are very appreciated! -
I'm trying to use data pulled from CoinMarketCap API, I can't access all the information from the dictionary
It looks like the information is a List with embedded dictionary. I'm a beginner and don't fully understand how to pull the information from lists/dictionaries. EXP: 'data': [{'id': 1, 'name': 'Bitcoin', 'symbol': 'BTC', 'slug': 'bitcoin', 'num_market_pairs': 7956, 'date_added': '2013-04-28T00:00:00.000Z', 'tags': ['mineable'], 'max_supply': 21000000, 'circulating_supply': 18344737, 'total_supply': 18344737, 'platform': None, 'cmc_rank': 1, 'last_updated': '2020-04-25T16:09:51.000Z', 'quote': {'USD': {'price': 7582.532132, 'volume_24h': 33998463530.3441, 'percent_change_1h': -0.102004, 'percent_change_24h': 0.497048, 'percent_change_7d': 5.20237, 'market_cap': 139099557755.5893, 'last_updated': '2020-04-25T16:09:51.000Z'}}} I can pull the information in 'data', but I can't pull the information in the 'quote':{'USD'} portion of the dictionary. My code in my template is: {% for coin_Key in cmc_Data.data %} {{ coin_Key }} <tr> <td>{{ coin_Key.cmc_rank }}</td> <td>{{ coin_Key.name }}</td> <td>{{ coin_Key.symbol }}</td> <td>{{ coin_Key.quote.price }}</td> <td>{{ coin_Key.quote.market_cap }}</td> <td>{{ coin_Key.total_supply }}</td> <td>{{ coin_Key.max_supply }}</td> </tr> {% endfor %} the {{ coin_Key }} lists all the information, so I know it's pulling from the API properly. I'm not sure I explained this properly, hit me up with any questions and I'll do my best to clarify. -
Django: Create object with ForeignKey from url
I am working on a Django project with two models linked by a ForeignKey. The parent model, Composition, is linked to the child model, NoteObject, by the id of Composition. in models.py class Composition(models.Model): id = models.AutoField(primary_key=True) ... class NoteObject(models.Model): id = models.AutoField(primary_key=True) composition = models.ForeignKey(Composition, on_delete=models.CASCADE) ... Once a composition is created, the user needs to be able to create NoteObjects that belong to that composition. The notes are created with the following method: in views.py class NoteCreateView(CreateView): model = NoteObject template_name = 'entry.html' fields = ['duration', 'pitch', 'accidental', 'octave'] success_url = reverse_lazy('compositions') def get_context_data(self, **kwargs): kwargs['notes'] = NoteObject.objects.filter( composition=self.kwargs['composition']) return super(NoteCreateView, self).get_context_data(**kwargs) The get_context_data method is there to display only the notes for the current composition. The current composition comes from the id of the composition that is part of the url where <composition> is the id of the composition. in urls.py path('entry/<composition>/', views.NoteCreateView.as_view(), name='entry') When I save a NoteObject, what do I need to do in order to set the value of the ForeignKey to be the value within <composition>? in models.py def save(self, *args, **kwargs): composition_id = ???????? self.composition_id = composition_id super(NoteObject, self).save(*args, **kwargs) How do I get the value of kwarg in the CreateView to … -
Unknown Indentation Error in the following code
this is the code: 3nd line is giving error. class RawMassegeForm(forms.Form): subject = forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Enter your Subject'})) name = forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Enter your Name'})) email = forms.EmailField(widget= forms.EmailInput(attrs={'placeholder':'Enter your email'})) message = forms.TextField(widget= forms.Textarea(attrs={'placeholder':'Enter Your Message here...'})) -
i want to create a MY ACCOUNT or MY PROFILE page on my django website. but my "account.html" template doesnt render
below is the VIEWS.PY code from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Tutorial from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login, logout, authenticate from django.contrib import messages from .forms import NewUserForm from .models import Tutorial, TutorialCategory, TutorialSeries from django.http import HttpResponse from django.contrib.auth.decorators import login_required def single_slug(request, single_slug): # first check to see if the url is in categories. categories = [c.category_slug for c in TutorialCategory.objects.all()] if single_slug in categories: matching_series = TutorialSeries.objects.filter(tutorial_category__category_slug=single_slug) series_urls = {} for m in matching_series.all(): part_one = Tutorial.objects.filter(tutorial_series__tutorial_series=m.tutorial_series).earliest("tutorial_published") series_urls[m] = part_one.tutorial_slug return render(request=request, template_name='main/category.html', context={"tutorial_series": matching_series, "part_ones": series_urls}) tutorials = [t.tutorial_slug for t in Tutorial.objects.all()] if single_slug in tutorials: this_tutorial = Tutorial.objects.get(tutorial_slug=single_slug) tutorials_from_series = Tutorial.objects.filter(tutorial_series__tutorial_series=this_tutorial.tutorial_series).order_by('tutorial_published') this_tutorial_idx = list(tutorials_from_series).index(this_tutorial) return render(request=request, template_name='main/tutorial.html', context={"tutorial": this_tutorial, "sidebar": tutorials_from_series, "this_tut_idx": this_tutorial_idx}) return HttpResponse(f"'{single_slug}' does not correspond to anything we know of!") #homepage def homepage(request): return render(request=request, template_name='main/categories.html', context={"categories": TutorialCategory.objects.all}) #register function def register(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, f"New Account Created: {username}") login(request, user) messages.info(request, f"You are now logged in as {username}") return redirect("main:homepage") else: for msg in form.error_messages: messages.error(request, f"{msg}: {form.error_messages[msg]}") form = NewUserForm return render(request, "main/register.html", context={"form":form}) #logout def logout_request(request): logout(request) … -
Retrieve data from queryset and pass to template in django
I have a model as bellow: class Artwork(models.Model): title = models.CharField(max_length=120) collection = models.CharField(max_length=120,null=True) slug = models.SlugField(blank=True, unique=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=20, default=0) image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) banner = models.ImageField(upload_to='artworks/banner') video = models.FileField(upload_to='artworks/video',blank=True,null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=15) views_count = models.IntegerField(default=150) featured = models.BooleanField(default=False) active = models.BooleanField(default=True) created = models.DateTimeField(default=timezone.now) and The view as bellow: def artwork_list_view(request): queryset = Artwork.objects.all() context = { 'objet_list':queryset, } return render(request, "artworks/list.html", context) I use the queryset in template as bellow: <div style='min-height:80px;'><p >First Collection</p></div> {% for obj in object_list %} <div class="workSeriesThumbnailStrip"> {% if obj.image %} <a href="{{ obj.get_absolute_url }}"><img src="{{ obj.image.url }}" style="float:left;width:67px;height:87px;margin:10px;" ></a> {% endif %} </div> {% endfor %} </div> know I have more than one collection and want to place a for loop in collections to show items of each collection in one row. But as I'm new in django, I don't know how to retrieve the list of collections and pass them to template. please help me. -
Django, Docker and SMTP - messages don't send
I'm trying to send an email through Django and a namshi/smtp Docker image. Code: settings.py: EMAIL_HOST = 'smtp' EMAIL_PORT = '25' DEFAULT_FROM_EMAIL = 'noreply@<domain name here>' # obviously, domain name is set here docker-compose.yml: smtp: image: namshi/smtp restart: always ports: - '25:25' volumes: - ./:/web environment: - KEY_PATH=/web/config/ssl_keys/privkey.pem - CERTIFICATE_PATH=/web/config/ssl_keys/fullchain.pem I'm using django-allauth to send a password reset email. This is the console output when I request for password reset for my account with a valid Yandex email address: smtp_1 | 282 LOG: MAIN smtp_1 | 282 <= noreply@<domain> H=<project name>_web_1.<project name>_default (<some sort of id>) [<some ip here>] P=esmtp S=8248 id=<i feel like it's better if i remove this>@<some sort of id> smtp_1 | 282 LOG: smtp_connection MAIN smtp_1 | 282 SMTP connection from shpplace_web_1.shpplace_default (<some sort of id>) [<some ip>] closed by QUIT web_1 | <my ip?>:34856 - - [25/Apr/2020:21:09:33] "POST /accounts/password/reset/" 302 - smtp_1 | 283 Exim version 4.92 uid=101 gid=101 pid=283 D=80001 smtp_1 | Berkeley DB: Berkeley DB 5.3.28: (September 9, 2013) smtp_1 | Support for: crypteq iconv() IPv6 GnuTLS move_frozen_messages DANE DKIM DNSSEC Event OCSP PRDR SOCKS TCP_Fast_Open smtp_1 | Lookups (built-in): lsearch wildlsearch nwildlsearch iplsearch cdb dbm dbmjz dbmnz dnsdb dsearch nis nis0 passwd … -
How to change title for the tab of User Change Page of Django admin?
I'm working on Django and wanted to change the default title for the tab of User Change Page of Django admin as marked in the pic : my admin.py file is: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): change_list_template='change_list_form.html' change_form_template = 'change_form.html' add_form_template='add_form.html' list_display = ('first_name','last_name','email','is_staff', 'is_active',) list_filter = ('first_name','email', 'is_staff', 'is_active',) search_fields = ('email','first_name','last_name','a1','a2','city','state','pincode') ordering = ('first_name',) add_fieldsets = ( ('Personal Information', { # To create a section with name 'Personal Information' with mentioned fields 'description': "", 'classes': ('wide',), # To make char fields and text fields of a specific size 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','check', 'password1', 'password2',)} ), ('Permissions',{ 'description': "", 'classes': ('wide', 'collapse'), 'fields':( 'is_staff', 'is_active','date_joined')}), ) So can we change it?? If yes then how?? Thanks in advance!! -
Django : How to show logged in users data from database
I am working on invoice management system having in which user can add invoice data and it will save in database and whenever user logged in the data will appear on home page.but the problem if whenever any user logged in the home page showing other users data also but i want active users data only. could you guys help me. here is my home page,you can see i am logged in through user 1 but at home page user 2 data also appear here is my code views.py from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView ) from .models import Invoicelist def home(request): context = { 'invoices': Invoicelist.objects.all() } return render(request, 'invoicedata/home.html', context) class InvoiceListView(ListView): model = Invoicelist template_name = 'invoicedata/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'invoices' class InvoiceDetailView(DetailView): model = Invoicelist class InvoiceCreateView(LoginRequiredMixin, CreateView): model = Invoicelist fields = ['issuer','invoice_number','date','amount','currency','other'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class InvoiceUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Invoicelist fields = ['issuer','invoice_number','date','amount','currency','other'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): invoice = self.get_object() if self.request.user == invoice.author: return True return False class InvoiceDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Invoicelist success_url = '/' … -
coveralls doesn't recognize token when dockerized django app is run in TravisCI, but only from pull requests
I'm getting this error from TravisCI when it tries to run a Pull Request coveralls.exception.CoverallsException: Not on TravisCI. You have to provide either repo_token in .coveralls.yml or set the COVERALLS_REPO_TOKEN env var. The command "docker-compose -f docker-compose.yml -f docker-compose.override.yml run -e COVERALLS_REPO_TOKEN web sh -c "coverage run ./src/manage.py test src && flake8 src && coveralls"" exited with 1. However, I do have both COVERALLS_REPO_TOKEN and repo_token set as environment variables in my TravisCI, and I know they're correct because TravisCI passes my develop branch and successfully sends the results to coveralls.io: OK Destroying test database for alias 'default'... Submitting coverage to coveralls.io... Coverage submitted! Job ##40.1 https://coveralls.io/jobs/61852774 The command "docker-compose -f docker-compose.yml -f docker-compose.override.yml run -e COVERALLS_REPO_TOKEN web sh -c "coverage run ./src/manage.py test src && flake8 src && coveralls"" exited with 0. How do I get TravisCI to recognize my COVERALLS_REPO_TOKEN for the pull requests it runs? -
Writing to txt file in UTF-8 - Python
My django application gets document from user, created some report about it, and write to txt file. The interesting problem is that everything works very well on my Mac OS. But on Windows, it can not read some letters, converts it to symbols like é™, ä±. Here are my codes: views.py: def result(request): last_uploaded = OriginalDocument.objects.latest('id') original = open(str(last_uploaded.document), 'r') original_words = original.read().lower().split() words_count = len(original_words) open_original = open(str(last_uploaded.document), "r") read_original = open_original.read() characters_count = len(read_original) report_fives = open("static/report_documents/" + str(last_uploaded.student_name) + "-" + str(last_uploaded.document_title) + "-5.txt", 'w', encoding="utf-8") # Path to the documents with which original doc is comparing path = 'static/other_documents/doc*.txt' files = glob.glob(path) #endregion rows, found_count, fives_count, rounded_percentage_five, percentage_for_chart_five, fives_for_report, founded_docs_for_report = search_by_five(last_uploaded, 5, original_words, report_fives, files) context = { ... } return render(request, 'result.html', context) report txt file: ['universitetindé™', 'té™hsili', 'alä±ram.', 'mé™n'] was found in static/other_documents\doc1.txt. ... -
How to get two distinct objects from the same view function in django according to the requirements?
I have 3 models in Django which are like: class Category(models.Model): name = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) class Subcategory(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True) class Product(models.Model): name = models.CharField(max_length=200, unique=True) category = models.ForeignKey(Subcategory, on_delete=models.CASCADE, related_name='products') slug = models.SlugField(max_length=150, unique=True) The view function which I want to modify currently looks like this: def product_list(request, category_name): subcategory = get_object_or_404(Subcategory, slug=category_name) subcategory_name = subcategory.name product_list = subcategory.products.all() context = { 'name':subcategory_name, 'product_list':product_list, } return render(request, 'products/product_list.html', context) In one of my html templates each category is displayed along with the subcategories under it. If anyone clicks on the category name instead of the subcategory under that category name, I want the views function to display all the products which come under that category and not just one subcategory under that given category. I can create a separate view to do that but I want to know if there's a way to do that in the same view function. -
django get model help pls by raxim
I have 3 Profil Stimul_Slov and OTVET model inside Stimulus_words there are questions, the participant must answer questions and questions must be saved on the OTVET model how can I put out Stimulus_words questions and save answers to OTVET models.py from django.db import models from django.contrib.auth.models import User class Profil(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fullname = models.CharField(max_length=100, blank=True) age = models.DateField(blank=True) specialite = models.CharField(max_length=100,blank=True) language = models.CharField(max_length=100,blank=True) def __str__(self): return self.fullname class Stimul_slov(models.Model): stimulus = models.CharField(max_length=200, blank=True) def __str__(self): return "%s" % ( self.stimulus) class Otvet(models.Model): answer = models.CharField(max_length=200, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) stimul = models.ForeignKey(Stimul_slov, on_delete=models.CASCADE) def __str__(self): return "%s: %s ----> %s" % (self.user ,self.stimul, self.answer) -
No ID assigned to objects when created in Django
I have a Class in my models.py named Order class Order(models.Model): customer_name = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='customer_name', ) order_individual_price = models.IntegerField(default=1) order_name = models.CharField(max_length=200) order_quantity = models.IntegerField(default=1) order_total_price = models.IntegerField(default=1) def __str__(self): return self.order_name In my views.py I create a new instance of order when a button is pressed def ordering(request): latest_order = Order.objects.all() menu = Menu.objects.all() if request.method == 'POST': if request.user.is_authenticated: menu_instance = request.POST.get('add') if menu_instance: get_order = Menu.objects.get(id=menu_instance) get_price = get_order.Menu_price new_order = Order.objects.create(customer_name=request.user, order_name=get_order, order_individual_price=get_price) return redirect('shop-ordering') order_instance = request.POST.get('delete') else: messages.info(request, f'Please Sign In First') return redirect('login') return render(request, 'shop/ordering.html', {'title':'Ordering', 'latest_order': latest_order, 'menu':menu}) However, when I try to get the ID of the object it throws this error Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/alan/Desktop/FRIENDS_CAFE_DJANGO/venv/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/alan/Desktop/FRIENDS_CAFE_DJANGO/venv/lib/python3.8/site-packages/django/db/models/query.py", line 415, in get raise self.model.DoesNotExist( shop.models.Order.DoesNotExist: Order matching query does not exist. I didn't touch any of the init files and since django creates the ID automatically, I'm really confused on why its not assigning each order a ID. -
I want to make multi step form using django form wizard so if anyone has done a project on it please do share
I am doing a project on multi step form in django and i need to make 5 step multi form with different details in it so if anyone has made it do share it with me. Thanks -
Django query based on another query results
I have 4 models in my simplified design class modelA(models.Model): name = models.CharField() class modelsUser(model.Model): username = models.CharField() class bridge(models.Model): user = models.ForeignKey(modelUser, on_delete=models.CASCADE, related_name='bridges') modelA = models.ForeignKey(modelA, on_delete=models.CASCADE, related_name='bridges') class subModelA(models.Model): modelA = models.ForeignKey(modelA, on_delete=models.CASCADE, related_name='subModelAs') value = models.IntegerField() class subModelB(models.Model): modelA = models.ForeignKey(modelA, on_delete=models.CASCADE, related_name='subModelBs') text = models.TextField() What I am trying to to is to get all subModelBs and subModelAs that are for modelAs for which given modelUser have bridge. I've started with this: user = modelUser.objects.get(pk=1) bridges = user.bridges.all() What I've been thinking is something like this: subModelBs = modelB.objects.filter(modelA__in=bridges__modelA) but unfortunately it doesn't work because of error that __modelA is not defined. Is there any proper way to do this? -
How exactly does CASCADE work with ManyToMany Fields in Django
Im Wondering how exactly does CASCADE work with ManyToMany Fields in Django. A short example: class Project(Model): name = TextField(null=False) class Job(Model): projects = ManyToManyField(Project, on_delete=CASCADE, null=False) name = TextField(null=False) As you can see I have a ManyToManyField here. So basically a Project can have mutiple Jobs and a Job can belong to Multiple different Projects. What I want is that a Job is automatically deleted only when all Projects it belongs to are deleted. Does CASCADE work like that in this scenario? -
Can you tell me where is my mistake? I am continuously getting FALSE form.is_valid()
can you look at my code and tell me where is my mistake? I have a form class AddEditTaskForm, which has several fields and it is getting tasks_list in order to get task.list id. forms.py class AddEditTaskForm(ModelForm): def __init__(self,user,*args,**kwargs): super().__init__(*args,**kwargs) task_list=kwargs.get('initial').get('task_list') self.fields['task_list'].value=kwargs['initial']['task_list'].id due_date=forms.DateField(widget=forms.DateInput(attrs={'type':'date'}),required=False) title=forms.CharField(widget=forms.widgets.TextInput()) description=forms.CharField(widget=forms.Textarea(), required=False) completed=forms.BooleanField(required=False) def clean_created_by(self): return self.instance.created_by class Meta: model = Task exclude = [] After rendering a form. I am getting form is not valid error. views.py @login_required def list_detail(request,list_id=None,list_slug=None,view_completed=False): task_list=get_object_or_404(TaskList,id=list_id) tasks=Task.objects.filter(task_list=task_list.id) form=None if view_completed: tasks=task.filter(completed=True) else: tasks=tasks.filter(completed=False) if request.POST.getlist("add_edit_task"): form = AddEditTaskForm(request.user,request.POST,initial={'task_list':task_list}) if form.is_valid(): new_task = form.save(commit=False) new_task.created_by = request.user new_task.description = bleach.clean(form.cleaned_data["description"], strip=True) form.save() messages.success(request, 'New task "{t}" has been added.'.format(t=new_task.title)) return redirect(request.path) else: messages.success(request,'form is not valid') context={ 'list_id': list_id, 'list_slug': list_slug, 'task_list': task_list, 'tasks':tasks, 'form':form, 'view_completed':view_completed, } return render(request,'todo/list_detail.html',context) -
Django: How to fetch data from two models and display it i template?
There are two models Product and ProductImage my code is as follows: models.py class Product(models.Model): product_name = models.CharField(max_length=100) product_weight = models.CharField(max_length=30) models.py from django.db.models.signals import post_save, pre_save from django.dispatch import receiver _UNSAVED_IMAGEFIELD = 'unsaved_imagefield' def upload_path_handler(instance, filename): import os.path fn, ext = os.path.splitext(filename) return "images/{id}/{fname}".format(id=instance.product_id, fname=filename) class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.DO_NOTHING) image = models.ImageField(upload_to=upload_path_handler, blank=True) @receiver(pre_save, sender=ProductImage) def skip_saving_file(sender, instance, **kwargs): if not instance.pk and not hasattr(instance, _UNSAVED_IMAGEFIELD): setattr(instance, _UNSAVED_IMAGEFIELD, instance.image) instance.image = None @receiver(post_save, sender=ProductImage) def update_file_url(sender, instance, created, **kwargs): if created and hasattr(instance, _UNSAVED_IMAGEFIELD): instance.image = getattr(instance, _UNSAVED_IMAGEFIELD) instance.save() views.py def products(request): products = Product.objects.all() context = { 'products' : products } return render(request, 'products/products.html', context) products.html {% if products %} {% for product in produucts %} <div class="col-sm-5 col-lg-5"> <div class="equipmentbox"> <div class="equipmentimgbox"> <img src="{{"**IMAGE URL HERE**"}}"> </div> <a href="">{{ product.product_name }}</a> </div> </div> {% endfor %} {% else %} <div class="col-md-12"> <p>No Products Available</p> </div> {% endif %} Product table contains product details and ProductImage contains images related to particular product. I have a listing page where I wan to display ProductTitle and Image. How can I fetch image from the other table and display it with product title. Thanks in advance. -
Visualize link has been clicked or not
I'm currently working on a web app in which I would like to display to the user whether they have visited the link already or not. The code that displays the links is fairly simple, as seen below. <ul> <li><a href="http://google.com">google</a></li> <li><a href="http://facebook.com">facebook</a></li> <li><a href="http://amazon.com">amazon</a></li> </ul> What I would like is to visualize that a link has been clicked by just adding a checkmark, or something along those lines, to the right of the link. How would I go about doing that? I'm working with Django for this project so a Django-specific solution would be great. -
npx create-react-app command does not work, returns ES module error instead
Here is the command that I ran to try to create a React app and the resulting error log. I have been able to successfully run it three times before with the command $ npx create-react-app, but now every time that I run it, it does not work and instead returns an error related to ES modules. I have been experimenting with many ways to integrate React with Django, but I don't think that I edited any core files in doing so that would have caused this error. I am completely new to React and Node.js so any advice would be greatly appreciated. npx: installed 99 in 7.591s Must use import to load ES Module: /Users/(username)/.npm/_npx/27993/lib/node_modules/create-react-app/node_modules/is-promise/index.js require() of ES modules is not supported. require() of /Users/(username)/.npm/_npx/27993/lib/node_modules/create-react-app/node_modules/is-promise/index.js from /Users/(username)/.npm/_npx/27993/lib/node_modules/create-react-app/node_modules/run-async/index.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules. Instead rename /Users/(username)/.npm/_npx/27993/lib/node_modules/create-react-app/node_modules/is-promise/index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /Users/(username)/.npm/_npx/27993/lib/node_modules/create-react-app/node_modules/is-promise/package.json.``` -
using form valid method to acess objects from requests made in django
i'm creating a small web application where users can review cars in my web app i made reviews to be relatable objects to cars and as such each review has a car attribute as a ForeignKey. I went on to make a createview for reviews though with a urlpattern containing a car object id . my goal is to find a way of the review form to know which car i am reviewing just like how i used form valid method to enable the form to grab current user making requests to server my models from django.db import models from django.urls import reverse from categories.models import Category # Create your models here. class Car(models.Model): image = models.ImageField(upload_to='images/cars/') make = models.CharField(null=False, blank=False, max_length=30) model = models.CharField(null=False, blank=False, max_length=30) year = models.IntegerField(null=False, blank=False) transmission = models.CharField(null=False, blank=False, max_length=30) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.model def get_absolute_url(self): return reverse('car_detail', args=[str(self.id)]) from django.db import models from django.urls import reverse from users.models import CustomUser from cars.models import Car # Create your models here. class Review(models.Model): title = models.CharField(max_length=20) description = models.TextField(max_length=160) date_added = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) car = models.ForeignKey(Car, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('review_detail', args=[str(self.id)]) views from …