Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does not display data after filling in the template
I make comments on the site and cannot understand why, after the user has filled out comment forms, they are not displayed, I try to display them through a template P.S I need to display the text and the nickname that the user would enter views.py def CommentGet(request): if request.method == 'POST': comment = Comments(request.POST) name = request.POST['name'] text = request.POST['text'] if comment.is_valid(): comment.save() return HttpResponseRedirect(request.path_info) comments = CommentModel.objects.all() else: comment = Comments(request.POST) comments = CommentModel.objects.all() return render(request, 'news/post.html', {'comment': comment,'comments':comments}) post.html <form method="post" action="{% url 'comment' %}"> {% csrf_token %} <input type="text" name="name" value="{{ name }}"> <input type="text" name="text" value="{{ text }}"> <input type="submit"> </form> {% for comm in comments %} <h1> {{ comm.name }} </h1> <h1> {{ comm.text }} </h1> {% endfor %} models.py class CommentModel(models.Model): name = models.CharField(max_length=100) text = models.TextField(default='') dates = models.DateTimeField(auto_now=True) class Meta: ordering = ['-dates'] def __str__(self): return self.name -
'TemplateDoesNotExist': template loader appears to be searching non-existent routes
I'm receiving a TemplateDoesNotExist error when I click on a particular link, and I've noticed from the 'template-loader postmortem' that Django is searching incorrect and non-existent paths. I've recently moved half of the contents of a Django app called 'reviews' into another called 'accelerators'. My templates directory for each app follows the pattern: '"app name"/templates(folder)/"app name"/html templates'. Having moved the template into the accelerators app (and having updated my settings and urls), Django should be looking for the template via 'accelerators/templates/accelerators/accelerator_form.html', but according to the error message it's instead searching: 'accelerators/templates/reviews/accelerator_form.html'. I suspect this has something to do with the fact that I've just moved this template, alongside a number of other files, from the reviews app, but I can't figure out why this is happening. I've included my updated urls etc. below for reference. Base directory urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='accounts/logout.html'), name='logout'), path('', include('accounts.urls')), path('reviews/', include('reviews.urls')), path('accelerators/', include('accelerators.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) accelerators/urls.py from django.urls import path from .views import ( AcceleratorListView, accelerator_detail, accelerator_reviews, AcceleratorCreateView, AcceleratorUpdateView, AcceleratorDeleteView, ) from . import views urlpatterns = [ path('', AcceleratorListView.as_view(), name='accelerators'), path('<int:pk>/', views.accelerator_detail, name='accelerator_detail'), path('new/', AcceleratorCreateView.as_view(), name='accelerator_create'), path('<int:pk>/update/', AcceleratorUpdateView.as_view(), name='accelerator_update'), path('<int:pk>/delete/', AcceleratorDeleteView.as_view(), name='accelerator_delete'), path('<int:pk>/reviews/', views.accelerator_reviews, name='accelerator_reviews'), … -
Getting 1062, Duplicate entry for key unique constraint key, but there are no rows in database with the data for which unique constraint is added
We are getting 1062, “Duplicate entry" for Key "unique constraint key name" on saving Django Model, whereas there are no existing rows in database with the unique constrained data, for eg: we have added unique together for email and phone number fields, but when we try to save data we are getting duplicate entry. This is not happening all the time but in some cases, also this happens a lot when database cpu utilization is high , we are using Amazon AWS -
Django on Google App Engine: Cron Job Returning 400
I am trying to create a cron job on Google App Engine for my Django application deployed in the flexible environment. The cron job is deployed and view-able on the GCP dashboard but when it runs it shows "Failed". In the logs I can see that it is returning an HTTP 400 error, which is likely the the problem. I am able to go to the URL that the cron job requests by putting into my browser. Checking the logs, that shows an HTTP status 200. The error only occurs when I press the "Run Now" button on the Cron Jobs GCP dashboard, or when it runs automatically at the interval specified in cron.yaml. This is my first attempt at setting up a cron job on Google App Engine so forgive me if this is not correct. I'm treating this like any other view function in Django. The url is specified in urls.py, which routs to the view function. The view function runs my process and returns an HttpResponse. For troubleshooting purposes, I've removed any process from the view function and just return the HttpResponse (see code below); obviously, the intention is to put a process in the function once … -
How to convert SQL import to Django import?
I'm trying to import data from a database using Django. This was previously done using SQL, but now I'm trying to use Django instead of SQL. I'm not familiar with SQL really and am having trouble converting the SQL import to a Django one. So far, I've converted con = psycopg2.connect("dbname='mydatabase' user='mydatabase_reader' host='xxx.xxx.xx.xx' password='test'") to users = EventTransactions.objects.using('mydatabase').filter('profitcenter_id'=profitcenter_id, 'actualdatetime'=date).values('') but that's as far as I've gotten. Right now, I'm working on using the for loop to grab information for each day. def handle(self, *args, **options): r = redis.Redis(host=REDIS_HOST, db=REDIS_DB) memberships = MEM_MAP_INV.keys() start_date = datetime.datetime.strptime(options['start_date'],'%Y-%m-%d').date() end_date = datetime.datetime.strptime(options['end_date'],'%Y-%m-%d').date() profitcenter_id = options['profitcenter_id'] # number of days passed elapsed_days = (end_date - start_date).days dates = [start_date + datetime.timedelta(days=i) for i in range(elapsed_days)] con = psycopg2.connect("dbname='mydatabase' user='mydatabase_reader' host='xxx.xxx.xx.xx' password='test'") cur = con.cursor() for date in dates: counts = {} for m in memberships: membership = tuple(MEM_MAP_INV[m]) sql = cur.mogrify("""SELECT count(*) from eventtransactions WHERE profitcenter_id = %s AND date(actualdatetime) = %s""", (profitcenter_id, date)) # have to split into two cases due to how postgres queries for NULL values if m == 'n/a': sql = cur.mogrify(sql + """ AND membertype IS NULL""") else: sql = cur.mogrify(sql + """ AND membertype IN %s""",(membership,)) cur.execute(sql) count = … -
Is there anyways to store the data from the forms into variables without saving it to the database?
I'm trying to save the data inside a form into variables without saving it to the database but I don't know how. I'm not even sure if it's possible. -
Pass id parameter into imported class in Django
In Django I have a function based view responsible of printing the details (actually only the name) of all the registered users on a pdf file. def test_pdf(request, id): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="My Users.pdf"' buffer = io.BytesIO() report = MyPrint(buffer, 'Letter', id) pdf = report.print_users() response.write(pdf) return response This function works because I imported in the views.py file a class I built in another file, responsible of drawing the pdf, MyPrint: from reportlab.lib.pagesizes import letter, A4 from reportlab.platypus import SimpleDocTemplate, Paragraph from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.enums import TA_CENTER from django.contrib.auth.models import User class MyPrint: def __init__(self, buffer, pagesize): self.buffer = buffer if pagesize == 'A4': self.pagesize = A4 elif pagesize == 'Letter': self.pagesize = letter self.width, self.height = self.pagesize def print_users(self): buffer = self.buffer doc = SimpleDocTemplate(buffer, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=72, pagesize=self.pagesize) # Our container for 'Flowable' objects elements = [] # A large collection of style sheets pre-made for us styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='centered', alignment=TA_CENTER)) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. users = User.objects.all() elements.append(Paragraph('My User Names', … -
validate and handle error to pass meaningful status back to client
I am using graphene-django instead of rest api(rest framework). I am working on user registration. In the rest framework, validation was done in serializers part but when using graphene how do i validate and handle error for passing meaningful status to client? Here is the registration code class Register(graphene.Mutation): class Arguments: email = graphene.String(required=True) password = graphene.String(required=True) password_repeat = graphene.String(required=True) user = graphene.Field(UserQuery) success = graphene.Boolean() errors = graphene.List(graphene.String) @staticmethod def mutate(self, info, email, password, password_repeat): if password == password_repeat: try: user = User.objects.create(email=email) user.set_password(password) user.is_active = False user.full_clean() user.save() return Register(success=True, user=user) except ValidationError as e: import pdb pdb.set_trace() return Register(success=False, errors=[e]) return Register(success=False, errors=['password', 'password is not matching']) one example can be validation for if user with email already exists -
Image are not displayed in my home page from model.py
I have created a form for user to post their stuff, all other stuff works fine only image can't be displayed in my home page I have tried to overlook again and again the code seems to ok, my guess is the structure of folders of image. Am not really sure how to structure the folders for images. Please help!! views.py @login_required def PostNew(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('loststuffapp:IndexView') else: form = PostForm() return render(request, 'loststuffapp/form.html', {'form': form}) models.py class Documents(models.Model): docs_name = models.CharField(max_length=200,verbose_name="Names in Documents") item_type = models.CharField(default="", max_length=100,verbose_name="Item type" ) police_station = models.CharField(max_length=255, verbose_name="Police station") phone_no = models.CharField(verbose_name="Phone number", max_length=10, blank=False, validators=[int_list_validator(sep=''),MinLengthValidator(10),], default='0766000000') date = models.DateTimeField(default=timezone.now,verbose_name="Date") Description = models.TextField(blank=True, null=True,verbose_name="Description") pay_no = models.IntegerField(default=0,verbose_name="payment number") publish = models.BooleanField(default=False) image = models.ImageField(default="add Item image", upload_to="media",blank=False, verbose_name="Images") """docstring for Documents""" def __str__(self): return self.docs_name forms.py class PostForm(forms.ModelForm): class Meta: model = Documents fields = ['docs_name', 'item_type', 'police_station','phone_no', 'Description', 'image'] labels = {'docs_name': 'Name in Documents','item_type':'Item type','police_station':'Police station', 'phone_no':'Phone number','Description':'Description','image':'Images' } setting.py STATIC_URL = '/static/' MEDIA_URL ='/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'loststuff/media') home.html {% for Doc in documents %} <div class="content-wrapper"> <div class="card"> <div class="card-image"> <p><label style="font-size:15px; font-weight: bold;color: black;">Names in … -
Recommended way to render a form with radio button in each row
I want to build a form with a table in which each row contains a radio button and some additional information. Suppose I have two related models: class City(models.Model): name = models.CharField(...) state = models.CharField(...) class Business(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE, null=True) I want to create a table showing all rows from the City model with a radio button in the first row, to be saved as the city field in a Business model instance. The additional columns in the table should not be editable. Each row in the table would look something like this: <tr> <td> <input type="radio" name="city_radio"/> </td> <td>CITY NAME HERE</td> <td>CITY STATE HERE</td> </tr> My first thought was to use a ModelFormSet and create a ModelForm representing each row: class CityTableRowForm(forms.ModelForm): city_radio = forms.RadioSelect() class Meta: model = City fields = ['name', 'state'] And use it in the template as such: {% for form in cities_formset %} <tr> <td> {{ form.city_radio }} </td> <td>{{ city.instance.name }}</td> <td>{{ city.instance.state }}</td> </tr> {% endfor %} The table does get rendered correctly. The problem is, each radio gets a different name and so they behave independently from each other. My second approach was to create a ModelForm representing the … -
Always getting 401 or 500 when authenticating users with amazon application load balancer and django oidc provider at receiving access token
I cannot get ALB to check the /userinfo endpoint after receiving access_token, refresh_token and id_token to it I'm trying to authenticate users with Amazon ALB and django_odic_provider. I have set the load balancer authentication on ALB side, tested all oidc endpoints (all are accessible and returning valid results). When I try to authenticate I'm presented with django's login view, I successfully authenticate, but on return from django's oidc/authorize endpoint I get 401 Unauthorized on oauth2/idpresponse page of load balancer. If I try to use Cognito and federated django_oidc_provider I also successfully log in and on return from authorize to oauth2/idpresponse I'm getting 500 server error with message: Exception processing authorization code. It seems to me that ALB is not able to read my response but when I check it everything is formatted as in documentation and jwt is ok. By looking at logs it seems that load balancer never checks token and userinfo endpoints once it receives access_token, refresh_token and it_token from authorization endpoint. I would like to understand how load balancer interprets this response in order to try to figure out what is wrong with it. This is authorization response: { 'access_token': 'd90623245e474ee0b23a0a9ca062ba74', 'refresh_token': '4d439d3249e64cbe9975310f84431c25', 'token_type': 'Bearer', 'expires_in': 3600, … -
djang admin client not making post request properly
I'm trying to make a post request with pytest admin client @pytest.mark.django_db def test_organisation_upload(admin_client): resp = admin_client.post("/mypage/upload_organisations/", follow=True) import pdb; pdb.set_trace() print(resp.content) assert resp.status_code == 201 I have a form in /mypage. When submitting the form, the user is directed to /mypage/upload_organisations/ Problem is, the response being returned is the page itself -- not the result that should be shown upon successful upload. how do i fix this? I want it to actually upload the form, not just go to the page. Everything works fine when i use a request factory (rf) instead. -
Calling a PL/SQL procedure from django with callproc
I need to call a procedure in PL/SQL from an API in Django. I use the callproc and the right values, but get the error: "PLS-00306: wrong number or types of arguments in call" In Oracle I have: PROCEDURE new_payment(pv_id IN VARCHAR2, parr_user IN OWA.vc_arr, parr_date_reg IN OWA.vc_arr, parr_d_value IN OWA.vc_arr, parr_descr IN OWA.vc_arr, parr_type IN OWA.vc_arr, pi_gerar_ref_mb IN PLS_INTEGER DEFAULT 0, pv_data_limite_ref_mb IN VARCHAR2 DEFAULT NULL) In models.py I have: class PAYMENT(): def new_payment(self, id, user, date_reg, value, descr, type): cur = connection.cursor() ref = cur.callproc("PAYMENT.new_payment", [id, user, date_reg, value, descr, type]) cursor.close() return ref In views.py: `pay=PAYMENT() x=pay.new_payment('123', '111', '2019-07-23', '10', 'test1', 'teste2`) At this point, i get the error: `"ORA-06550: line 1, column 7: PLS-00306: wrong number or types of arguments in call to 'NEW_PAYMENT'"` Any tip in what am I doing wrong? -
Python Django - update booleanField via List View
Is there any way how to update booleanField in the list view? In list view I have listed all my orders and I need to mark which are done and which are not done. I know I can update it via UpdateView, but that is not user friendly because I have to leave the listview page. models.py class Order(models.Model): ... order = models.CharField(max_length = 255) completed = models.BooleanField(blank=True, default=False) views.py class OrderIndex(generic.ListView): template_name = "mypage.html" context_object_name = "orders" def get_queryset(self): return Order.objects.all().order_by("-id") mypage.html {% extends "base.html" %} {% block content %} {% for order in orders%} User: {{ order.user}} | Completed: {{order.completed}} <input type="checkbox"> {% endfor %} <input type="submit"> {% endblock %} I am quite new to the django framework and have no idea how to make it work. -
$group aggregation with $sum returns nothing
I have a query which runs as expected when it's directly executed in MongoDB, but I'm facing some troubles trying to make it work through MongoEngine. In fact, it returns nothing. Query on MongoDB (which works correctly): db.annual_account.aggregate([{ $group: { "_id":"$adress.city", "total"{$sum: 1} }} ]) Result (which is what I expect): { "_id" : "Genk", "total" : 1 } { "_id" : "Ottignies-Louvain-la-Neuve", "total" : 1 } { "_id" : "Ganshoren", "total" : 1 } { "_id" : "Mont-de-l'Enclus", "total" : 1 } { "_id" : "Charleroi", "total" : 1 } And now, my query on MongoEngine in my views.py: class StatisticsView(generics.ListAPIView): serializer_class = AnnualAccountSerializer def get_queryset(self): group = {"$group" : {"_id": "$code", "total": {"$sum":1} } } response = AnnualAccount.objects.aggregate(group) return response Results: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ {}, {}, {}, {}, {}, ] Does someone has any idea of what is wrong, please? Why I don't have the same result between the shell Mongo and MongoEngine? Thank you, Simon -
HINT: Perhaps you meant to reference the column
When I open the page, I get error: column user_landings_landing.flow_chatbot_id does not exist LINE 1: ...ding"."message", "user_landings_landing"."video", "user_land... ^ HINT: Perhaps you meant to reference the column "user_landings_landing.flow_chatbot". How can I fix it? I tried ` SELECT "flow_chatbot" FROM user_landings_landing; and SELECT flow_chatbot FROM user_landings_landing; but it's not efficiency. -
How to save custom added field in an extended user creation form in django
I am pretty new to Django and i made a custom signup form by extending the UserCreationForms in Django. class SignUpForm(UserCreationForm): #This class will be used in views of account to make sigupform user_type = forms.CharField(required=True,widget=forms.Select(choices=usertypes)) email = forms.CharField(max_length=254, required=True, widget=forms.EmailInput()) class Meta: model = User fields = ['username', 'user_type','email','password1','password2'] def save(self,commit=True): user = super(SignUpForm, self).save(commit=False) user.user_type = self.cleaned_data['user_type'] print('Flag3') if commit: user.save() return user It is working fine with the view : def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) print('Flag0') if form.is_valid(): user = form.save() if user.user_type == 'Seller' or user.user_type=='seller': print('Flag1') auth_login(request, user) print('Flag2') print(user.user_type) group = Group.objects.get(name='Seller') print(group.name) print('Flag3') user.groups.add(group) return redirect('get_seller') if user.user_type == 'Customer' or user.user_type=='customer': print('Flag1') auth_login(request, user) print('Flag2') print(user.user_type) group = Group.objects.get(name='Customer') print(group.name) print('Flag3') user.groups.add(group) return redirect('home') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) I added flags because is was checking the progress of the form. The problem that i am facing is that i want to save the custom field that made user_type . I don't know how to save the custom field or if it is being saved how to get the value. -
I need to do a form that changes on-the-fly depending of a choice
The form that I need to do is for the user to select a payment type.The problem is that depending on the choice if the user wants to pay monthly or annually a different date-picker field has to appear. if he selects monthly, he has to choose a day of the month. And if he chooses annually a date-picker that allows him to pick the month has to appear. I've been searching online for an answer but all I can find is dynamic form in the sense that it can generate a field type multiples times and that is not what I need. All help is appreciated. -
problem with modelchoicefield show objet 1 and object 2without names?
hi friends i have model structure with code and names (structure_desig) i want show list of choices in modelchoicefield and it shows like this structure: --------------------- structure object(1) structure object (2) and i want show name of structure not like that from django.db import models # Create your models here. class Structure(models.Model): structure_code=models.CharField(max_length=1) structure_desig=models.CharField(max_length=350) def __str__(self): return self.structure_desig class Service(models.Model): structure_id= models.ForeignKey(Structure,on_delete=models.CASCADE,null=True) service_desig=models.CharField(max_length=350) class Immob(models.Model): immo_code=models.CharField(max_length=7) immo_desig=models.CharField(max_length=150) immo_qte=models.FloatField(default=1) immo_datemes=models.DateTimeField() immo_cptimmob=models.CharField(max_length=10) immo_dureevie=models.IntegerField(default=7) immo_numaut=models.CharField(max_length=4) immo_origine=models.CharField(max_length=1) immo_fournisseur=models.CharField(max_length=150) immo_nufact=models.CharField(max_length=20) immo_datefact=models.DateTimeField() immo_valht=models.DecimalField(max_digits=18,decimal_places=2) immo_monaie=models.CharField(max_length=3) immo_tauxcvt=models.DecimalField(max_digits=18,decimal_places=2) immo_tauxctrval=models.DecimalField(max_digits=18,decimal_places=2) immo_frais=models.DecimalField(max_digits=18,decimal_places=2) immo_coutacq=models.DecimalField(max_digits=18,decimal_places=2) immo_refcmde=models.CharField(max_length=35) immo_datecmde=models.DateField() immo_journee=models.CharField(max_length=10) immo_cptanal=models.CharField(max_length=9) immo_local=models.CharField(max_length=45) immo_mode_amort=models.CharField(max_length=1) immo_code_r=models.CharField(max_length=2) immo_val_amort=models.DecimalField(max_digits=18,decimal_places=2) immo_status=models.CharField(max_length=1) immo_code_bar=models.CharField(max_length=25) service_id= models.ForeignKey(Service,on_delete=models.CASCADE,null=True) #this is the forms.py from django.contrib.auth.forms import AuthenticationForm from immob.models import Structure from django import forms class LoginForm(AuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs= {'class':'form-control'})) password = forms.CharField(widget=forms.PasswordInput(attrs= {'class':'form-control'})) class UserRegistrationForm(forms.Form): username = forms.CharField(label='Username', max_length=100) password = forms.CharField(label='Password', max_length=100) structure = forms.ModelChoiceField(Structure.objects.all(), to_field_name="structure_desig") the result it shows like that without names of structure structure: --------------------- structure object(1) structure object (2) and i want show name of structure not like that -
Django how to handle urls.py with a login form in a navbar
I have a login form in a navbar accesible via context processors, I want it to be shown in every page where there's no active user. core/context_processors.py def login_form(request): form = AuthenticationForm() return { 'auth_form': form } The urls.py is stated as normal core/urls.py path('accounts/', include('django.contrib.auth.urls')), And the form in the navbar is called this way: <h2>Login</h2> <form method="post" action="{% url 'login' %}"> {% csrf_token %} {{ auth_form | crispy }} <input type="submit" class="btn btn-primary" value="Login"/> <p><a href="{% url 'password_reset' %}">Lost password?</a></p> </form> Now I don't want a custom login view, since it's available in all templates. But when I hit login I got redirected to a 404 or the login template if a create one. How can I bypass the template part, login the user and redirect somewhere else? -
Django, psycopg2: permission denied on Heroku server
I have a Django project running on Heroku, every time an action is carried out, I get a looong series of errors like this, all pointing back to the same cause: ERROR:django.request:Internal Server Error: /event/ Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: permission denied for relation django_session The URL /event/ does not exist on my project, nor is it referenced anywhere in it, and as far as I know there isn't a database associated with this slackbot (so if someone could also direct me as to how to list all existing databases I would be grateful). How can I fix this through Heroku? I tried the online console with some basic psql command, but all I got was this response psql: could not connect to server: No such file or directory -
django multiple annotate sum advanced
I Have the following queryset, and I want to multiple sum using django annotating but i have some error, Could you please have your suggestions on this??, any help will be appreciated. i already try this but not same what i want myqueryset= BuildingCell.objects.filter(absent__publish='2019-07-22', absent__building_name='f2', absent__bagian='CUT', inputcutsew__publish='2019-07-22', inputcutsew__days='normal', inputcutsew__user=factory_user_cutting)\ .exclude(inputcutsew__cell_name__isnull=True).exclude(inputcutsew__cell_name__exact='').order_by('inputcutsew__cell').values('inputcutsew__cell', 'inputcutsew__model', 'absent__normal_mp', 'absent__ot0_mp', 'absent__ot1_mp', 'absent__ot2_mp', 'absent__ot3_mp').exclude(occult_cell='yes')\ .annotate(total_output_jam=Coalesce(Sum(Case(When(inputcutsew__dummy_days='normal', then='inputcutsew__output'))), 0), total_output_ot=Coalesce(Sum(Case(When(inputcutsew__dummy_days='overtime', then='inputcutsew__output'))),0), total_time=Coalesce(Sum('inputcutsew__time'),0), total_time_ot=Coalesce(Sum('inputcutsew__time_ot'),0), total_time_ot1=Coalesce(Sum('inputcutsew__time_ot1'),0), total_time_ot2=Coalesce(Sum('inputcutsew__time_ot2'),0), total_time_ot3=Coalesce(Sum('inputcutsew__time_ot3'),0))\ .annotate( normal_wmh=Coalesce(F('absent__normal_mp'),0)*Coalesce(F('total_time'),0), normal_swmh=Coalesce(F('absent__normal_mp'),0)*Coalesce(F('total_time'),0), overtime_wmh=(Coalesce(F('absent__ot0_mp'),0)*Coalesce(F('total_time_ot'),0))+(Coalesce(F('absent__ot1_mp'),0)*Coalesce(F('total_time_ot1'),0))+(Coalesce(F('absent__ot2_mp'),0)*Coalesce(F('total_time_ot2'),0))+(Coalesce(F('absent__ot3_mp'),0)*Coalesce(F('total_time_ot3'),0)), overtime_swmh=(1.5*Coalesce(F('absent__ot0_mp'), 0) * Coalesce(F('total_time_ot'), 0)) + (2*Coalesce(F('absent__ot1_mp'), 0) * Coalesce(F('total_time_ot1'), 0)) + (2*Coalesce(F('absent__ot2_mp'), 0) * Coalesce(F('total_time_ot2'), 0)) + (2*Coalesce(F('absent__ot3_mp'), 0) * Coalesce(F('total_time_ot3'), 0)))\ .annotate( sum_total_output_jam=Sum(F('total_output_jam')), sum_total_output_ot=Sum(F('total_output_ot')), sum_overtime_wmh=Sum(F('overtime_wmh')), sum_overtime_swmh=Sum(F('overtime_swmh')) ) FieldError at /superuser/inputtime/2/3/f2/CUT/2019-07-22 Cannot compute Sum('total_output_jam'): 'total_output_jam' is an aggregate -
How to fix: "Unknow command: manage.py" in a Django project in PyCharm (newbie)
I'm totally new to Django, just learned a bit Python for science analysis. I use PyCharm as IDE wanted to made the django "tutorial" from the PyCharm website (https://www.jetbrains.com/help/pycharm/creating-and-running-your-first-django-project.html). I struggle quite early at the point "Launching Django Server". So, I can open the new command line with Ctrl+Alt+R, but when I enter "manage.py" as described in the tutorial I get the error "Unknown command: manage.py Type'manage.py help' for usage". If I type 'manage.py help' the same error occurs. Since PyCharm creates the files, the code itself should be functional since I didn't changed a single line. The versions are: PyCharm 2019.1.3 (Professional); Python: 3.7; Django: 2.2.3 I tried to run PyCharm as administrator. Since I'm totally new to Django I also have no idea what else I should try. A google search showed just findings not comparable to mine. -
How to display and hstore field in forms as separate fields in django
I trying to create a form that separates the hstore field address into fields street, city, state, and zipcode in form.py. But when the form is submitted, it will be added to the database as Hstorefield with {'street':street,'city':city,'state':state,'zipcode':zipcode}. Any help is appreciated! model.py from django.contrib.postgres.fields import HStoreField class Student(models.Model): user=models.OneToOneField(CustomUser,on_delete=models.CASCADE,primary_key=True,) fullname=models.CharField(max_length=100,null=False,blank=False,default="fullname") address=HStoreField(null=True) form.py class StudentProfileForm(forms.ModelForm): street=forms.CharField(max_length=80, required=True, strip=True) city=forms.CharField(max_length=50, required=True, strip=True) state=forms.CharField(max_length=20, required=True, strip=True) zipcode=forms.IntegerField(required=True) class Meta: model = Student exclude = ['user'] # I've tried adding this, but that does nothing to the database. def clean(self): self.cleaned_data['address'] = {"street":self.cleaned_data.get('street'),"city": self.cleaned_data.get('city'), "state": self.cleaned_data.get('state'),"zipcode":self.cleaned_data.get('zipcode'),}, self.save() -
Get data related to manytomany field
I have two model, first one is Industries, second one is experts. My models looks like this. name = models.CharField(max_length=255, verbose_name="Industry name") slug = models.SlugField(unique=True, blank=True, max_length=150) class Expert(models.Model): name = models.CharField(max_length=255, blank=True, verbose_name="Expert Name") industry = models.ManyToManyField(Industries, blank=True, verbose_name="Industries") on the all experts page I made an industries field clickable, when user clicked any industry, My goal is show the experts which is in this industry. My urls.py looks like this: path('e/country/<slug:slug>', ExpertCountryView.as_view(), name="expert_country") Now I am confused with my views.py how can I create my view (ExpertCountryView) to shows me experts with this industry. example: www.mysite.com/p/country/trade trade is my industry. I hope all is understandable.