Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to add comments to a post using a ModelForm in Django
views.py def postdetail(request,pk): # Single Post view. post = Post.objects.get(id=pk) comment = post.comments.all() comment_count = comment.count() if request.user.is_authenticated: if request.method == 'POST': form = CommentForm(data=request.POST) content = request.POST['cMessage'] if form.is_valid(): print("Yes valid") form.instance.body = content new_comment = form.save(commit=False) print(new_comment) new_comment.post = post new_comment.user = request.user new_comment.save() return redirect('blog-home') else: form = CommentForm() context = { 'comment_form': CommentForm, 'post' : post, 'comments': comment, 'count': comment_count, } return render(request,'post/postdetail.html', context=context) models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(User,on_delete=models.CASCADE, related_name='comments') body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) # active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return f'Comment by {self.user} on {self.post}' forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['body'] There is no error being displayed neither If I am adding a comment using the shell/through admin panel but if I am trying to add the comment dynamically through the form then the comment is not getting saved. -
django filter queryset show variables on template
Below is the views.py to my stats page. This page has a bunch of calculations based on my model objects. Works great. However when I apply django-filter to the data it does not change. Example filtering for only "short" trades or in the "last 7 days". I know that get_context_data is basically hardcoding the results and it will not be affected by any filter query. This is not the approach but I've tried several things with no results so back to square one... How would I do this? views.py class StatsView(LoginRequiredMixin, FilterView): model = Trade template_name = 'dashboard/stats.html' filterset_class = StatsFilter def get_form(self, *args, **kwargs): form = StatsFilter() user = self.request.user form.fields['associated_portfolios'].queryset = Portfolio.objects.filter(user=user) return form def get_max_consecutive_wins(self, data): longest = 0 current = 0 for num in data: if num > 0: current += 1 else: longest = max(longest, current) current = 0 return max(longest, current) def get_max_consecutive_loses(self, data): longest = 0 current = 0 for num in data: if num < 0: current += 1 else: longest = max(longest, current) current = 0 return max(longest, current) def get_context_data(self, *args, **kwargs): trade = Trade.objects.filter(user=self.request.user, status='cl').order_by('created') all_trades = Trade.objects.filter(user=self.request.user, status='cl').count() context = super(StatsView, self).get_context_data(*args, **kwargs) data = [t.profit_loss_value_fees for t … -
How to check if a file is a Python file in Python language
I'm working on a web application where candidates submit python code and the platform passes them through a unit test which is written by the recruiters. I'm using Django and I'm having trouble validating the unit-test file. How to test if a file is a python file and that it's correctly formed (no Syntax or lexical errors)? using Python ? Thanks -
django on docker - https with letsencrypt
I have implemented django on docker deployment process using below tutorial. https://github.com/testdrivenio/django-on-docker I'm using ubuntu 18 server, Installed docker and docker-compose. I'm trying to integrate https with letsencrypt for my website. How to integrate the https with letsencrypt using existing docker compose. Thanks in advance. -
Using attribute from a related model django
At my work everyone has to plan until they've reached their planning target. To make this easier I'm building a planning tool to plan the activities. All the activities have standard durations which are saved in the PlanningActivity model. Now I want to show a list of all the planned activities with the standard duration and also sum up the total planned time in a week. How can I use strd_duration in my added Planning's? I've tried so much, but nothing seems to work... models.py class PlanningActivity(models.Model): name = models.CharField(max_length=255) is_billable = models.BooleanField() is_auto_realised = models.BooleanField() strd_duration = models.PositiveIntegerField() def __str__(self): return self.name class Planning(models.Model): added_by = models.ForeignKey( User, related_name='planning_activity', on_delete=models.DO_NOTHING ) activity = models.ForeignKey( PlanningActivity, on_delete=models.DO_NOTHING ) date = models.DateField() note = models.CharField(max_length=255) def __str__(self): return str(self.id) views.py def home(request): planning_form = PlanningForm(request.POST) if request.user.is_authenticated: planning = Planning.objects.filter(added_by=request.user).order_by('-date') contracts = UserContract.objects.filter(assigned_user=request.user) else: planning = '' contract = '' if planning_form.is_valid(): new_planning = planning_form.save(commit=False) new_planning.added_by = request.user new_planning.save() return redirect('/') else: planning_form = PlanningForm() return render(request, 'home.html', {'planning_form': planning_form, 'planning':planning, 'contracts':contracts}) home.html <table class="table table-striped mt-2"> <thead class="thead-light"> <tr> <td>Activity</td> <td>Date</td> <td>Note</td> <td>Duration</td> </tr> </thead> <tbody> {% for plan in planning %} <tr> <td>{{ plan.activity }}</td> <td>{{ plan.date }}</td> <td>{{ … -
Why isn't Bokeh server serving index.html, and only serving the graph document?
I have a django app that is being served a graph from a bokeh server. This works well, but I'm trying to make it prettier. Looking at the docs, I think this is done by embedding the chart in an index.html page, applying your own CSS here, and then serve this to the client as part of the embedded script. However, I cannot get these changes to show up on the django side. serverapp/templates/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> {{ bokeh_css }} {{ bokeh_js }} </head> <body> <p>YOU'VE HIT THE INDEX PAGE</p> #this way I know I've reached index.html {{ plot_div|indent(8) }} {{ plot_script|indent(8) }} </body> </html> serverapp/main.py args = curdoc().session_context.request.arguments pk = int(args.get('pk')[0]) ... #build graph here ... display_data = layout([ [widgetbox(selector),], [plot,], #plot is gmap not figure [slider,], [button,], [data_table,], ]) curdoc().add_root(display_data) When I run bokeh serve --show serverapp, I get index.html served up in a browser window. Over on the django side: viewchart.html {% block content %} <head> <link href = "https://cdn.pydata.org./bokeh/release/bokeh-2.0.1.min.css" rel = "stylesheet" type = "text/css" > <link href = "https://cdn.pydata.org./bokeh/release/bokeh-widgets-2.0.1.min.css" rel = "stylesheet" type = "text/css" > <link href = "https://cdn.pydata.org./bokeh/release/bokeh-tables-2.0.1.min.css" rel = "stylesheet" type = "text/css" > <script type = "text/javascript" … -
Djnago Mysql not migrating models
I'm learning Django, and I cant seem to migrate model, the only thing that is being migrated is ID. although the model has name, description, image,,,,etc models.py from django.db import models # Create your models here. class Destination(models.Model): name: models.CharField(max_length=100) price: models.IntegerField() desc: models.TextField() img: models.ImageField(upload_to='pics') special: models.BooleanField(default=False) Generated 0001_initial.py # Generated by Django 3.0.6 on 2020-05-23 14:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Destination', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], ), ] settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'python', 'USER': 'root', 'PASSWORD': '1q2w3e4r', 'HOST': 'localhost', 'PORT': '3306', } } Migration output $ python3 manage.py sqlmigrate travel 0001 -- -- Create model Destination -- CREATE TABLE `travel_destination` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY); -
How can I raise send a django error message in a class based view with a LoginRequiredMixin?
I have a class based view ProfileView to which unauthorized users are not allowed access to. I have used the LoginRequiredMixin to limit access. class ProfileView(LoginRequiredMixin, TemplateView) : template_name='profile.html' permission_denied_message='You are not allowed access here' login_url='/users/login' I have this snippet included in my base.html {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{ message }} </div> {% endfor %} {% endif %} But when I try to login as an anonymous user, I am redirected to the login url but there is no message displayed. What do I do? -
SyntaxError: invalid syntax in urlpattern ??? RedirectView.as_view
hello i am getting a syntax error url(r'^$', RedirectView.as_view(url='/diabetics/uploads/', permanent=True)), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) what is the probleme? -
how can i search user id if user is not logged in?
how can i search user if user is not logged in and if i put the username in the search box and i want to get all user data or only user id tell me please in Django .strong text '''def search_user(request): if request.method =='POST': user_search =request.POST['username'] if User.objects.filter(username=user_search).exists(): use_r = User.objects.filter(username = user_search) print(use_r) prof = profile.objects.get(users=3) return render(request,'profiles.html',{'profile':prof}) else : return HttpResponse("user is not exists") else: return HttpResponse("do not try again")''' -
Django Rest Framework. Create multiple objects with one POST request to ModelViewSet
I have two models: class ProductImage(models.Model): product = models.ForeignKey("api.Product", on_delete=models.CASCADE, related_name="images") image_id = models.IntegerField(primary_key=True) url = models.URLField() def __str__(self): return self.url class Product(models.Model): shop = models.ForeignKey("api.Shop", on_delete=models.CASCADE, related_name="interested_products") name = models.CharField(max_length=200) product_id = models.IntegerField(primary_key=True) def __str__(self): return f'{self.shop} #{self.product_id}' I have viewsets.ModelViewSet for Product. I will post there data like this: "product_id": 4515934699590, "name": "HTML Crash Course", "images": [ { "id": 13972310982726, "src": "https://cdn.shopify.com/s/files/1/0280/2434/0550/products/html_crash_course.jpg? v=1590183692" } ] How can I set up my ViewSet, so when I do Post request it automatically creates one Product and all instances of ProductImage given. -
How can I save a file AFTER a new entity is created?
I have a case where a newly created entity will have a file submitted during creation. I have this code: def upload_path(instance, filename): return '/'.join(['menu_item_images', str(instance.id), filename]) class MenuItem(ModelBase): name = models.CharField(max_length=100, blank=True, null=True) description = models.TextField(blank=True, null=True) ingredients = models.TextField(blank=True, null=True) active = models.BooleanField(default=True) removed = models.BooleanField(default=False) image = models.ImageField(blank=True, null=True, upload_to=upload_path) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) def __str__(self): return self.name This looked OK till the first time I ran it and the instance ID was 'None'. So it appears the file is saved before the entity is created. I want to manage these files by MenuItem ID. Right now, I have them saving to a unique folder, but I plan to just update the filename. But I still need a unique identifier. Is there a way to save the file afterwards, or an idea of a way to create a unique slug that might be stored in the MenuItem? -
How to handle private configuration file when deploying?
I am deploying a Django application using the following steps: Push updates to GIT Log into AWS Pull updates from GIT The issue I am having is my settings production.py file. I have it in my .gitignore so it does not get uploaded to GITHUB due to security. This, of course, means it is not available when I PULL updates onto my server. What is a good approach for making this file available to my app when it is on the server without having to upload it to GITHUB where it is exposed? -
Django: Unable to set custom id in CheckboxSelectMultiple widget
I have a MultipleChoiceField with a CheckboxSelectMultiple widget where I want the checkboxes to have custom ids. I am creating the field in the form's __init__ function. This is the relevant code - choice_id = 'q_{}'.format(question.id) # no issues here self.fields['response_choices'] = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple(attrs={'id': choice_id}), label='', choices=choices, required=False ) This doesn't work. I did the same for ChoiceField with RadioSelect widget and it works there. Is there any other attribute I need to set for MultipleChoiceField? -
How to count the total choices in DJANGO? Annotate not working
I want to display the total count of a choice field, so basically i made this, which is working, but instead of giving me the total count is reapiting the fields. Picture of how is showing now And this must look like: Not started: 5 or just 5 anyone know how to resolve this? views.py class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' context_object_name='posts' paginate_by = 15 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') def get_context_data(self, **kwargs): context = super(UserPostListView, self).get_context_data(**kwargs) user = get_object_or_404(User, username=self.kwargs.get('username')) context['postuser'] = Post.objects.filter(author=user).order_by('-date_posted')[:1] context['posts'] = Post.objects.filter(author=user).order_by('-date_posted') context['postns'] = Post.objects.filter(author=user,status="NOT STARTED").annotate(dcount=Count('status')).order_by('status') return context HTML {% for post in postns %} <div class="col-auto col-ns-st padding-col-st"><span class="vertical-span"><i class="fa fa-circle color-ico-st"></i>&nbsp;{{ post.status }}</span></div> {% endfor %} models.py class Post(models.Model): NS= 'NOT STARTED' STATUS_CHOICES = ( ('NOT STARTED','NOT STARTED'), ('IN PROGRESS','IN PROGRESS'), ('COMPLETE','COMPLETE'), ) title=models.CharField(max_length=100) content=models.TextField(blank=True) author=models.ForeignKey(User, on_delete=models.CASCADE) status=models.CharField(max_length=40, choices = STATUS_CHOICES,default=NS) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) def __str__(self): return 'Post: {}'.format(self.status) -
Display CreateView field as DateTimePicker in Django
How can I this 'date_delivery' field display as DateTimePicker? Right now it is automatically generated as 'input type="text"' In models.py class MyMachine(models.Model): date_delivery = models.DateTimeField(null=True, verbose_name='Datum Dostave:') machine_name = models.ForeignKey(MyName, on_delete=models.PROTECT) machine_model = models.ForeignKey(MyModel, on_delete=models.PROTECT) machine_serial = models.CharField(max_length=15) language = models.ForeignKey(MyLanguage, on_delete=models.PROTECT) in views.py class MyMachineCreateView(CreateView): model = MyMachine fields = ['date_delivery', 'machine_name', 'machine_model', 'machine_serial', 'language', ] It shows good in DjangoAdmin But in html form not -
should i use django admin for my ecommerce site
Is there any admin dashboard I can use for my client which is not Django admin or should I just use Django admin -
How to avoid users going to other URLs before fulfiling a condition?
I am a newby in django. On my website, users will be redirected to the profile update page right after loging in, and I want to avoid users going to other URLs if some field of update form is empty. Thanks in advance for any kind of advice. -
VariableDoesNotExist, Failed lookup for key [user]
I'm using django-guardian library to verify users permissions in an object level and I'm trying to verify that inside of the change_list_results.html template, NOTE : the same code worked just fine under change_list.html but for some reason it's not working for change_list_results.html. (also I saw some similar questions but I didn't understand their answers and I feel like their cases doesn't apply on me.) here's my code, under change_list_results.html template : {% for object in cl.result_list %} {% get_obj_perms user for object as "context_var" %} {% if 'college_admin' in context_var %} <p>hi</p> {% endif %} {% endfor %} The user in {% get_obj_perms user for object as "context_var" %} is causing the error. error: Failed lookup for key [user] in [{'True': True, 'False': False, 'None': None}, {'cl': <django.contrib.admin.views.main.ChangeList object at 0x7fa319ba0a00>, 'result_hidden_fields': [], 'result_headers': [{'text': '<input type="checkbox" id="action-toggle">', 'class_attrib': ' class="action-checkbox-column"', 'sortable': False}, {'text': 'generator', 'class_attrib': ' class="column- __str__"', 'sortable': False}], 'num_sorted_fields': 0, 'results': [['<td class="action-checkbox"><input type="checkbox" name="_selected_action" value="26" class="action-select"></td>', '<th class="field-__str__"><a href="/generator /generator/26/change/">الهندسة</a></th>'], ['<td class="action-checkbox"><input type="checkbox" name="_selected_action" value="25" class="action-select"></td>', '<th class="field-__str__"><a href="/generator/generator/25/change/">العلوم</a> </th>']], 'csrf_token': <SimpleLazyObject: 'TcuMSJ6FwzuUboZtet03iJh2sPVzcHlLYa2rUGhB9Y4UDKpPPaxusKUelClRAVP3'>}] -
I need a free hosting sites for my Django MySQL project on my windows
I have created a project on Django with mysql database in local, this is my first project so i would like to deploy it online. I tried on heroku and pythonanywhere but it didn't work because they need database in postgresql but I have used MySQL.So please suggest me some hosting sites. -
how to relate the model and use it
i have four model shop(user), product customer order how i can relate that on home page shop get the its customer and order shop user = models.OneToOneField(User, null=True, blank=True,related_name='shop', on_delete=models.CASCADE) name = models.CharField(max_length=70, serialize=True) address = models.CharField(max_length=70) product Shop = models.ForeignKey(Shop, null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=100, serialize=True) Brand = models.CharField(max_length=200) customer Shop = models.ManyToManyField(Shop) name = models.CharField(max_length=100, serialize=True) Phone = models.FloatField() order Shop = models.ManyToManyField(Shop) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) product = models.ManyToManyField(Products) -
How to make djangoQ run as a service using systemd
How to make DjangoQ run as a service using systemd? There is a gap, djangoQ installation and running is like learning to run a Django project. But now, you want to push the project which is using DjangoQ to production. The problem is you are not aware of server and Linux, maybe you are even coming from Windows.... So can somebody tell us, How to run DjangoQ in ubuntu using systemd I am getting the error that ExecStart path is not absolute... I came from here: Stack Question But that answer is not complete, too much tacit knowledge unshared... [Unit] Description= Async Tasks Runner After=network.target remote-fs.target [Service] ExecStart=home/shreejvgassociates/ot_britain_college/env/bin/python manage.py qcluster --pythonpath home/shreejvgassociates/ot_britain_college/OverTimeCollege --settin$ RootDirectory=home/shreejvgassociates/ot_britain_college/OverTimeCollege User=shreejvgassociates Group=shreejvgassociates Restart=always [Install] WantedBy=multi-user.target -
NoReverseMatch at /blog/1
enter image description here how can i solve this error please solve this Reverse for 'comment_form' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['blog/(?P[0-9]+)/comment$'] -
How to post the javscript score variable to the view in the django?
I am developing the quiz application using JavaScript , Django . I stuck at the posting the variable into the Django (DB). I am not getting idea how to post the score variable of Java script along with the name which the user logged into the application. I will share the code of the Javascript . Note: Here I didn't used the views.py to calculate score of user. Entire thing I used the JavaScript to validate and to calculate the score. I got three questions from this : please answer anyone How to get the variable value from the JavaScript to the Django views? Please tell me the way. Can we use the ajax to post variable value into the Django views. If the value is displaying in the html template. For suppose my score value is storing in the score variable in JavaScript and displaying in the html . I want that value into my Django views. Then how to get that value from the javascript? Note: Here score is not storing in the form. It is an individual variable HTml:- In this place the score will displays <div id="result" class="result" style="display:none;"></div> JavaScript:- var resultCont = document.getElementById('result'); if (currentQuestion … -
django template if and tag not functioning the way I expect
I have a team and the number of users is limited by the membership type of the leader of that team. "num_members" gets passed through the view and I displayed num_members and user.membership_type above the if statement to see if they were 5 and Premium and they certainly are but the "else" statement gets triggered still. Is there some kind of small error in my "and" statement that I'm not seeing? I also tried using if, and, or instead of two if ands but achieved the same outcome. So in my template I have: {{ num_members }} <!-- This prints 5 --> {{ user.membership_type }} <!-- This prints Premium --> {% if user.team_leader %} <!-- user has a boolean field for team_leader --> {% if num_members == 5 and user.membership_type == 'Premium' %} stuff {% elif num_members == 10 and user.membership_type == 'Enterprise' %} stuff {% else %} other stuff {% endif %} {% endif %} I fixed it by applying the filters in the view and creating a "current_membership" parameter along with the "num_members" parameter. num_members = CustomUser.objects.filter(user_team=pk).count() user_membership_qs = CustomUser.objects.filter(email=request.user).first() current_membership = str(user_membership_qs.membership_type) This seemed to work just fine when replacing the template code with the current_membership parameter …