Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i use python code as core for website?
Hi ,I have written python algorithm in windows and I wanna make UI for this code in web . I haven't make any server or API and so on .How can I do it ? How can I use my code as core for website ? -
How can a logged in user comment on a post? django
I wrote the codes for commenting system and whenever you want to add a comment to a post, You'll be redirected to a page that you can write your comment and choose which member you are. How can I fix the member field with the user that is currently logged in to the site? And how can I make the comment section only down the post and not being redirected to another page? Here's my view.py def comment_post(request, slug): post = get_object_or_404(Post, slug=slug) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('samplepost', slug=post.slug) else: form = CommentForm() return render(request, 'blogapp/comment.html', {'form': form}) and here is my models.py class Comment(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE, null=True) post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, related_name='comments') body = models.TextField() date_created = models.DateTimeField(auto_now_add=True) -
import variable with data from django to sql database (SQLite3) Django
I'm a beginner so sorry if it's a stupid question. I create a site on the Django. On the HTML code, a have a form that to request and save the data of the form fields on the variable. on views.py file. How I can to do this: when I going to a web page, force Django to run a Python file in the same folder) (which contains a code with a request to add data from a form to a database table) I'm home that I succeed to explain it. -
django get 7 days back date from one date
Here is the date i am getting from django model data 2020-09-18 05:46:41.043849+00:00 <class 'datetime.datetime'> I am trying to get 7 days back from that that. Expected result: 2020-09-11 05:46:41.043849+00:00 Is there any way we can achive that efficiently ? Please have a look -
Django application error when deploying to heroku
I'm new to python and the Django framework. After some series of learning python and Django, I created a web app. I wanted to deploy it into Heroku platform but I'm caught up with this weird error. I have spent weeks googling and researching and finding solutions but to no avail. One of the errors I couldn't fix was wrapt==1.12.1) is not available for this stack (heroku-18). I have searched everywhere on the internet and pip installing wrapt==1.12.1 but still, I kept getting the same error. Please I need help in fixing this error. Thank you. The error message is down below. Error message here -
How to get all the texts from html page having same id with JavaScript?
I am having webpage with this code:- <article class="media content-section"> <div class="media-body"> <h2><a id="post_title" class="article-title" href="/post/new/">new</a></h2> <div class="article-metadata"> <a class="mr-2" href="/profileview/manish">manish</a> <div class="float-right"> <small class="text-muted">Category</small> <small class="text-muted">Sept. 19, 2020, 2:49 a.m.</small> </div> <div style="float:right;"> <img style="height:19px; width:18px;" src="/static/blog/viewicon.png"> <p style="float: right; display: inline !important;" id="ViewCount"> </p> </img> </div> </div> <p class="article-content"><p>newnwnewnenwnenwenwewewewewe</p></p> </div> </article> <article class="media content-section"> <div class="media-body"> <h2><a id="post_title" class="article-title" href="/post/post-with-markdown-styling/">Post with Markdown Styling?</a></h2> <div class="article-metadata"> <a class="mr-2" href="/profileview/manish">manish</a> <div class="float-right"> <small class="text-muted">Category</small> <small class="text-muted">Sept. 15, 2020, 6:46 p.m.</small> </div> <div style="float:right;"> <img style="height:19px; width:18px;" src="/static/blog/viewicon.png"> <p style="float: right; display: inline !important;" id="ViewCount"> </p> </img> </div> </div> <p class="article-content"><p>This are the points which you should follow while writting a good blog:- Have a proper Introduction.&nbsp;Be explainatory.&nbsp;Use easy english language.&nbsp;Be consise and clear.&nbsp;Have a go…</p> </div> </article> ------ ------ ------ I am trying to add a text on the tags containing the id ViewCount by adding a condition to my javascript code that whenever the title feched from the server mathes the title of the page. Here's my javascript code:- $(document).ready(function(){ setInterval(function() { $.ajax({ type:'GET', url: "{% url 'getBlogs' %}", success: function(response){ $("#ViewCount").empty(); for (var key in response.blogs) { var fromServerTitle = response.blogs[key].title; var fromPageTitle = document.getElementById("post_title").innerText; if (fromServerTitle == … -
'chromedriver' executable needs to be in PATH in Python Django
I am trying to execute a Python script in Django. My view file is: def generate_traffic(request): #other code out = run([sys.executable, 'C://Users//Maisum Abbas//learning_users//trafficapp//traffic.py', "--domain", url, "--thread", requests, "--max-clicks", maximum, "--min-clicks", minimum]) If I run the script alone without running it in Django, it works fine. Now, the problem that I am facing is that the script is not able to detect chromedriver if I run it from my function generate_traffic in view.py. I don't know what seems to be the problem since the chromedriver is in the same directory as of my other files. myFolder -view.py -traffic.py (the script I am executing) -chromedriver.exe -otherfiles Kindly guide me of what I am doing wrong or what seems to be the problem here. -
While setting interpretor to python 3.8.2 in django its giving errors such as unable to import django.urls?
I am working on django in VS code. Its giving errors on any django import (ex unable to import django.urls) while setting interpreter to python 3.8. Although when I set interpreter to python 2.7 the errors are resolved. I have installed django in virtual environment. Please enlighten me why this problem is occuring and will it cause any trouble in future?enter image description hereenter image description here -
Can we set live django project on local machine
Is there any way to setup live django project on local machine for practice. There are many ways to set php projects on local machine, same as is there any way for django. -
Error while querying attendance list of employee having OneToOne user relation
I am trying to get my employee attendance list using django-rest-framework but getting this error::: ValueError at /shifts/api/v1/my_attendance Cannot query "sureshemployee@gmail.com": Must be "Employee" instance. Please help class EmployeeAttendance(ModelDateCommonInfo): employee = models.ForeignKey(Employee, related_name='employee_attendances', on_delete=models.CASCADE) check_in = models.TimeField() check_out = models.TimeField() class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee') class MyAttendanceList(generics.ListAPIView): authentication_classes = [authentication.TokenAuthentication] permission_classes = [permissions.IsAuthenticated] serializer_class = MyAttendanceListSerializer filterset_fields = [] def get_queryset(self): queryset = EmployeeAttendance.objects.filter(employee=self.request.user).order_by('-created_at') return queryset Error : Cannot query "sureshemployee@gmail.com": Must be "Employee" instance. Please help -
django.core.exceptions improperly configured ("Error loading psycopg2 module:no module named psycopg2._psycopg2
Can't come up with this error. Any idea about this. ''' django.core.exceptions.improperlyconfigured:error loading psycopg2 module: No module name psycopg2_.psycopg2 ''' -
Ordering models using Django AutoField with custom step size
Consider a model Section that is displayed on a site and created / edited by a user using the Django admin interface. I would like to add a field that allows the user to easily control the order in which sections are displayed on the site. The easiest option seems to be to allow for an integer field that is auto-incremented but can be edited by the user -- akin to what the built-in AutoField does. However, to make editing the order easier, I would like to increment the fields default value by 10 every time, to allow the user to shift sections around more easily. The first section would get order=1, the next one order=11 and so on, that way a section can be wedged in between those first two by giving it, e.g., order=6. Is there a way I can reuse AutoField to achieve this purpose? And if no, how could I best achieve this type of ordering scheme? -
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', ]