Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NOT NULL constraint failed: registratie_inkomen.pg_id
This are my models: class PersoonGegevens(models.Model): # Voornaam en achternaam voornaam = models.CharField(max_length=265,) achternaam = models.CharField(max_length=265) #username user = models.OneToOneField(User, on_delete=models.CASCADE) class inkomen(models.Model): pg = models.ForeignKey(PersoonGegevens, on_delete=models.CASCADE) inkomenfield = models.CharField(max_length=100) This is the form: class inkomenForm(forms.ModelForm): class Meta(): model = inkomen fields = ('inkomenfield',) This is my view: def tijdelijk(request): #User id user = request.user.id if request.method == 'POST': incoming = inkomenForm(data=request.POST) if incoming.is_valid(): incoming.save() return HttpResponse("saved") else: x = incoming.errors print (x) return HttpResponseRedirect('/tijdelijk') else: incoming = inkomenForm() return render(request, 'index/tijdelijkeindex.html', {'inkomen':incoming}) I have tried: incoming.save(commit=False) incoming.pg = user incoming.save also readed the documentation about Inline formsets of django. But i dont really get So i get the following error:(NOT NULL constraint failed) and i know it comes because i need to assign the pg.id and i know i can do that by adding the field in the form.py and let the user choose the id. But what i actually want is that pg = the logged in user. -
Django adding and removing form ManyToMany field: AttributeError: 'QuerySet' object has no attribute 'add'
I am trying to add users to a many to many fields in my course model buy I am getting an error: Course.course_dislikes.through.objects.filter(course__course_code=code,course__course_university=university).add(request.user) AttributeError: 'QuerySet' object has no attribute 'add' My intention is to filter my Course model based on course code and add a user to like a field or remove it when the user dislikes. Now I know I cannot use get since there may be two objects with the same course code. Currently, I am trying to do this by: Course.course_likes.through.objects.filter(course__course_code=code).remove(request.user) I have tried with get but it gaves me an error that two objects with the same name exist which is understandable since get has to return one unique object. How can I achieve this withot for-loop as I cannot think of anny other method. -
Stack Inline Multiple Django Models in Admin with indirect relationship
I have the following three models class Participant(models.Model): participant_id = models.AutoField(primary_key=True) pin = models.CharField(unique=True, max_length=4, validators=[RegexValidator(r'^\d{1,10}$')]) class Teacher(models.Model): teacher_id = models.AutoField(primary_key=True) participant_id = models.OneToOneField(Participant, on_delete=models.CASCADE) email = models.EmailField() compensation_id = models.OneToOneField(Compensation, on_delete=models.CASCADE) class Compensation(models.Model): compensation_id = models.AutoField(primary_key=True) wage = models.DecimalField(max_digits=6, decimal_places=2) To summarize, Participant has different types one of them is Teacher (OneToOne relation). The teacher is one type of employee that is compensated with and it's related (OneToOne relation) with Compensation Model I want to create an admin form by stacking Participant Teacher Compensation The problem: I am using Participant as a primary model and stacking teacher to it. However, when I try to stack compensation to it, it apparently doesn't work due to missing foreign key relation between Participant and Compensation models. An easy way out would be to have the fields of the Compensation model in the Teacher Model. However, it would create redundancy when I want to associate other types of Participants to it. What could potentially be a solution to this? I am open to altering the model if it makes thing any easier or less complicated. P.S. There are also other types of participants (Child, Parent) that I have not mentioned. -
Django 3.0 Forms: Form Errors are not showing onto template
###I have model named Publisher in models.py file.### ###And based on this model, a modelForm has made, called "RegistrationForm".### ###Which renders form on registration.html template.### <br /> <br />**This is code of registration.html** <pre><code> ``` <body> <div class="container"> {% load my_filters %} <div class="row"> <div class="col-md-6 offset-md-3"> {% if registered %} <h1>Thank you for registering!</h1> {% else %} <h1>Register Here</h1> <h3>Just fill out the form.</h3> <form enctype="multipart/form-data" method="POST"> {% csrf_token %} {{ reg_form.non_field_errors }} <div class="fieldWrapper"> <div class="form-group"> {{ reg_form.name.errors }} <label for="{{ reg_form.name.id_for_label }}" >Name:</label> {{ reg_form.name|addclass:'form-control' }} </div> </div> <div class="fieldWrapper"> <div class="form-group"> {{ reg_form.email.errors }} <label for="{{ reg_form.email.id_for_label }}">Email:</label> {{ reg_form.email|addclass:'form-control' }} </div> </div> <div class="fieldWrapper"> <div class="form-group"> {{ reg_form.contact.errors }} <label for="{{ reg_form.contact.id_for_label }}">Contact:</label> {{ reg_form.contact|addclass:'form-control' }} </div> </div> <div class="fieldWrapper"> <div class="form-group"> {{ reg_form.password.errors }} <label for="{{ reg_form.password.id_for_label }}">Password: </label> {{ reg_form.password|addclass:'form-control' }} </div> </div> <div class="fieldWrapper"> <div class="form-group"> {{ reg_form.confirm_password.errors }} <label for="{{ reg_form.confirm_password.id_for_label }}">Confirm Password:</label> {{ reg_form.confirm_password|addclass:'form-control' }} </div> </div> <input type="submit" name="" value="Register"> </form> {% endif %} </div> </div> </div> </body> ``` </code></pre> ### I am NOT using crispy forms just manually rendering Django forms and using manual template tag to add classes to fields. **This is the template tag in used … -
How to add to the database outside of the admin site in django
I'm new to coding (6 months, self taught) and am currently working on an order and inventory management system using django. I have an order class setup in the database and am able to add orders using the django admin. My question is, how can I now create a separate html page with forums that will add orders to my database in the same way? I realize this is probably really general and basic, but I've yet to find the answer. Thanks tigerking -
django create confirm email for subscribe
I want to confirm e-mail for my subscribers. But I can not create confirm email. In views.py , I am sending e-mail but there is no confirm link. How can I create confirm link in this example ? models.py class Subscribe(models.Model): name = models.CharField(max_length=200,verbose_name="İsim") email = models.EmailField(max_length=200,verbose_name="E-Mail") confirmed = models.BooleanField(default=False) def __str__(self): return self.name + " - " + self.email views.py def yeniabone(request): if request.method == 'GET': form = SubscribeForm() else: form = SubscribeForm(request.POST) if form.is_valid(): request.session['form-submitted'] = True name = form.cleaned_data['name'] email = form.cleaned_data['email'] abone = Subscribe.objects.create(name=name,email=email) mymessage = "Merhaba "+name+",\nYazılarıma abone olduğun için teşekkürler. Aşağıdaki linkten aboneliğini onaylayıp yazılarımdan en hızlı şekilde haberdar olabilirsin.( I WANT TO SHOW CONFİRMATİON LİNK HERE )\n\nCemre ACAR - cemreacar.com" try: send_mail("Abone | cemreacar.com",mymessage,'Abonelik | Cemre ACAR <mail@cemreacar.com>',[email],'fail_silently=False') except BadHeaderError: return HttpResponse('Bir şeyler ters gitti!') return redirect('blog:yeniabone_onay') return render(request, "yeniabone.html", {'form': form}) -
{ % block content % } { % endblock % } is not working
This is main.html file: <!DOCTYPE html> <html> <head> <title>CRM</title> </head> <body> <h1>Navbar</h1> <hr> { % block content % } { % endblock % } <hr> <h1>Footer</h1> </body> </html> This is the contact.html { % extends 'accounts/main.html' % } { % block content %} <h2>contact!</h2> { % endblock % } this is my directory: accounts accounts accounts templates accounts contact.html main.html This is what I am getting: It displays the block tags too. -
How to build variable of integers + strings in python for loop?
Manually built variable STAFFLIST works in django database as a list of choices listed as PositiveSmallIntegers. STAFF1 = 1 STAFF2 = 2 STAFF3 = 3 STAFFLIST = ( (STAFF1, _('John Doe')), (STAFF2, _('Lisa Beauty')), (STAFF3, _('Harry Potter')), ) Print for this variable works as follows: >>>print(STAFFLIST[1]) (2, 'Lisa Beauty') >>> How to built this variable automatically in for loop based on the actual list of staffs? I was trying something like below, but unsuccsessful: from django.contrib.auth.models import User from django.utils.translation import gettext as _ staff = User.objects.filter(is_staff=True) idx=0 for stf in staff: STAFFLIST[idx] = (stf.id, _(stf.first_name + ' ' + stf.last_name)) idx=idx+1 I am getting error like: TypeError: 'str' object does not support item assignment I believe, my problem is low knowledge level of python datatypes. And currently, I am trying to work with tuple datatype and to store string inside. -
What is the best way to select single id from a loop using jquery in Django
I have a django template that loops through and displays all objects of a particular model. Each object displayed has a submit button. However, whenever I submit a form, the request always returns the id of the first object. html {% for food in food_list %} {{food}} <form action="{% url 'like'%}" id="form_id" method="post"> {%csrf_token%} <input name="food_id" type="hidden" value="{{ food.id }}"> <div class="like-button"></div> </form> {%endfor%} javascript <script> $('.like-button').on('click', function () { $(this).toggleClass('animate').promise().done(function () { document.getElementById("form_id").submit($(this)); }); }); </script> Please help, I am fairly new to jquery. -
Why is clang failing when building wheel for psycopg2?
I know this question or various forms of it has been asked. I am just trying to follow the Django tutorial on Heroku - which involves installing django-heroku, which has psycopg2 as a dependency. I am running MacOS Catalina, 10.15.3. I know one work around is to download the binary with pip install psycopg2-binary, but then I don't know how to get pip to recognize psycopg2-binary and stop trying to install psycopg2 from source when I run pip install django-heroku. So I suppose if someone could help me figure out that workaround, that would also suffice - although at this point I think I'm just gonna use Node. In any case, I feel like it's most likely just another instance of Catalina breaking things, but it would be nice to know how to fix this in case I ever have to use django-heroku/psycopg2. I have upgraded homebrew, reinstalled pyenv/python3.7.4, updated pip. I have openssl 1.1.1g installed (homebrew). I recently reinstalled XCode - but just to be sure it wasn't my compiler's fault, I installed homebrew clang using brew install llvm. Building wheels for collected packages: psycopg2 Building wheel for psycopg2 (setup.py) ... error ERROR: Command errored out with exit status … -
django + chart.js : Cannot get two bar charts on the same graph with appropriate data
I am fairly new to javascript and I cannot get a bar chart to workout. Here is what is going on: DATA: {'supplier : "ARAGON", average_service_level_implied:-9.24, average_service_level_optimal: 0.495} view.py @method_decorator(login_required, name='dispatch') class SupplierPage(LoginRequiredMixin,APIView): def get(self, request, *args, **kwargs): query = request.GET.get('search_ress', None) context = {} if query and request.method == 'GET': Supplier = supplier.objects.filter(supplier = query) context.update({'Supplier': Supplier}) return render(request, 'Supplier.html',context) and chart.js graph <script> $(document).ready(function() { var endpoint = 'items.html' var forecastdata = [] var reference = [] ; $.ajax({ method: "GET", url: endpoint, success: function (data) { reference = data.reference forecastdata = data.forecastdata setChart() }, error: function (error_data) { console.log(error_data) } } ) function setChart() { var ctx = document.getElementById('myChart3').getContext('2d'); var myChart3 = new Chart(ctx3, { type: 'bar', data: { labels: ["actual service level", "optimal service level"], datasets: [{ label: 'Service level analytics', data: [ {% for dr in reference %}{{ dr.niveau_service_implicite}}, {% endfor %}, {% for dr in reference %}{{ dr.niveau_service_optimal}}, {% endfor %} ], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, … -
Django website uploads faster than video on the background
I am new to Django and I am trying to build a website for a friend. I manage to create a view page on my localhost with a video on the background. However, the video takes approx 2 seconds longer to show on the website. The video is hosted locally on my machine. Can you please advise? Here is the code I use to have a video on the background: <div class="fullscreen-video-wrap"> <video src="{% static "/Sequence01.mp4" %}" autoplay = True loop=True></video> </div> Thank you, -
How use Django to create a search bar on the home page, then redirect to search results?
I have a search bar on my jobs_board.html page which works well. But I want to add this search bar to my home page so it performs the same search and redirects to the jobs_board.html page to display the results. Any suggestions on how I can add this the home.html and it's view.py Thanks in advance. jobs/views.py def get_jobs_queryset(query=None): queryset = [] queries = query.split(" ") for q in queries: posts = JobsPost.objects.filter( Q(title__contains=q)| Q(body__icontains=q) ).distinct() for post in posts: queryset.append(post) def board_jobs_view(request): context = {} query = "" if request.GET: query = request.GET['q'] context['query'] = str(query) jobs_posts = sorted(get_jobs_queryset(query), key=attrgetter('date_updated'), reverse=True) context['jobs_posts'] = jobs_posts return render(request, "jobs/jobs_board.html", context) jobs_board.html <div class="container"> <div class="center"> <h1 class="display-4"> <form method="get"> <input class="form-control form-control-lg" type="text" name="q" id="id_q" placeholder="Search Jobs"> </h1> </div> </div> <script type="text/javascript"> document.getElementById("id_q").value = "{{query}}" </script> -
Good practices in creating a json with conditionals
I would like to improve the creation of this json, it has a conditional part but I don't think it is the best practice. I would appreciate examples with JS and Python example(list_contacts) { this.list_person= []; list_contacts.forEach(item => { let natural_person = item.natural_person; let _natural_person = { birth_day: natural_person.birth_day, dni: natural_person.dni, full_name: natural_person.full_name, dniPartner: '', full_name_partner: '', birth_day_partner: '', phone: natural_person.contact_details[0].concept, email: natural_person.contact_details[1].concept }; let partner = natural_person.partner; if (natural_person.partner != undefined) { _natural_person.dniPartner = partner.dni; _natural_person.full_name_partner = partner.full_name; _natural_person.birth_day_partner = partner.birth_day; } this.list_person.push(_natural_person); }); } -
django 3.0 inline admin form foreignkey -> foreignkey
I have any models and one Manager app/models.py class castratedListStudent(models.Manager): use_in_migrations = False def get_query_set(self): return super().get_query_set().filter(isOn=1) class student(models.Model): id = models.AutoField(primary_key=True) firstName = models.CharField(max_length=20) lastName = models.CharField(max_length=20) isOn = models.BooleanField() default_manager = castratedListStudent() objects = castratedListStudent() class discipline(models.Model): id = models.AutoField(primary_key=True) nameDiscipline = models.CharField(max_length=100, null=False) itemIdToDiscip = models.ForeignKey(item, on_delete=models.CASCADE, default=1) class listOfStudForDiscipline(models.Model): id = models.AutoField(primary_key=True) discipListId = models.ForeignKey(discipline, on_delete=models.CASCADE) studId = models.ForeignKey(student, on_delete=models.CASCADE) I am using django inline accounts/admin.py class discipStudentInline(admin.TabularInline): model = listOfStudForDiscipline admin.TabularInline.verbose_name = 'Student' extra = 0 def has_change_permission(self, request, obj=None): return False def get_queryset(self, request): return self.model.objects.filter(studId__isOn=1) class disciplineAdmin(admin.ModelAdmin): model = discipline inlines = [discipStudentInline] The Inline form is displayed on the HTML page and filter (studId__isOn=1) works. But the problem is that on the HTML page below there is a field that allows you to add another student and the list of students is not filtered by the filter rule(studId__isOn=1) When I check in the DEBUG_SQL console, I can see how the query goes without the WHERE expression "FROM journal_student". (0.000) SELECT `journal_listofstudfordiscipline`.`id`, `journal_listofstudfordiscipline`.`discipListId_id`, `journal_listofstudfordiscipline`.`studId_id` FROM `journal_listofstudfordiscipline` INNER JOIN `journal_student` ON (`journal_listofstudfordiscipline`.`studId_id` = `journal_student`.`id`) WHERE (`journal_student`.`isOn` = 1 AND journal_listofstudfordiscipline`.`discipListId_id` = 1) ORDER BY `journal_student`.`lastName` DESC; args=(True, 1) (0.000) SELECT `journal_student`.`id`,..., `journal_student`.`descriptionStudent` FROM journal_student` … -
Creating search functionality for profiles in my blog app based in Django
I want to extend my django blog app by creating a search form for User model based profiles. Currently any profile page is only accessed by the current logged in User with simple base url corresponding to the following urlpattern. urlpatterns = [ path('profile/', views_register.profile, name='profile'), ] I am fetching user search query from the following html template. <form method="GET" action="" id="searchform"> <input class="searchfield" id="searchbox" name="q" type="text" value="{{ request.GET.q }}" placeholder="Search..."/> </form> In my views.py, I have a function to receive this query but I don't know how to redirect the searching user to the corresponding user profile as the profile page for each user doesn't have any specific username based custom url. class ProfileSearch(LoginRequiredMixin): template_name = 'home.html' def get_queryset(self, request): query = request.GET.get('q') if query: return User.objects.filter(username__icontains=query) else: return User.objects.all() How do I redirect the query initiator to this new profile page? I know this function does nothing as it doesn't do any dynamic redirects but I am clueless. Following is the profile model and is auto created through signals when a new user registers. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default= 'default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = … -
How does Django decrypt EncryptedCharField fields?
So I've got a field in my Postgres database that is a bytea type. I know the decrypted value and also the key, but can't figure out how to get from that raw database value to the decrypted string. I believe I'm looking for the algorithm that Django uses to decrypt these values and how I can use that to encrypt another string. Django supposedly uses the package Keyczar, which mentions using Crypter package to encrypt/decrypt things. I'm unable to install that package so I'm not sure how to go about this in another way. I ultimately want to update a value in the EncryptedCharField field in my database since it is not valid anymore - is there a way to get this encrypted value online or within Python? -
Allowing users to login via FB and login by making an account on your website
I want to give people the opportunity of logging into my site using FB or by making an account on my site. At the moment I have separate pages for the two options. urls.py path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('abc/',TemplateView.as_view(template_name='blog/index.html'), name="facebook") I changed the name from facebook to abc to make sure that the name had nothing to do with the issue. When I click on the Login With Facebook button, every thing works fine. When I click Login on this screen, everything works fine. When I click Login with FB, nothing happens. index.html {% load socialaccount %} {% providers_media_js %} <head> <title>Facebook Registration</title> </head> <button class="btn"><a href="{% provider_login_url "facebook" method="js_sdk" %}">Login With Facebook</a></button> login.html {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% load socialaccount %} {% providers_media_js %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Log In</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Login</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Need An Account? <a class="ml-2" href="{% url 'register' %}">Sign Up Now</a> </small> </div> </div> <article class="media content-section"> <button class="btn"><a href="{% provider_login_url "facebook" method="js_sdk" %}">Login With Facebook</a></button> </article> {% endblock content %} -
Django Autocomplete Light ... PK vs display field
I am using DAL to provide a selectable dropdown list like this: class OccupationsModel(models.Model): Occupation_Code = models.CharField(max_length = 20, primary_key=True) Occupation_Title = models.CharField(max_length = 150, unique=True) Occupation_Desc = models.CharField(max_length = 1000) class Meta: db_table = 'Occupation_Info' def __str__(self): return self.Occupation_Title Note here that occupation_code is my PK while I am using str to show occupation_title as my display. Mostly everything works fine but then I use instance to prepopulate the form, the title is not displayed. The form field is empty. I have other similar models where the PK is the same as display and those work just fine. So I am pretty sure there is something I am missing here. Here is my DAL view: class OccCreateView(CreateView): model = OccupationsModel template_name = 'dashboard/input_page.html' form_class = InputForm class occautocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = OccupationsModel.objects.all().order_by('Occupation_Code') # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated: qs = qs[:3] if self.q: qs = qs[:3] if self.q: qs = qs.filter(Occupation_Title__icontains = self.q) return qs Here is my form: def miscuserinfo_view(request): misc_user_info = MiscUserInfoModel.objects.get(user = request.user.id) if request.method == 'POST': if form.is_valid(): obj = form.save(commit=False) # do something here with the form obj.save() return HttpResponseRedirect(reverse('registration:userprofile')) else: # Pre-populate with … -
Django - Populate integer (counter) field based on number of times referenced
I am new to Django and could not wrap my head around this problem. I have two models- Session and Circuit. The goal of these models is to document how many circuits a user completes in a session. Here are the models: (models.py) Class Circuit(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) _set = models.IntegerField(blank=False) class Session(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) circuits = models.ManyToManyField(Circuit) My goal is whenever the Circuit model is referenced inside of Session I want the _set field to self increment. Any one session will have have many circuits in it. So, when a user adds a instance of the Circuit model to the Session model, I want the _set variable to be updated to the order its added (basically +=1). If the user adds 3 circuits to their session, the _set field for each of those would automatically be updated to set 1, 2, and 3. Thanks in advanced for the help! It is greatly appreciated! -
Django social with apple oauth sends final redirect without cookies
We are trying to get apple oauth working for a web app with a django backend using django-social. The initial login request sets a sessionid cookie but the final auth/complete request doesn't send any of the browser's cookies. No errors in the console and our testing server uses ssl. The redirect_uri is correct, it's just missing it's cookies. Settings in django we have tried: SESSION_COOKIE_SECURE = False SESSION_COOKIE_SAMESITE = "Lax" SOCIAL_AUTH_APPLE_ID_CLIENT = '<our_website_name>' # Your client_id com.application.your, aka "Service ID" SOCIAL_AUTH_APPLE_ID_TEAM = '<our_id>' # Your Team ID, ie K2232113 SOCIAL_AUTH_APPLE_ID_KEY = values.SecretValue() # Your Key ID, ie Y2P99J3N81K SOCIAL_AUTH_APPLE_ID_SECRET_B64 = values.SecretValue() SOCIAL_AUTH_APPLE_ID_SCOPE = ['email', 'name'] SOCIAL_AUTH_APPLE_ID_EMAIL_AS_USERNAME = True # If you want to use email as username USE_X_FORWARDED_HOST = True SOCIAL_AUTH_REDIRECT_IS_HTTPS = True @property def SOCIAL_AUTH_APPLE_ID_SECRET(self): return base64.b64decode(self.SOCIAL_AUTH_APPLE_ID_SECRET_B64 AUTHENTICATION_BACKENDS = ( "rest_framework.authentication.TokenAuthentication", "social_core.backends.open_id.OpenIdAuth", # for Google authentication "social_core.backends.google.GoogleOpenId", # for Google authentication "social_core.backends.google.GoogleOAuth2", # for Google authentication "django.contrib.auth.backends.ModelBackend", 'social_core.backends.apple.AppleIdAuth', # Apple oauth ) This results in the following error: [04/May/2020 22:18:39] "GET /auth/login/apple-id/ HTTP/1.0" 302 0 Internal Server Error: /auth/complete/apple-id/ Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response … -
Python: Update a dictionary value within a list, within another list of dictionaries
Apologies for the confusing title. Essentially- I am looping through a series of model-objects extracting the date and marketname to prepare for a chart. Currently my method is as follows def getData(): projects = Opportunity.objects.all() markets = [] total = { 'marketname': "Total", 'data': [] } for x in projects: d = datetime.date(x.datecreated).strftime('%b-%Y') keytotaldate = "" keydate = "" market = x.market.all()[0].marketname # Check to see if market exists in list if not any(c.get('marketname', None) == market for c in markets): newobj = { 'marketname': market, 'data': [] } newdateobj = { 'date': d, 'count': 1 } newobj['data'].append(newdateobj) markets.append(newobj) keytotaldate = next((s for s in total['data'] if s['date'] == d), None) if keytotaldate is not None: keytotaldate['count'] += 1 else: newtotaldateobj = { 'date': d, 'count': 1 } total['data'].append(newtotaldateobj) else: keymarket = None keydate = None for n in markets: if n['marketname'] == market: keymarket = n break for t in markets: for m in t['data']: if m['date'] == d: m['count'] += 1 keydate = m break if keydate is None: newdateobj = { 'date': d, 'count': 1 } newobj['data'].append(newdateobj) keytotaldate = next((u for u in total['data'] if u['date'] == d), None) if keytotaldate is not None: keytotaldate['count'] += 1 … -
One-to-one based on condition
I have a model that looks like this: class Voting(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) choice = models.ForeignKey(Choice, on_delete=models.CASCADE) answered_at = models.DateTimeField(auto_now_add=True) It works as expected, however, a user is not supposed to be able to vote on the same question twice. In other words, the user shouldn't have the ability to vote twice on the same question: class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.CharField(max_length=120) class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.CharField(max_length=200) Is there a way to add this condition on a model level? -
Django start-up code (like initial caching) conflicts makemigrations. Operational Errors no such columns tables
First of all I'm not a fan of "do it the django way" thing. Instead of spending hours to learn the django way I prefer to utilize my basic programming knowledge when I develop an application. Background : Application I'm developing is a REST backend that stores localization values like language information. I want to take language information that is stored in the database and load it into memory once at startup and then serve that data from memory when a request comes. I created my model class Text(models.Model): language = models.CharField() key = models.CharField() text = models.CharField() Then ran python manage.py makemigrations and migrate commands as a regular step Then I jumped ahead and implemented my caching code and put it directly under admin.py(it could be urls.py it does not matter, it only needs to be run once) cached_languages = models.Text.objects.all() I go ahead and run my app and it is just working fine. Then I wanted to add a field to my Text model like class Text(models.Model): language = models.CharField() key = models.CharField() text = models.CharField() **dummy = models.CharField()** Then hit python manage.py makemigrations command and boom at line cached_languages = models.Text.objects.all() We get an error saying that … -
Django - How to display specific text after the discount is no longer valid
I'm working on a project and I want to know how to display the product 'name' and its 'price' when the validity of the 'discount_price' expires and as long as the 'discount_price' is valid, I would like to display the product 'name', 'price' and 'discount_price'. models.py: from django.db import models from datetime import datetime class Products(models.Model): name=models.CharField(max_length=60) photo = models.ImageField(upload_to='photos/', default='photos/none.png', null=True, blank=True) description=models.TextField() price=models.FloatField() discount_price = models.FloatField(blank=True, null=True) valid_from = models.DateTimeField(('Valid from'), default=datetime.now) valid_until = models.DateTimeField(('Valid until'), blank=True, null=True) stock=models.IntegerField(default=0) my template, index.html: {% extends "./base.html" %} {% load static %} {% block content %} <h3 style="text-align:center"> Product list: </h3> {% for product in products %} <div class="products"> <div class="item"> <table > {% if product.discount %} <tr><td> <a class="products" href ="{% url 'entry' produs.id %}"> {{products.name}} {{product.discount|cut:".0"}} {{product.price|cut:".0"}}</a> {% else %} <tr><td><a class="products" href ="{% url 'entry' product.id %}"> {{product.name}} {{product.price|cut:'.0'}} </a> {% endif %} </table> </div> </div> {% endfor %} {% endblock content %}