Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django reverse relationship in many-to-many field
how do i get gallery response like bellow. Now, galleryserializer returns response with images array with ids only. I am not able to get details of images. json response: { "name": "New Gallery", "images": [ { id: 1, image: 'url/path/to/image', alt_text: 'alt' }, { id: 2, image: 'url/path/to/image1', alt_text: 'alt' }, ] } My models.py file: class GalleryImage(models.Model): image = models.ImageField(upload_to='gallery/') alt_text = models.CharField(max_length=300) created = models.DateTimeField(auto_now_add=True) class Gallery(models.Model): name = models.CharField(max_length=30) slug = AutoSlugField(populate_from='name', unique_with='id') images = models.ManyToManyField(GalleryImage, related_name="galleryimages") created = models.DateTimeField(auto_now_add=True) My serializers.py file: class GalleryImageSerializer(serializers.ModelSerializer): class Meta: model = GalleryImage exclude = '__all__' class GallerySerializer(serializers.ModelSerializer): class Meta: model = Gallery fields = '__all__' -
how do i use DRF serializer to get the following api structure?
how can i use drf to get an api similar to: { "user":{ "username":"my username", "email":"my email" }, "product":[ { "id":id, "product_name":"somename", "type":"sometype", "date_bought":date, "image": "image address",... }, { "id":id, "product_name":"somename", "type":"sometype", "date_bought":date, "image": "image address",... },.... ] } models.py class Product(models.Model): product_name=models.CharField(max_length=50) price = models.IntegerField() product_type = models.CharField(max_length=25) description = models.CharField(max_length=250 ,default='', blank=True) brand = models.CharField(max_length=25, null=True,blank=True) image = models.ImageField(upload_to='images/product_image') date_added = models.DateField(auto_now_add=True) instock = models.BooleanField(default=True) instock_qty = models.IntegerField() def __str__(self): return f"{self.product_name}" class UserHistory(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.RESTRICT) date_bought = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.user},{self.product}' i need to be a ble to do the following: when GET , retrive the above data. add products (user is read only, only the authenticated user will be able to add product). how do i write the serializer to achieve the above objectives fairly new to django so notify me if i missed something -
how to get cart total amount in Django?
I have deals products and normal products. I have a function for normal products which calculate grand toal is working fine but when I add deal product in the cart it did calculate the grand total but only normal prices not deals prices get total of one product with quantity def get_total(self): price = self.product.price quantity = self.quantity total = price*quantity print(total) return total function of get cart total @property def get_cart_total(self): orderitem = self.orderitem_set.all() total = sum(item.get_total for item in orderitem) return total i have two fields in databse price and deal_price how i can calculate complete correct cart total? -
Channel not sending message to partners browser
I'm trying to send chat data to my browser. The websocket is sending data to the message owner's browser. But the problem is the message is not updating from other user's browser. class ChatConsumer(WebsocketConsumer): def connect(self): if(not self.scope['user'] is User): my_id = self.scope['user'] self.me = User.objects.get(id=my_id) else: self.me = self.scope['user'] others_id = self.scope['url_route']['kwargs']['user_id'] other_user = User.objects.get(id=others_id) self.thread_obj = Thread.objects.get_or_create_personal_thread( self.me, other_user) self.room_name = f'presonal_thread_{self.thread_obj.id}' self.channel_layer.group_add( self.room_name, self.channel_name) self.accept() print(f'[{self.channel_name}] - {self.me.username} You are connected') def fetch_messages(self, data): messages = Message.objects.filter(thread=self.thread_obj) content = { 'command': 'messages', 'messages': self.messages_to_json(messages) } self.send_message(content) def new_message(self, data): message = Message.objects.create(sender=self.me, thread=self.thread_obj, message=data['message']) content = { 'command': 'new_message', 'message': self.message_to_json(message) } return self.chat_message(content) def messages_to_json(self, messages): result = [] for message in messages: result.append(self.message_to_json(message)) return result def message_to_json(self, message): return { 'id': message.id, 'sender_id': message.sender.id, 'sender': message.sender.username, 'content': message.message, 'timestamp': str(message.posted_on) } commands = { 'fetch_messages': fetch_messages, 'new_message': new_message } def disconnect(self, close_code): self.channel_layer.group_discard( self.room_name, self.channel_name ) def receive(self, text_data): data = json.loads(text_data) self.commands[data['command']](self, data) def chat_message(self, message): print(message) async_to_sync(self.channel_layer.group_send)( self.room_name, { 'type': 'chat_message', 'message': message } ) self.send(text_data=json.dumps(message)) def send_message(self, message): self.send(text_data=json.dumps(message)) When I send chat message to the channel socket from my browser It updates only to my browser. But not updating other user's … -
Django elasticsearch dsl term and phrase search is not working
I used two packages (i.e django-elasticsearch-dsl==7.1.4 and django-elasticsearch-dsl-drf==0.20.8) to add a search engine to my Django project. The model which I indexed in elastic is: class Article(models.Model): created_time = models.DateTimeField(_('created time'), auto_now_add=True) updated_time = models.DateTimeField(_('updated time'), auto_now=True) profile = models.ForeignKey('accounts.UserProfile', verbose_name=_('profile'), on_delete=models.PROTECT) approved_user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('approved user'), blank=True, null=True, editable=False, on_delete=models.CASCADE, related_name='article_approved_users') approved_time = models.DateTimeField(_('approved time'), blank=True, null=True, db_index=True, editable=False) title = models.CharField(_('title'), max_length=50) image = models.ImageField(_('image'), blank=True, upload_to=article_directory_path) slug = models.SlugField(_('slug'), max_length=50, unique=True) content = models.TextField(_('content')) summary = models.TextField(_('summary')) views_count = models.PositiveIntegerField(verbose_name=_('views count'), default=int, editable=False) is_free = models.BooleanField(_('is free'), default=True) is_enable = models.BooleanField(_('is enable'), default=True) tags = TaggableManager(verbose_name=_('tags'), related_name='articles') categories = models.ManyToManyField('Category', verbose_name=_('categories'), related_name='articles') namads = models.ManyToManyField('namads.Namad', verbose_name=_('namads'), related_name='articles', blank=True) I used the following document for indexing my Article model: html_strip = analyzer( 'html_strip', tokenizer="whitespace", filter=["lowercase", "stop", "snowball"], char_filter=["html_strip"] ) @registry.register_document class ArticleDocument(Document): title = fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField(analyzer='keyword'), 'suggest': fields.CompletionField(), } ) tags = fields.ObjectField( properties={ "name": fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField(analyzer='keyword'), 'suggest': fields.CompletionField(), } ) } ) categories = fields.ObjectField( properties={ 'id': fields.IntegerField(), 'title': fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField(analyzer='keyword'), 'suggest': fields.CompletionField(), } ) } ) namads = fields.ObjectField( properties={ "id": fields.IntegerField(), "name": fields.TextField( analyzer=html_strip, fields={ 'raw': fields.TextField(analyzer='keyword'), 'suggest': fields.CompletionField(), } ), "group_name": fields.TextField( analyzer=html_strip, fields={ 'raw': … -
Is there a way to duplicate entire data from one project to the other in Django?
So I've made and been running a beta test of my project for a couple of months. It is a CRUD application, where user posts some stuff. The thing is, I realized that I might have to pivot the item a little, so I'm planning to build a new project from the beginning. But the posts of my beta testers have to be kept as-is, so I want to migrate(or duplicate) the entire data to this new project. Given that I have the exact same model as the original project in the new one, is there a way to make this possible? Or (I strongly hope not, but) do I have to manually copy+paste all the data? The posts are quite private so the users wouldn't want me to copy+paste them. Thank you very much in advance. :) FYI, I'm using AWS EC2 and Postgres. -
How to override Django file input in forms.py?
I want to override the default input looking, I'm not looking to change an attribute, I'm searching for something more advance So here is a normal Django input file field with crispy_tag_forms <div id="div_id_image" class="form-group"> <label for="id_image">Image*</label> <div> Currently: <a href="/media/profile_images/DefaultUserImage.jpg">profile_images/DefaultUserImage.jpg</a><br> Change: <input type="file" name="image" accept="image/*" id="id_image"> </div </div> However this looks very ugly, so all of the time I completly hide it and write my own that looks something like this <div style="display:none"> ... <input type="file" id="id_image"> ... </div> <p class="btn btn-outline-success" onclick = "document.querySelector('#id_image').click()" onchange = "this.innerHTML = document.querySelector('#id_image')[0].files[0].name"> <i class="someicon"> Image </p> And to be able to do so I have to use some Javascript, however for some reason, it always puts it at the end of the form which is not what I want, and I won't be writing the same function over and over again for each form I create with Django Is there any way to make this the default django file field? -
Assign permissions to users in Django groups
I'm using Django (3) with a custom user model using BaseAbstractUser in which I have a BooleanField field named is_instructor and also created a group named instructor. So when the user signup with is_instructor he will have all the permissions of the instructor group. And to this group I assigned all the permissions related to my courses app in Django admin. Now If I try to create a new course with a user which has instructor group permissions it redirect me to incorrect login page, my actual login URL path is /users/login but it redirect me to '/accounts/login`. Here's my Model: class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name='email', max_length=60, unique=True) fullname = models.CharField(max_length=30, unique=True) is_instructor = models.BooleanField(default=False) date_join = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['fullname'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True My signup view: def registration_view(request): form = RegistrationForm(request.POST or None, request.FILES or None) if request.method == 'POST': print('get post req') if form.is_valid(): user = form.save(commit=False) user.is_active = True user.save() if form.cleaned_data['is_instructor'] is True: instructor_group = Group.objects.get(name='instructor') instructor_group.user_set.add(user) return … -
Django not rendering python variable in template
I have a string variable in a Python file that I am trying to render in my HTML template. The variable is called contacts, and in my template, I have {{contacts|default:"null"}}. From the documentation, it seems like that should work, but the template keeps coming up with the null keyword. I've scoured the documentation and found nothing. Probably a super simple thing I'm overlooking that has frustrated me to no end. In the python file, I'm using an API to get a JSON and unloading it into a dictionary (don't know all the specific terms), where I then extract the value I need into a string: ... dict_data = dict(json.loads(data)) contacts = str(dict_data["contact_count"]) Then in my HTML file: <p class="spotbanner"> {{contacts|default:"null"}} spots left! </p> Is there something else I'm missing? Something super simple that I just don't understand about Django despite having used this method before? Happy to provide more information. -
How to add Paypal to Payment in Django E-commerce Project
I have been searching on the best way to add the PayPal payment to my E-commerce Project, but I am currently stuck on where to start exactly, I have read the PayPal documentation found in https://developer.paypal.com/demo/checkout/#/pattern/radio Currently when the user adds items to the cart, in the checkout page there is a form to be filled, so after adding the address there is a radio button to choose from it whether to proceed with Stripe or PayPal, so my question is what should I do so that when the PayPal radio is chosen it opens the PayPal login window? Here is the models.py class Payment(models.Model): stripe_charge_id = models.CharField(max_length=50) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True) amount = models.FloatField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username Here is the views.py class CheckoutView(View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) form = CheckoutForm() context = { 'form': form, 'couponform': CouponForm(), 'order': order, 'DISPLAY_COUPON_FORM': True } shipping_address_qs = Address.objects.filter( user=self.request.user, address_type='S', default='True' ) if shipping_address_qs.exists(): context.update( {'default_shipping_address': shipping_address_qs[0]}) billing_address_qs = Address.objects.filter( user=self.request.user, address_type='B', default='True' ) if billing_address_qs.exists(): context.update( {'default_billing_address': billing_address_qs[0]}) return render(self.request, "checkout.html", context) except ObjectDoesNotExist: messages.info(self.request, "You do not have an active order") return redirect("core:checkout") def post(self, *args, **kwargs): form = … -
How can I apply my form to multiple templates in django
I am creating a blog site where users can post articles on the home page which can then also be commented on using a form. These posts can also be viewed elsewhere on the site, under search results and on user profiles for example. What I am trying to do is allow users to comment on the posts anywhere that they appear. At the moment my comments view looks like this: def create_comment_view(request): profile = Profile.objects.get(user=request.user) c_form = CommentModelForm() if 'submit_c_form' in request.POST: c_form = CommentModelForm(request.POST) if c_form.is_valid(): instance = c_form.save(commit=False) instance.user = profile instance.post = Post.objects.get(id=request.POST.get('post_id')) instance.save() c_form = CommentModelForm() context = { 'profile': profile, 'c_form': c_form, } return render(request, 'posts/comment.html', context) My form looks like this: class CommentModelForm(forms.ModelForm): class Meta: model = Comment fields = ('body',) And I have used {% include 'posts/comment.html' %} to link my templates to a separate html file which looks like this: <form method="post"> {% csrf_token %} <input type="hidden" name="post_id" value={{ post.id }}> {{ c_form }} <button type="submit" name="submit_c_form">Send</button> </form> Right now my submit button is appearing in the right place and I have tested the input which is working, however the form itself is not being shown. Can anyone please tell me … -
Is there a way to put a sold label on an item once it gets sold?
I am creating an E-Commerce Website and i have only one piece for each item stored in the db. My question is there a way to put a sold label on the item once it gets sold? I don’t want an item to be sold twice because i have only one piece for each item as I mentioned. -
Django: templates problem with index.html?
i reied to run server by adding html files to templates directory but it says that there is no that kind of files i dont know what i did wrong? please help me with that.. My django server cant find my home.html and says : blog/home.html Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.0.7 Exception Type: TemplateDoesNotExist Exception Value: blog/home.html Exception Location: /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/template/loader.py in get_template, line 19 Python Executable: /Library/Frameworks/Python.framework/Versions/3.8/bin/python3 Python Version: 3.8.2 Python Path: ['/Users/barkhayotjuraev/Desktop/app_blog', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python38.zip', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload', '/Users/barkhayotjuraev/Library/Python/3.8/lib/python/site-packages', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages'] setting.py : ```INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
View Management in Django
I'm new to python and I have chose Django Framework. I searched over documentations and couldn't find my desired way of view management. I want to create a skeleton base view and load other view in that view. But my question is that I want to create some views in views.py write code their and output result in base skeleton. One page may contains view from different methods in views.py file. Is there any idea of this modular implementation of template ? Thanks in Advance. -
Upload image to firebase and save url in sqlite DJango
suddenly someone can guide me. I made an application, people have a normal profile, with a series of fields that can modify the profile photo, locally it works perfectly, however, when deploying it in heroku (free account) it is not possible because heroku in its free version does not handle dynamic files, or at least that is what I understood, so I want to save the images in firebase and only the urls in the database. Anyone have any idea how I can do this? Thank you very much for your answers This is the code currently views.py def edit_profile(request): if request.method == 'POST': form = UEditF(request.POST, instance=request.user) extended_profile_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile) if form.is_valid() and extended_profile_form.is_valid(): form.save() extended_profile_form.save() return redirect('/polls/perfil') else: form = UEditF(instance=request.user) extended_profile_form = ProfileForm(instance=request.user.profile) context = { 'form': form, 'extended_profile_form':extended_profile_form } form.fields['password'].help_text = 'Para cambiar la contraseña has clic en el menú superior derecho "Cambiar contraseña"' return render(request, 'registration/edit_profile.html', context) forms.py class UEditF(UserChangeForm): class Meta: model = User fields = ['first_name', 'last_name'] class ProfileForm(forms.ModelForm): birth_date = forms.DateField(widget=DatePickerInput(format='%d/%m/%Y'), label='Fecha de nacimiento') photo = forms.ImageField(label="Foto de perfil") models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateField('Fecha de nacimiento', default=date.today) photo = models.ImageField('Foto de perfil', upload_to='media/', max_length=200, default='default.png') -
Graphene-python performance issues for large data sets
Currently using graphene-python with graphene-django (and graphene-django-optimizer). After receiving a GraphQL query, the database query is successfully completed in a fraction of a second; however, graphene doesn't send a response for another 10+ seconds. If I increase the data being sent in the response, the response time increases linearly (triple the data = triple the response time). The data being retrieved composed of nested objects, up to 7 layers deep, but with the optimized queries this doesn't impact the time taken to retrieve the data from the DB, so I'm assuming the delay has to do with graphene-python parsing the results into the GraphQL response. I can't figure out how to profile the execution to determine what is taking so long -- running cProfiler on Django doesn't seem to be tracking the execution of graphene. SQL Query response time was determined using the graphene-django-debugger middleware, results shown below: "_debug": { "sql": [ { "duration": 0.0016078948974609375, "isSlow": false, "rawSql": "SELECT SYSDATETIME()" }, { "duration": 0.0014908313751220703, "isSlow": false, "rawSql": "SELECT [redacted]" }, { "duration": 0.0014371871948242188, "isSlow": false, "rawSql": "SELECT [redacted]" }, { "duration": 0.001291036605834961, "isSlow": false, "rawSql": "SELECT [redacted]" }, { "duration": 0.0013201236724853516, "isSlow": false, "rawSql": "SELECT [redacted]" }, { "duration": 0.0015559196472167969, … -
django-bakery page variables missing from bake
I've been reading the docs and have been able to mostly bake a site successfully. However I'm having an issue on passing page parameters to the baking view. Original View that works in the regular runserver command class auto(View): def get(self, request): return render( request, 'app/auto.html', { 'title':'Auto Insurance', 'message': 'generic message', 'year':datetime.now().year, } ) I use this bakery view class AutoTemplateView(BuildableTemplateView): build_path = 'auto.html' template_name = 'app/auto.html' The settings has the view and the page is being generated successfully outside of the title and message are blank BAKERY_VIEWS = ( 'app.views.HomeTemplateView', 'app.views.AutoTemplateView', ) html template <div class="col-sm-8 col-sm-offset-2"> <h3 class="title-one"> {{ title }}</h3> <h4>{{ message }}</h4> </div> and bakery html output : <div class="col-sm-8 col-sm-offset-2"> <h3 class="title-one"> </h3> <h4></h4> </div> I can't imagine this is an actual bug but what am I missing? -
How do I host two servers on NGINX? (Django and Angular PWA)
I want Django to keep all of its defined routes and Angular to be hosted from ip/pwa. I have these block bodies: #Angular server { listen 157.230.4.110:80; root /home/pwa/dist/reportpwa; location /pwa { try_files $uri $uri/ /index.html; } } #Django Database server { listen 157.230.4.110:80; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/django-apps/reportdbapi; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } The servers seem to run fine on their own but when I put them both up together, the Django server takes over and refuses to recognize the Angular server. Can anyone tell me what kind of configuration I need to make them both work? -
Background image not rendering correctly in Django
I am working on a project in Django 2. I have a base.html in templates: {% block removable-pagetop %} <div class="showcase"> <div class="showcase-content-top"> {% block page-title %}{% endblock %} <p>{% block page-subtitle %}{%endblock %}</p> </div> {% block button-list %} <div class="showcase-content-buttons"> <ul> <li>{% block button1 %}{% endblock %}</li> <li>{% block button2 %}{% endblock %}</li> <li>{% block button3 %}{% endblock %}</li> <li>{% block button4 %}{% endblock %}</li> </ul> </div> {% endblock %} </div> {% endblock %} The CSS for a background image is: .showcase { background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.2)), url(/static/img/vg_home.jpeg); height: 100%; background-position: center; background-repeat: no-repeat; background-size: cover; } My index.html is: {% extends 'base.html' %} {% load static %} {# Page/Tab Title #} {% block title %}Video Games | Home{% endblock %} {# Navbar with video game theme icon #} {% block navbar %} <header> <nav class="nav-wrapper"> <div class="logo"> <a href="{% url 'index' %}"> {% block nav-icon %}<img src="{% static 'img/vg_icon.png' %}">{% endblock %} </a> </div> <ul class="menu"> <li><a href="{% block home-button %}{% url 'index' %}{% endblock %}">Home</a></li> <li><a href="{% block about-button %}{% url 'about' %}{% endblock %}">About</a></li> </ul> </nav> </header> {% endblock %} {% block removable-pagetop %} <div class="showcase"> <div class="showcase-content-top"> {% … -
I want to create an RestFul Web Scraping API with a Python framework
i'm looking for recommandations about what framework is good to build a this API (DJANGO or FLASK) also what library is good for "OCR" (Scrappy or Tessaract). Thanks -
Can't add SSL certificate to Traefik running on Docker
I'm working on a project runs on Ubuntu 18.04, I depend on Docker to run the application. here is the production.yml file part of traefik: traefik: build: context: . dockerfile: ./compose/production/traefik/Dockerfile image: goplus_backend_production_traefik depends_on: - django volumes: - production_traefik:/etc/traefik/acme - ${PWD}/certs:/certs ports: - "0.0.0.0:80:80" - "0.0.0.0:443:443" here is the Dockerfile for traefik: FROM traefik:alpine RUN mkdir -p /etc/traefik/acme RUN touch /etc/traefik/acme/acme.json RUN chmod 600 /etc/traefik/acme/acme.json COPY ./compose/production/traefik/traefik.toml /etc/traefik and here is traefik.toml file: logLevel = "INFO" defaultEntryPoints = ["http", "https"] # Entrypoints, http and https [entryPoints] # http should be redirected to https [entryPoints.http] address = ":80" [entryPoints.http.redirect] entryPoint = "https" # https is the default [entryPoints.https] address = ":443" [entryPoints.https.tls] [[entryPoints.https.tls.certificates]] certFile = "/certs/hrattendence_gs-group_nl.chained.crt" keyFile = "/certs/hrattendence_gs-group_nl.key" [file] [backends] [backends.django] [backends.django.servers.server1] url = "http://django:5000" [frontends] [frontends.django] backend = "django" passHostHeader = true [frontends.django.headers] HostsProxyHeaders = ['X-CSRFToken'] [frontends.django.routes.dr1] rule = "Host:<IP name>" Each time i run docker i got this error messages about traefik: traefik_1_6f05e4889627 | time="2020-09-18T23:23:49Z" level=info msg="Using TOML configuration file /etc/traefik/traefik.toml" traefik_1_6f05e4889627 | time="2020-09-18T23:23:49Z" level=info msg="No tls.defaultCertificate given for https: using the first item in tls.certificates as a fallback." traefik_1_6f05e4889627 | time="2020-09-18T23:23:49Z" level=info msg="Traefik version v1.7.16 built on 2019-09-13_01:12:20PM" traefik_1_6f05e4889627 | time="2020-09-18T23:23:49Z" level=info msg="\nStats collection is disabled.\nHelp us … -
django Page not found Using SQLite3
Not Sure why I am getting this error I only have 1 Item Only my ToDoList its called "Habibs List" but when I go on the website and put http://127.0.0.1:8000/Habibs List Its giving me this error I am doing the same thing from this Tutorial but I am not sure why mine isnt working its at 22:12 Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/Habibs%20List Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ <int:id> [name='index'] The current path, Habibs List, didn't match any of these. this is in my view tab def index(response, name): ls = ToDoList.objects.get(name=name) item = ls.item_set.get(id=1) return HttpResponse("<h1>%s</h1><br></br><p>%s</p>" %(ls.name, str(item.text))) #def v1(response): #return HttpResponse("<h1>Game Page</h1>") #def v2(response): #return HttpResponse("<h1>Electronic Page</h1>") my url page in my main # the path to our defferent web pages # like the defferent views we have in our file from django.urls import path from . import views urlpatterns = [ path("<int:id>", views.index, name="index"), ] -
Can't create new django project [VS CODE]
PS C:\Users\Kwaku Biney\Desktop\hello_django> django-admin startproject dj_pro django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + django-admin startproject dj_pro + ~~~~~~~~~~~~ + CategoryInfo : ObjectNotF ound: (django-admin:String) [], Comm andNotFoundException + FullyQualifiedErrorId : CommandNot FoundException This is what happens everytime a try to create a new project. How do I rectify it? Created the path and everything.. but still -
Extract date from datetime dictionary in django queryset
Spent way too much time on this so Ima ask, queryset = MyModel.objects.filter(id=id).values('send_date') the result is this <QuerySet [{'send_date': datetime.date(2020, 9, 30)}]> Trying to get 2020, 9, 30 I tried sd=queryset.strftime('%Y-%m-%d'), sd=datetime.strptime(max(queryset.keys()),'%Y-%m-%d') even tried sd=queryset['send_date'], sd=queryset.get('send_date'). -
How to set venv in Django Manage Commands for Sublime 3
I've installed Django Manage Commands for Sublime 3 via Package Control but I am unable to set virtual environment. I followed the instructions but when I try Ctrl + Shift + p and select Django: New Project it asks to choose an interpreter, but I only get the default one, virtualenvs are not listed. I also added "python_virtualenv_paths" : "C:/Users/virtualenvs/django_blog/Scripts/" to JSON. I suspect I skipped some step(s) during the setup, but I can't figure out which.