Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why doesn't Preview on Mac respect the "read only" flag in PDF files?
I'm working on a django project using pdfrw to fill a fillable pdf form. I'm setting the Ff = 1 flag in order to make the fields read-only. for annotation in template_path.Root.AcroForm.Fields: # the code goes here annotation.update(pdfrw.PdfDict(Ff=1)) This seems to work in every viewer I tested so far except for "Preview" the native mac app to open and display pdf files. Why is that? Am I missing something? Is there another way of achieving this? -
Last digit not matched in the barcode image file, django
I have a model where the produc_attr is being stored in a CharField (string). Using the get_code method, I am converting the string of the product_attr to a number (13 digits), which is shown in my code_number column. Next, I'm generating a barcode image via the get_barcode method. The problem is: the number on the barcode PNG (image) file is wrong. That is, the last number out of a total of 13 digits is more or less being printed which I have shown by adding a column (printed_number) at the end of the table. Any help would be appreciated. class Inventory(models.Model): product = models.ForeignKey('Product', blank=True, null=True, on_delete=models.SET_NULL) product_attr = models.CharField(max_length=50, blank=True, null=True) code_number = models.CharField(max_length = 13, blank=True, editable=False) barcode = models.ImageField(upload_to = 'barcode/', blank=True) def __str__(self): return self.product def get_code_number(self): str1 = self.product_attr.encode() hash1 = hashlib.sha1() hash1.update(str1) return str(int(hash1.hexdigest(), 16))[:13] def get_barcode(self): EAN = barcode.get_barcode_class('ean13') ean = EAN(f'{self.code_number}', writer=ImageWriter()) buffer = BytesIO() ean.write(buffer) return self.barcode.save('barcode.png', File(buffer), save=False) def save(self, *args, **kwargs): self.code_number = self.get_code_number() self.get_barcode() super(Inventory, self).save(*args, **kwargs) -
PyCharm - pip freeze env terminal displaying global packages
I've been using PyCharm for a Django project for a couple months now. Due to some complications I had to rename the project and move it around the directories. The project uses a virtual environment that works as the Python Interpreter. When I run the local server of the project everything works fine, no errors reading and writing into the database, paths, views, etc. (note that I had to make a couple changes in order for the project to work fine) Now... when opening the PyCharm terminal it says I'm in the virtual environment, however, when I "pip freeze" to see all of the packages that are installed in the environment, it returns all of the packages installed in the computer. What am I missing? This is the terminal: This are the packages installed in the interpreter: -
how to create test into with django
I just started to create an app and now I m trying to do somme test on it so I write a test code however it always return a 200 code even when I put a wrong URL that doesn't exist here is the code class TestViews(TestCase): c=None response = None def setUp(self): User = apps.get_model('auth','user') User.objects.create_superuser("admin", "Admin", "Admin") self.c = Client() self.response = self.c.post('/login/', {'username': 'admin', 'password':'admin'}) def testAudit(self): self.response.get('/actors/audit') self.assertEqual(self.response.status_code,200) def testGetFile(self): self.response.get('/actors/GetFile',{'file_name' : 'file1'}) self.assertEqual(self.response.status_code,200) def testDetail(self): self.response.get('/ffff') self.assertEqual(self.response.status_code,200) can anyone help or does anyone went throught this problem tnx -
expected string or bytes-like object django while saving to db
I am trying to save my model to db but I keep getting the error expected string or bytes-like object. I tried searching and I thing I am passing it as tuple but I cannot figure out where I made the mistake. Here is the view of the post route: class PreviousSearchView(View): def post(self, request): if request.method == 'POST': searchdomain = request.POST['searchdomain'] domain = whois.whois(searchdomain) date = datetime.datetime.now() domain_name = domain.domain_name creation_date = domain.creation_date expiration_date = domain.expiration_date org = domain.org city = domain.city state = domain.state zipcode = domain.zipcode country = domain.country search = Search( searchdomain = domain_name, org = domain.org, city = domain.city, state = domain.state, zipcode = domain.zipcode, country = domain.country, user = User.objects.get(id = request.user.id), date = date, creation_date = domain.creation_date, expiration_date = domain.expiration_date, ) search.save() return redirect('/') -
How to add x months to a date based on an integerfield in django with mysql
I would like to know how to achieve the following MariaDB-Syntax using django's query expressions: select distinct CASE when (`coredb_commoncontract`.`duration_month` is not null) then (`coredb_commoncontract`.`date_start` + INTERVAL `coredb_commoncontract`.`duration_month` MONTH) else null end as `date_end` from `coredb_commoncontract` The duration of a contact is given as an integer in CommonContract.duration_month. I am trying to calculate the end date in an annotation. EDIT: the part I am having problems with is ... INTERVAL `coredb_commoncontract`.`duration_month` MONTH -
Django: Show a field of a model depending on the value of another field
I have a model in my Django project called Category. models.py class Category(models.Model): parent_category=models.ForeignKey('self', related_name='categories', on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, unique= True) image = models.ImageField(upload_to='categories/', blank=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name Now in admin, I want to show the image field only if the parent field is not empty, on the fly. The parent field is a dropdown. I have a tried this, but it does not work: admin.py @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): def get_fields(self, request, obj=None): fields = super(CategoryAdmin, self).get_fields(request, obj) for field in fields: if field == 'parent_category' and 'parent_category'== None: fields.remove('image') return fields prepopulated_fields = {'slug' : ('name',)} It shows the image field regardless of the value of parent_category. Any suggestions? Thanks -
How make @login_required with AJAX?
I have follow_user functions with JSON response. Looking for some way to make @login_required for 'follow_user' function. def follow_user(request): user = request.user if request.method == "POST": user_id = request.POST.get("user_id") user_obj = Profile.objects.get(id=user_id) if user not in user_obj.followers.all(): UserFollowing.objects.get_or_create(following_from=user, follow_to=user_obj) else: UserFollowing.objects.filter(following_from=user, follow_to=user_obj).delete() return JsonResponse({"status": "ok", "followers_number": user_obj.followers.count()}) and in template I have: {% if request.user.username != profile.username %} <form action="{% url 'users:follow_user' %}" method="POST" class="follow-form" id="{{ profile.id }}"> {% csrf_token %} <input type="hidden" name="user_id" value="{{ profile.id }}" class="follow_id"> <button type="submit" class="follow-btn{{ profile.id }} follow-btn"> {% if request.user not in profile.followers.all %} Follow {% else %} Unfollow {% endif %} </button> </form> <script> $(document).ready(function () { $('.follow-form').submit(function (e) { e.preventDefault(); const csrf = $('input[name ="csrfmiddlewaretoken"]').val() const user_id = $('.follow_id').val(); $.post('/users/followers/', {'user_id': user_id, 'csrfmiddlewaretoken': csrf}, function (data) { console.log(data); $('.total-followers').html(`Obserwujących (${data.followers_number})`) if ($('.follow-btn').html().trim() === 'Follow') { $('.follow-btn').html('Unfollow'); } else { $('.follow-btn').html('Follow'); } }); }); }); </script> How can I make login required to this function? I've tried @login_required but this solutin doesn't work. Was thinking about redirect to login after click 'follow' button or message 'You must log in first' -
Golang - GORM how to create a model for an existing table?
According to the source from this link : https://gorm.io/docs/index.html To declaring a model, we do this: type User struct { ID uint Name string Email *string Age uint8 Birthday *time.Time MemberNumber sql.NullString ActivatedAt sql.NullTime CreatedAt time.Time UpdatedAt time.Time } Then run migration to create it on the database. However, I could not find any document mentioning about declaring a model that already exist in database. I suppose there is something like this: type User struct { ID uint Name string This_struct(User).belongs_to_an_existing_table_named("a_table_name") -- this is an example to explaning what I mean If and only if we do it by declaring a struct with the same name with an existing table. Can I change the name for simplicity in my code ? -
How to pass slug in generic view (Django)
How can i pass a slug in this generic 'ListView', I was confused by the get_context_data function. The slug is in the 'Profile' model. views.py class PostListView(ListView): model = Post template_name = 'feed/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 10 def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) if self.request.user.is_authenticated: liked = [i for i in Post.objects.all() if Like.objects.filter(user = self.request.user, post=i)] context['liked_post'] = liked return context -
This page isn’t working right nowIf the problem continues, contact the site owner. HTTP ERROR 405 trying to fix this problem in django?
When I click on delete button, I am getting an error: This page isn’t working right now the problem continues, contact the site owner. HTTP ERROR 405 This is mine view.py file: from django.shortcuts import render,get_object_or_404 from django.http import HttpResponse from django.views.generic import ListView,DetailView, CreateView, UpdateView, DeleteView from .models import Post, TaskCategory from .forms import PostForm from django.urls import reverse_lazy class DeletePostView(DetailView): model = Post template_name = 'delete_post.html' success_url = reverse_lazy('PostPage') urls.py file: from django.urls import path # from . import views from .views import PostHomeView,PostDetail,NavFooter,PostPageView,AddPost,UpdatePost,DeletePostView urlpatterns = [ path('', PostHomeView.as_view(), name ='home'), path('PostDetail/<int:pk>', PostDetail.as_view(), name ='post_detail'), path('PostPage/', PostPageView, name ='post_page'), path('AddPost/', AddPost.as_view(), name = 'add_post'), path('PostDetail/UpdatePost/<int:pk>', UpdatePost.as_view(), name = 'update'), path('DeletePost/<int:pk>/', DeletePostView.as_view(), name = 'delete'), ] HTML delete_page.html file: {% extends "nav_footer.html" %} {% load static %} {% block content %} <div class="form-group"> <p>{{ post.task_title }}</p> <p>{{ post.task_discription }}</p> <p>{{ post.recommended_tools }}</p> <p>{{ post.budget }}</p> <form method="post"> {% csrf_token %} <button class="btn btn-secondary">Delete</button> </form> </div> {% endblock %} And this is modes.py from django.contrib.auth.models import User from django.db import models from django.urls import reverse class TaskCategory(models.Model): category_title = models.CharField(max_length=50) def __str__(self): return self.category_title class Post(models.Model): task_title = models.CharField(max_length=250) task_discription = models.CharField(max_length=250) task_category = models.ForeignKey(TaskCategory, on_delete=models.CASCADE) recommended_tools = models.CharField(max_length=250) budget … -
python Django NoReverseMatch error to product_detail.html
my product.html works fine but when I click on the link to take me to product_detail.html, I keep getting NoReverseMatch error. I have kept everything you will need to help me out below. I appreciate it if anyone of you help me because am stuck in this error for 2 days. My Django folder structure is as follows src/urls.py urlpatterns = [ path('admin/', admin.site.urls), url(r'', include('main.urls')), url(r'contact/', include('contact.urls')), url(r'product/', include('product.urls')), ] product/urls urlpatterns = [ url(r'^$', product, name='product'), path('<slug:slug>/', ProductDetail.as_view(), name='product_detail'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) product/views.py def product(request): products = Products.objects.all().order_by("-id") page = request.GET.get('page', 1) paginator = Paginator(products, 6) try: products = paginator.page(page) except PageNotAnInteger: products = paginator.page(1) except EmptyPage: products = paginator.page(paginator.num_pages) context = { 'products': products } return render(request, 'products.html', context) class ProductDetail(generic.DetailView): model = Products template_name = 'products_detail.html' product.html {% for p in products %} <div class="mb-4 mb-lg-4 col-sm-6 col-md-6 col-lg-4"> <div class="block-service-1-card"> <a href="{% url 'product_detail' p.slug %}" class="thumbnail-link d-block mb-4"> <img src="{{ p.product_image.url }}" alt="Image" class="img-fluid" style="height: 400px; width: 400px"> </a> <h3 class="block-service-1-heading mb-3"><a href="{% url 'product_detail' p.slug %}"> {{ p.product_title }} </a></h3> <div class="block-service-1-excerpt"><p>{{p.product_description|slice:":20" }} <a href="{% url 'product_detail' p.slug %}" class="d-inline-flex align-items-center block-service-1-more"><span>Find out more</span> <span class="icon-keyboard_arrow_right icon"></span></a></p></div> </div> </div> {% endfor %} products_details.html … -
Django Ajax Form Submition: Reverse for 'find_search' with arguments '('',)' not found
First question: i am trying to make a search page where you can filter posts by categories and genres. I know that a search should be a GET request but i am going to filter them manually so that i can have it done by a button click instead of a filter form with ModelMultipleChoiceFilter because buttons look better. So my question is: can i pass data in with a GET Request? Second question: I am trying to pass a list of genres through an AJAX call so that i can filter by them but at the point where my form is placed the list doesn't exist yet so i am getting this error Reverse for 'find_search' with arguments '('',)' not found. 1 pattern(s) tried: ['find/searchproduct=genres=(?P<genres_selected>[^/]+)$'] and in the traceback this is highlighted return render(request, 'find/find.html', context) so my question is: How do i fix this error? or is there a better way to do this (i have tried many ways but this one seems close to what the solution would be)? Here is some relevant code for what i am doing templates: <form class="filter_form" action="{% url 'find_search' genres_selected %}" method="GET"> <div class="filters_label">Genres</div> <div class="filter_buttons_container" name="{{ genre_list_count }}" id="genres_id"> {% … -
Agenda availabilities slot calculation API
What is the faster way to checks the availabilities of an agenda depending of the events attached to it. The main method has a start date for input and is looking for the availabilities of the next 7 days. Event settings include duration, amount of simultaneous slots. Results should take in consideration, working hours, vacancy, and authorised amount of simultaneous slots. We are actually working with a flutter app speaking to a Django backend/api. Any idea? -
how to create tag field in django form
i want to create a tag field like youtube give tage field while uploading a vedio this is what i tried in in my blog form my models.py from django.db import models from django.contrib.auth.models import User from django.utils import timezone # Create your models here. class Blog(models.Model): author = models.OneToOneField(User, on_delete=models.CASCADE,) title = models.CharField(max_length=200,blank=False,) thumbnail = models.ImageField(upload_to='blogs_thumbnail',default='blogdefa.png') tags = models.CharField(max_length=500, blank=False, default='Blog') data = models.TextField(blank=False,) published_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True,editable=False) def __str__(self): return self.title any idea how to do it i don,t know how to do it my forms.py from django import forms from django.forms import ModelForm, Textarea from django.contrib.auth.models import User from .models import Blog, comment, report forms here class BlogForm(forms.ModelForm): class Meta: model = Blog fields = '__all__' widgets = {'data': Textarea(attrs={'cols': 80, 'rows': 20, 'placeholder':'Write Here'}), 'title':forms.TextInput(attrs={'placeholder':'Your Blog Title Here'}), 'tags': forms.TextInput(attrs={'placeholder':'Please enter you content related tags'}), } exclude = ['author','published_date','update_at'] all i want is user can create his own tag for blogs like in youtube and not like stackoverflow where you have use to choose you tag please help -
Redirection in django and passing arguments
I spent some time reading through the documentation and forums, but not sure I understand this. I have this bit of code in the views of my app: def billboard_index(request): if request.method == 'POST': form = SpotiForm(request.POST) if form.is_valid(): date = form.cleaned_data['spotiread_date'] try: url = 'https://www.billboard.com/charts/hot-100/' + date billboard = requests.get(url) billboard.raise_for_status() except: print("No response") else: soup = BeautifulSoup(billboard.text, 'html.parser') positions = [int(i.text) for i in soup.find_all(name='span', class_='chart-element__rank__number')] songs = [i.text for i in soup.find_all(name='span', class_='chart-element__information__song')] artists = [i.text for i in soup.find_all(name='span', class_='chart-element__information__artist')] top100 = list(zip(positions, songs, artists)) if Top100model.objects.exists(): Top100model.objects.all().delete() for position in top100: top100data = Top100model( idtop=str(position[0]), artist=str(position[2]), song=str(position[1]) ) top100data.save() params = { 'client_id': SPOTIPY_CLIENT_ID, 'response_type': 'code', 'redirect_uri': request.build_absolute_uri(reverse('spotiauth')), 'scope': 'playlist-modify-private' } query_string = urlencode(params) url = '{}?{}'.format('https://accounts.spotify.com/authorize', query_string) return redirect(to=url) # if a GET (or any other method) we'll create a blank form else: form = SpotiForm() return render(request, 'billboardapp.html', {'form': form}) on billboard_index I have a form with one field in which user puts a date. This date is then used as an input for a webscraper. I save the scraped data in the database, this works (I know this code will break in couple instances, but I'll deal with this later). Next I … -
Django RF - nested serializers with ModelVievSet
I have a problem with nested serializers. In Shell everything works, but when I make an HTTP request its always an error like "field required". Models: class Product(models.Model): index = models.CharField(max_length=12, unique=True, db_index=True) quantity = models.PositiveIntegerField(default=0) def __str__(self): return self.index class Name(models.Model): product = models.ForeignKey(Product, related_name='names', on_delete=models.CASCADE, null=True) language = models.CharField(max_length=50, default="name_pl") title = models.CharField(max_length=300, blank=True, null=True) def __str__(self): return self.language Serializers: class ProductSerializer(serializers.ModelSerializer): names = NameSerializer(many=True) class Meta: model = Product fields = ["index", "quantity", "names"] def create(self, validated_data): names = validated_data.pop('names') product = Product.objects.create(**validated_data) for name in names: Name.objects.create(product=product, **name) return product views: class NameView(viewsets.ModelViewSet): queryset = Name.objects.all() serializer_class = NameSerializer filter_backends = [DjangoFilterBackend, filters.SearchFilter] filterset_fields = ('id',) search_fields = ['id'] class ProductView(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = [DjangoFilterBackend, filters.SearchFilter] filterset_fields = ('id',) search_fields = ['id'] permission_classes = (CustomDjangoModelPermissions,) I'm trying to POST data: data = { "index": "11111", "quantity": 1213, "names": [ {"language": "DE","title": "GER"}, {"language": "CZ","title": "CZZ"} ] } RESPOND: names field required I've tried to override create in view, to "look" whats wrong: def create(self, request): data = request.data serializer = ProductSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=201) return Response(request.data, status=400) Then I get: {'index': '11111', 'quantity': '1213', 'names': 'title'} So it … -
Problem with MaxValueValidator limits on Floatfield field
I am doing a simple inventory app that works completely through the django admin panel. I'm stuck somewhere. I created an (inline) addition for the model in the Admin panel. Here, I can show the current total number of stocks "based on the product" that I received from the toplamstok(). enter image description here But I can't set a limit up to the current inventory quantity for the quantity model using the same function. I also get an error totalstock() missing 1 required positional argument: 'self' when using the MaxValueValidator function, because the function receives product-based data using self. I can also add a limit thanks to the following variable, but this is the number of stocks of all products. maxqty = StokEkle.objects.values_list("adet").aggregate(total=Sum("qty"))["total"] I need a product-based limit. The model codes are as follows. class AddFood(models.Model): book = models.ForeignKey(Defter, on_delete=models.deletion.CASCADE) food = models.ForeignKey("stok.Urun", on_delete=models.CASCADE, verbose_name="Ürün") def totalstock(self) -> float: toplamurun = StokEkle.objects.filter(urunadi=self.food) totalqty = toplamurun.aggregate(toplam=Sum("adet"))["toplam"] return totalqty totalstock.short_description = 'Güncel Stok Adedi' qty = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(totalstock)]) def __str__(self): return self.food.productname class Meta: verbose_name_plural = "Malzeme Ekle" verbose_name = "Malzeme" If I can't figure out how I should do. If you can help I'd appreciate it. -
My JavaScript function is not working in my html
I am trying to run a function called send mail but it doesn't run at all because the response is supposed to be 201 when it runs but django returns a 200 response like it isn't there. I tried running the function directly in my console and it worked fine so the backend is working as excpected. Here is the JS code: document.addEventListener('DOMContentLoaded', function() { // Use buttons to toggle between views document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox')); document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent')); document.querySelector('#archived').addEventListener('click', () => load_mailbox('archive')); document.querySelector('#compose').addEventListener('click', compose_email); document.querySelector('#compose-form').addEventListener('submit',send_mail); // By default, load the inbox load_mailbox('inbox'); }); function compose_email() { // Show compose view and hide other views document.querySelector('#emails-view').style.display = 'none'; document.querySelector('#compose-view').style.display = 'block'; // Clear out composition fields document.querySelector('#compose-recipients').value = ''; document.querySelector('#compose-subject').value = ''; document.querySelector('#compose-body').value = ''; } function load_mailbox(mailbox) { // Show the mailbox and hide other views document.querySelector('#emails-view').style.display = 'block'; document.querySelector('#compose-view').style.display = 'none'; // Show the mailbox name document.querySelector('#emails-view').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`; fetch(`/emails/${mailbox}`) .then(response => response.json()) .then(emails => { // Print emails console.log(emails); // ... do something else with emails ... }); } function send_mail(){ fetch('/emails/', { method: 'POST', body: JSON.stringify({ recipients: document.querySelector('#compose-recipients').value, subject: document.querySelector('#compose-subject').value, body: document.querySelector('#compose-body').value }) }) .then(response => response.json()) .then(result => { // Print result … -
Passing Django model properties to JavaScript with the Fetch API
I'm working on an assignment to use the fetch API to do some of the normal things we would have Python do in our views with JavaScript such as adding records or querying the database. One issue I'm running across is passing the normal properties we would see in Django, say a user or username, where it just shows up as a literal user id when I pull it from the sql database with the fetch API. With the views, html and JavaScript I have written now, how would I go about pulling the username with fetch in JavaScript that I can normally grab with a variable or view with a print statement in the Django console, instead of just viewing the user id from the database. I feel like I'm missing a step and I'm just not seeing it. urls app_name = "network" urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), # API Routes path("addpost", views.post, name="post"), path("<str:navbar_item>", views.viewposts, name="viewposts"), ] models.py class User(AbstractUser): pass class Profile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) bio = models.TextField(null=True, blank=True) # pics website = models.CharField(max_length=225, null=True, blank=True) follower = models.ManyToManyField( User, blank=True, related_name="followed_user") # user following … -
call a function with a button in django admin
I have a python class in models.py: class Scenario(TemporalObject): name = models.CharField(max_length=200) user = models.CharField(max_length=200) start = models.DateTimeField(default=django.utils.timezone.now) end = models.DateTimeField(default=django.utils.timezone.now) def nb_hours(self): """Compute the number of hours between start and end""" return (int((self.end - self.start).total_seconds() // 3600))+1 def activate_button(self): return format_html( '''<form action="activate/" method="POST"> <button type="submit"> Activate </button> </form>''') And the correspondig class ScenarioAdmin(admin.ModelAdmin): list_display = ("name", "user", "start", "end", "nb_hours","activate_button") I want to call a function through the button that I created with activate_button. How can I do? -
self Many to many field adding when is not supossed to
class User(AbstractUser): first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=64) bio = models.TextField(max_length=128, blank=True) followers = models.ManyToManyField('self', related_name='followers', blank=True) So i have this table but when i add a user in the followers field, django also add the user in both ways. For example if i have an user called john and i want to follow a user called math. When Jhon is added to the followers of math, math is also added to the followers of jhon. And i dont know why is that. Should i use other type of model? -
i can't retrieve an image from the image url link in django model
I use the CharField for the image url in the django model bt can't retrieve image in the detail page of food , this app is food app and i use default parameter as a food a placeholder image : from django.db import models Create your models here.emphasized text class Item(models.Model): def __str__(self): return self.item_name item_name = models.CharField(max_length=200) item_desc = models.CharField(max_length=200) item_price = models.IntegerField() item_image = models.CharField(max_length=500, default="https://p.kindpng.com/picc/s/79-798754_hoteles-y-centros-vacacionales-dish-placeholder-hd-png.png") -
Getting error like ModuleNotFoundError in Windows although it has been installed in Git Bash and executing on the expected lines when run in Git Bash
This is regarding a small django project that i am developing for self learning. I have created a virtual environment in git bash using the following command: $ python -m venv virtual And activating it with: $ source virtual/Scripts/activate After this I have installed some modules like Pillow, django-decouple, CKEditor and some more. When I run the django server from git bash, I have no problems. However, I like the django server in windows cmd. But when I run the django server from windows (version 7 is what i have), the server crashes and I get an error message like: ModuleNotFoundError: No module named '\decouple' or ModuleNotFoundError: No module named 'CKEditor' I can only presume that the modules installed in the virtual environment in Git Bash are not being detected in Windows command prompt. Can someone please help me understand this and how to get around it. Many thanks -
After linking urls&views "hello world" is not visible in django
i have just now started learning the django basics ,but i have been keeping on facing a problem with the urls & views ....i do not get the "Hello world" after i reload or even try adding myapp nname in the url WROTE THIS CODE FOR THE PROJECT URL from django.urls import include, path from .views import home urlpatterns = [ path('', include('calc.urls')), path('admin/', admin.site.urls), ]```` WROTE THIS FOR MYAPP URLS `````from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ]```` WROTE THIS FOR THE VIEWS ````from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return HttpResponse("Hello world");```` kindly let me know what mistake i am doing . LINK: < http://127.0.0.1:8000/calc>