Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DataError at /freshleadaction value too long for type character varying(20)
I am working on a django web app. everything is working fine on my local machine and then pushed the code live on Heroku. but it doesn't work on the live server. it gives the following error when I try to post a .csv file: DataError at /freshleadaction value too long for type character varying(20) I have PostgreSQL database integrated. I deleted the migrations and then migrated the whole schema again. I think the problem is either PostgreSQL or heroku? I have two models which are as follows: class fresh_leads_model(models.Model): fname = models.CharField(max_length=250) lname = models.CharField(max_length=250) street_number = models.CharField(max_length=250) street_name = models.CharField(max_length=250) state = models.CharField(max_length=250) zip_code = models.CharField(max_length=250) bedrooms = models.CharField(max_length=250) legal_description = models.CharField(max_length=250) sq_ft = models.CharField(max_length=250) address = models.CharField(max_length=250) orign_ln_amt = models.CharField(max_length=250) prop_value = models.CharField(max_length=250) equity = models.CharField(max_length=250) email = models.CharField(max_length=250) cell = models.CharField(max_length=250) submitted_date = models.DateField(auto_now_add=True) updated_date = models.DateField(auto_now_add=True) deleted_date = models.DateField(auto_now_add=True) class cash_buyer_model(models.Model): fname = models.CharField(max_length=255) lname = models.CharField(max_length=255) email = models.CharField(max_length=255) city = models.CharField(max_length=255) state = models.CharField(max_length=255) submitted_date = models.DateField(auto_now_add=True) updated_date = models.DateField(auto_now_add=True) deleted_date = models.DateField(auto_now_add=True) my views.py function: def upload_fresh_leads(request): get_type = request.GET['type'] lst = [] if request.method == 'POST': leads = Fresh_leads_Form(request.POST, request.FILES) data = request.FILES.getlist('csv') # data = Fresh_leads_Form(request.FILES) # csv_file = request.GET['csv'] … -
Updating fields jQuery + Django
При обработке события JQuery данные не передаются в поле формы. На стороне Django формируется список типа ['RUS', 'USA']. На самой странице после выбора страны поле Activity становится пустым. Как это исправить. Template: {% extends "base.html" %} {% block content %} <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <section class="site_filter"> <div class="container-fluid"> <div class="row"> <div class="col-sm-2 col-2"> <div class="form-group"> <label for="country">Country</label> <select class="form-control" id="country"> {% for obj in country %} <option value='{{obj}}'>{{obj}}</option> {% endfor %} </select> </div> </div> <div class="col-sm-2 col-2"> <div class="form-group"> <label for="Activity">Activity</label> <select class="form-control" id="activity"> {% for obj in activity %} <option value='{{obj}}'>{{obj}}</option> {% endfor %} </select> </div> </div> </div> </div> </section> <script> /* jshint esversion: 6 */ $('#country').on('change', function(){ $.ajax({ type : "GET", url: "{% url 'info:get_cr_map' %}", data: { "country" : $(this).val(), "csrfmiddlewaretoken": '{{ csrf_token }}', "dataType": "json", }, success: function(response){ let activity_option = ''; $.each(response["activity"], function (a, b) { activity_option += `<option value=${b}>` + b + "</option>"; }); $("#activity").html(activity_option); }, error: function(response){ console.log(response); } }); }); </script> </body> </html> {% endblock %} views.py def cr_map(request): countries = Map.objects.exclude(country__isnull=True).\ exclude(country__exact='').order_by('country').values_list('country').distinct() countries = [i[0] for i in list(countries)] activity = Map.objects.exclude(activity__isnull=True).\ exclude(activity__exact='').order_by('activity').values_list('activity').distinct() activity = [i[0] for i in list(activity)] return render(request, "info/cr_map.html", {"country": countries, 'activity': activity}) … -
Logout redirect url can't find a view
So, here are my files: settings.py LOGOUT_REDIRECT_URL = 'refresh' views.py def about(request): return render(request, 'about.html', {}) def refresh(request): return HttpResponseRedirect(request.META.get("HTTP_REFERER")) The problem: If I set LOGOUT_REDIRECT_URL = 'about', it works fine. Also if I add the code from refresh view to about view, it works fine too. However, when I set LOGOUT_REDIRECT_URL = 'refresh' I'll get the error 'View name was wrong'. I don't understand why I get this error. -
Why does my time countdown return NaN when i format time in django template
I have been working on this app where i have a time countdown to event date, having a challenge working around the time format in django when i format the start datetime in django format{{ event.start|date:'D d M Y' }}" it return NaN in template, but when i format datetime like this "date: 2021-11-11T08:32:06+11:11" it works, I have search on here for a solution, but somehow the solution didn't work in my case. HTML #This works <div class="items-center space-x-2 text-center grid grid-cols-4" uk-countdown="date: 2021-11-11T08:32:06+11:11"> #but this does not work, It returns NaN <div class="items-center space-x-2 text-center grid grid-cols-4" uk-countdown="{{ event.start|date:'D d M Y' }}""> Here is my model for event class Event(models.Model): title = models.CharField(max_length=220) description = models.TextField(_('description'), blank=True) image = models.ImageField(upload_to='events/',blank=True) url = models.URLField(blank=True) country = models.CharField(max_length=200,blank=True) city = models.CharField(max_length=200, blank=True) start = models.DateTimeField(_('start'),db_index=True,default=datetime.now().replace(microsecond=0)) end = models.DateTimeField(_('end'), db_index=True,default=datetime.now().replace(microsecond=0)) creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='create') interested = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='interest') going = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="going") created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) service = models.CharField(_("service"), blank=True, max_length=200) My view for event def event_main(request,pk): event = get_object_or_404(Event, pk=pk) posts = Post.objects.filter(event=pk).prefetch_related('event_comment').order_by('-date_posted') related = Event.objects.filter(creator=request.user) liked = [i for i in Post.objects.all() \ if Like.objects.filter(username = request.user, post=i)] friend_list = FriendList.objects.get(user=request.user) friends = friend_list.friends.all() groups = … -
show fixed cell empty table in django template and then populate it with session items cell by cell
as I am trying to get the functionality of clicking an item from product catalogue populate that item at the fixed cells tables say a table of 4 cells - this is to achieve make-your-box kind of functionality with assorted items - the problem is first showing empty table of 4 cells and then populating the cells one by one on the click by a buyer. What I have achieved is to be able to keep clicking the items and they will appear at the top without any table structure. {% for product_id, item in b_data.items %} {% for i in item.numItems %} <div class="col-md-4 mb-4"> <div class="card" style="width: 18rem;"> <img src="/media/{{item.image}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{item.title}}</h5> <p class="card-text">{{product_id}} {{item.qty}}</p> <div class="card-footer"> <a href="#" class="btn btn-primary"><i class="bi bi-cart2"></i></a> </div> </div> </div> </div> {% endfor %} {% endfor %} above template works but now if I want that - say i have a box of 4 selected by buyer then - box of 4 will appear empty and then on the click of item fro the product-catalogue appearing below the fixed table of 4 - the session will keep the information of the clicked product and each time the above … -
In Django why the error "TypeError at / string indices must be integers"?
I am trying to learn how to save in Django part of a json content coming from a kraken api. Going through several examples here on stackoverflow i came up with this code: views.py from django.shortcuts import render from meal_app.models import Kraken import requests def get_krakens(request): all_krakens = {} url ='https://api.kraken.com/0/public/Assets' response = requests.get(url) data = response.json() for i in data: kraken_data = Kraken( name = i['altname'] ) kraken_data.save() all_krakens = Kraken.objects.all().order_by('-id') return render (request, 'krakens/kraken.html', { "all_krakens": all_krakens} ) When i try to run it appears: How can i solve this error? My json is visible in my console but i cannot access the value 'altname'. Your help would be really appreciated. /Users/davidmoreira/Documents/crypto/djangokrakenapi/meal_project/meal_app/views.py, line 14, in get_krakens name = i['altname'] -
Recieving SQLDecodeError for djongo migration
I'm trying to use djongo module for mongodb support with django, after I made migration and trying to apply it. But after trying to migrate I'm receiving: djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: None FAILED SQL: ('SELECT "openwisp_users_organizationuser"."created", "openwisp_users_organizationuser"."modified", "openwi sp_users_organizationuser"."is_admin", "openwisp_users_organizationuser"."id", "openwisp_users_organizationuser"."organization_ id", "openwisp_users_organizationuser"."user_id" FROM "openwisp_users_organizationuser" WHERE ("openwisp_users_organizationuser "."is_admin" AND "openwisp_users_organizationuser"."organization_id" = %(0)s) ORDER BY "openwisp_users_organizationuser"."creat ed" ASC LIMIT 1',) Params: ((UUID('ba052935-7bd6-4262-9860-593d33f1934c'),),) Version: 1.3.6 Also for createsuperuser I recieve: djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: None FAILED SQL: ('SELECT COUNT(*) AS "__count" FROM "account_emailaddress" WHERE ("account_emailaddress"."primary" AND "acc ount_emailaddress"."user_id" = %(0)s)',) Params: ((UUID('d4d66e84-4a91-49eb-ad86-d35ad8556e41'),),) Version: 1.3.6 Versions used: Django: 3.11.2 Djongo: 1.3.6 sqlparser: 0.2.4 Is there anyway to bypass that and make the migration work? -
Django Template tag in {% if %} block does not show
I'm making a bulletin board with Django. How can I express it with the letters I want instead of the type number? my bulletin board HTML template(board.html) {% for p in postlist %} <tr> <td> {% if p.p_type == '1' %} 'cloud' {% elif p.p_type == '2' %} 'wind' {% endif %} </td> </tr> {% endfor %} output (EMPTY) expected cloud wind Vies.py def board(request, p_type=None): current_type = None p_types = PostType.objects.all() postlist = Post.objects.all() page = request.GET.get('page', '1') if p_type: current_type = get_object_or_404(PostType, p_type=p_type) postlist = postlist.filter(p_type=current_type) paginator = Paginator(postlist, 10) # Showing 20 posts. page_obj = paginator.get_page(page) return render(request, 'board/board.html', {'current_type':current_type, 'p_types': p_types, 'postlist': page_obj}) -
Get list of the functions that used a decorator (in Django)
I have a Django project that I used a decorator for some functions in project (in different apps) Now I want to get list of all functions that used the decorator (I want to get this list when project starts [in app ready()], I want to call those functions. Also I wrote the decorator, I can change it if needed. How can I do it? -
pass variable to quotation in javascript
I have a web app, backend using Django, frontend using HTML5. I want to pass a variable from bootstrap table to the quotation in javascript. <th class ='Format_issued' data-field="book.publisher" data-formatter="renderFormat">Material Format</th> <script> function renderFormat(value) { return '<select style="width: 7em" name="Material_format" id="Material_format" >\n' + ' <option value="">--Select--</option>\n' + ' <option value="eText" {% if ' + value + ' == "eText" %} selected="selected" {% endif %}>eText</option>\n' + ' <option value="No Material" {% if value == "No Material" %} selected="selected" {% endif %}>No Material</option>\n' + ' ' </select>' } </script> 'value' is the variable that I want to pass. But I have tried several method: 1 . use ' + value + ': ' <option value="eText" {% if ' + value + ' == "eText" %} selected="selected" {% endif %}>eText</option>\n' 2 . use value in my js quotation directly: ' <option value="No Material" {% if value == "No Material" %} selected="selected" {% endif %}>No Material</option>\n' all could not pass the value variable. How could I pass 'value'? -
how django session distinguish user?
Below is my code. def sessfun(request) : num_visits = request.session.get('num_visits', 0) + 1 request.session['num_visits'] = num_visits if num_visits > 4 : del(request.session['num_visits']) resp = HttpResponse('view count='+str(num_visits)) return resp The code use request.session. It works well. When I visit in chrome and Firefox, it makes another session. But my question is session is saved in server, but how can request get session?? And How session distinguish user without any session id or something... -
Does multilingual query support on Django?
I have created a blog website where users can POST and save text in a specific regional language (Malayalam). Can I query the database as we used to do in English language database ? or will database consider the regional language as special character. I am using Django with sqlite and in future I may use PostgreSQL. -
Heroku Django App deploy missing some CSS
Below are the screenshot of my portfolio made using Django , and hosted in local host. And this is the link of my portfolio hosted on heroku : bifolio.herokuapp.com I dont know what happened to the css of navbar and other containers when hosted on heroku. THey works totally fine on local host! Need some help to make it working on heroku.[portfrolio hosted on local host Portfolio Portfolio on local Host(image) Portfolio on Local Host(image) -
Django real time jobs
How Can I create real time actions in python / django? for more info: Some user add some thing to database also other user add same one too (not same as they are but they have similar property) at same time (and all times) program should being check if they are objects with similar property {if they are not same check both of them in other time with all other objects that may be added/edited on database} these actions should be in real time or at last by few minuts appart. for example: for every(2min): do_job() or while True: do_job() if i use second one program will stop. -
'Access-Control-Allow-Origin' header is not published from django project
I access the django project on Enginx-unit from another server ReatJS I have error like this below. Access to XMLHttpRequest at 'https://api.example.net:8008/upload/' from origin 'https://example.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I tested curl -H "origin example.net" --verbose https://api.example.net:8008 it shows log. > GET / HTTP/1.1 > Host: api.example.net:8008 > User-Agent: curl/7.71.1 > Accept: */* > * TLSv1.3 (IN), TLS handshake, Newsession Ticket (4): * TLSv1.3 (IN), TLS handshake, Newsession Ticket (4): * old SSL session ID is stale, removing * Mark bundle as not supporting multiuse < HTTP/1.1 200 OK < Content-Type: text/html; charset=utf-8 < X-Frame-Options: DENY < Content-Length: 402 < X-Content-Type-Options: nosniff < Referrer-Policy: same-origin < Vary: Origin < Server: Unit/1.25.0 < Date: Sun, 07 Nov 2021 09:44:43 GMT < I guess it doens't include Access-Control-Allow-Origin header. I already setup django-cors-headers and in my settings.py CORS_ALLOWED_ORIGINS = [ 'https://example.net' ] CORS_ALLOW_ALL_ORIGINS = True Is there anything I can check?? -
Best model field for product details? In django
I am making an ecommerce website in django. I am facing with a problem. Can you tell me what is the best way or model field for product details??? please Help! Thank in advance -
How to count model objects in Django
I'm trying to make a student management website with Django. Now I want to count how many students are in a single grade and display the number in my website. How can I do that? My model:enter image description here -
Error when trying to deploy Django app to Heroku - Conflicting Dependencies
This is the error i get when trying to push, everything was working fine a week ago, I could deploy with no problems. Now when I try to deploy I always get this error beacuse I can't satisfy both python-dateutil==2.8 (needed by the app) and python-dateutl==1.5 (needed by heroku). No clue why this started happening. (Updated heroku globally but nothing changed). There is a wrapper Heroku3 but I can't seem to use it to deploy, when i install it in the env, heroku3 command doesn't exist and its not available on npm, so all I can do is write python code with it. Would really appreciate if someone knew how to resolve this problem. git push heroku master Enumerating objects: 401, done. Counting objects: 100% (401/401), done. Delta compression using up to 16 threads Compressing objects: 100% (321/321), done. Writing objects: 100% (386/386), 226.01 KiB | 4.43 MiB/s, done. Total 386 (delta 39), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: heroku/python remote: -----> Python app detected remote: -----> No Python version was specified. Using the same version as the last build: … -
my question is about TemplateDoesNotExist at /cms_wizard/create/ INHERIT
here is the issue Here is one solution I tried: "os.path.join(SETTINGS_PATH, 'templates'),"(I substituted SETTINGS_PATH with BASE_DIR, and the setting.py terminated without any errors but still the problem isn't solved. how am I supposed to inherit the template, it has to be in a folder which I should make? also, the directory of cms_wizard/create isn't making sense as shown in the image above how do I fix it. Here is my setting.py ``` TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'sekizai.context_processors.sekizai', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'cms.context_processors.cms_settings', 'django.template.context_processors.i18n', ], }, }, ] ``` -
Django ORM, Sum column values through query
I have a table with the following values: user amount date John 10 2017-07-01 John 20 2019-07-01 John 30 2020-09-01 John 40 2021-11-01 ... ... ... Dan -20 2019-02-01 Dan -30 2020-04-01 Dan -40 2021-06-01 The input of the function is a range of date, for example, as follows: date_start = '2019-01-01' date_end = '2021-11-07' Expected output: For all users, for each date in this range of date, I want to return the sum of the amounts, from the current date to all previous dates like this: user amount date John 30 (10+20) 2019-07-01 John 60 (10+20+30) 2020-09-01 John 100 (10+20+30+40) 2021-11-01 ... ... ... Dan -20 2019-02-01 Dan -50 (-20-30) 2020-04-01 Dan -90 (-20-30-40) 2021-06-01 My efforts def get_sum_amount(self, date_start=None, date_end=None): date_detail = {} # Minimum date if date_start: date_detail['date__gt'] = date_start # Maximum date if date_end: date_detail['date__lt'] = date_end detail = Financial.objects.filter(Q(**date_detail)) \ .values('user') \ .annotate(sum_amount=Coalesce(Sum(F('amount')), Value(0))) but no result. -
Django Form does not display, gives error that it is unable to match urls
With Django, I am trying to display a form to edit content on a page. However I run into the following error when trying to visit the editpage view NoReverseMatch at /editpage/CSS/ Reverse for 'editpage' with keyword arguments '{'topic': ''}' not found. 1 pattern(s) tried: ['editpage\/(?P[^/]+)\/$'] Where "CSS" here is an example pulled from the link address via str:topic in urls.py. I think the issue is with my form action in editpage.html, where I reference the editpage url and I have tried numerous combinations but am unable to get it to display. Removing the form allows the link to display with no error. Any help is much appreciated. urls.py from django.urls import path from . import views urlpatterns = [ path("editpage/<str:topic>/", views.editpage, name="editpage"), ] editpage.html {% extends "encyclopedia/layout.html" %} {% block title %} Edit Page {% endblock %} {% block body %} <h1>Edit page</h1> <form action="{% url 'editpage' topic=topic %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="submit"> </form> {% endblock %} views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django import forms from . import util class EditPageForm(forms.Form): title = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'topic', 'class': 'form-control'})) article = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'Existing article', 'class': … -
Django+Angular 2 in one port
I am new in python and django. I want that my django project work with angular 2 in one port (for example localhost:8080). I visit many page, but I don't find project django that's work with angular 2 in one port. Please help me find simple project django that's work with angular 2 in one port. -
how to use foreign key to submit a form
I have an address model like this: class PrevAddress(models.Model): id = models.AutoField(primary_key=True) user = ForeignKey(User, on_delete=models.CASCADE) address_province = models.CharField(max_length=32, null=True) address_city = models.CharField(max_length=32, null=True) address = models.CharField(max_length=128, null=True) and a mapinfo models which is connected to it using a foreign key relation: class MapInfo(models.Model): id = models.AutoField(primary_key=True) user = ForeignKey(User, on_delete=models.CASCADE) prevAddress = models.ForeignKey(PrevAddress, on_delete=models.CASCADE) location = LocationField( map_attrs={ "style": "mapbox://styles/mapbox/streets-v11", "center": (51.3890, 35.6892), }, null=True) lat = models.FloatField(blank=True, null=True) long = models.FloatField(blank=True, null=True) and these are the views I wrote for the mapinfo: class MapInfoView(CreateView): template_name = 'reg/map.html' model = MapInfo fields = ['location'] success_url = '/profile/contact/prev-addresses' def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) the issue is that each mapinfo is related to a prevaddress object and when I want to add a new mapinfo, it needs a prevaddress object id for the connection and gives me this error: NOT NULL constraint failed: reg_mapinfo.prevAddress_id. how do I add something like this to the views ... prevaddress.id = mapinfo.id ? I can choose a prevaddress object for the mapinfo from the admin page but users obviously dont have any access to it. please help me -
How to create relationships in Django models
I am not sure how I am suppose to represent my relationships correctly. Let's say I have 2 tables User and Post. For this example I will mix and match relationships between these 2 tables. relationships 1st case A user has zero-to-many posts and a post belongs to one user. I looked at the Many-to-One relationships on Django documentation and decided I can maybe model this by doing the following... class User(models.Model): pass class Post(models.Model): user = models.ForeignKey(User) I read it as a User can have many post (zero or more). A Post belongs to one (and only one) user. 2nd case A User has one-to-many posts and a Post belongs to one user This is almost identical to the first case but the difference here is that a User has one-to-many post vs. zero-to-many. I'm not sure how to model this. How do I tell my model User to own at least 1 or more posts but not zero. I may add more of the other relationships to this question if I need further clarification but for now would really like to know how this is suppose to work. The only thing I can think of is having a … -
how to calculate due date in django based on existing date
How do i calculate the due date from this model based on the date renewed. i want the due date to be 5 years after the date Renewed. I'm pretty stuck. I need help def get_deadline(): return dateRenewed() + timedelta(days=1825) class Trademark(models.Model): trademarkName = models.CharField(max_length=100) trademarkClass = models.CharField(max_length=100) dateCreated = models.DateTimeField(default=timezone.now) acknowledgeDoc = models.FileField(upload_to='acknowledge_docs', default='default.jpg') acceptanceDoc = models.FileField(upload_to='acceptance_docs/', default='default.jpg') cert = models.FileField(upload_to='trademark_cert/', default='default.jpg') renewalDoc = models.FileField(upload_to='renewalDocs', default='default.jpg') dateRenewed = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True) duedate = models.DateTimeField(default=get_deadline) uploadedBy = models.ForeignKey(User, on_delete=models.RESTRICT) ```