Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django slugfield changes unicode characters when saving and causes reverse no match error
I'm trying to create Unicode slugs with Django. The problem arises when it tries to save and resolve URLs with said slugs with Unicode characters in it. When I checked, Django seems to modify the characters when SlugField is used. This is my models.py: class Post(models.Model): title = models.CharField() slug = models.SlugField(unique=True, blank=True, allow_unicode=True) And I use slugify(slug, allow_unicode=True) to auto-generate slug from title. So to test this I used தமிழ் as title. Instead of a successful redirect to the URL /cats/test-cat/posts/தமிழ்/ Django showed NoReverseMatch exception with the following message. Reverse for 'post-detail' with arguments '('test-cat', 'zw93tz-தமழ')' not found. 1 pattern(s) tried: ['cats/(?P<cat_slug>[-a-zA-Z0-9_]+)/posts/(?P<post_slug>[-a-zA-Z0-9_]+)/$'] When I check the database, the title field has the right characters தமிழ் but the slug field has the modified characters தமழ. When I looked up for solutions, I found a workaround to use <str> instead of <slug> in urls.py. Why is this happening with <slug> and how to fix this? -
Send the logged user Profile Model to a CreateView form
what I am trying to accomplish is to send the "requester" model, using the logged-in user to a form ... Mainly the problem that I have is that the views.py "class CreateOrderView(CreateView)" does not have a parameter "request" , so I cannot get the request.user, and therefore get requester_obj and automatically select this requester_obj in the form field "requester", when entering this page. models.py Order: DEFAULT_REQUESTER_ID= 1 requester = models.ForeignKey(Profile, on_delete=models.CASCADE, default=DEFAULT_REQUESTER_ID, verbose_name="usuario") forms.py: class OrderCreateForm(BaseForm, forms.ModelForm): date = forms.DateField(label="Fecha" , widget=forms.DateInput(attrs={'type': 'date'})) class Meta: model = Order fields = ['requester','title' , 'date', ] views.py: @method_decorator(staff_member_required, name='dispatch') class CreateOrderView(CreateView): template_name = 'form.html' form_class = OrderCreateForm model = Order def get_success_url(self): self.new_object.refresh_from_db() return reverse('update_order', kwargs={'pk': self.new_object.id}) def form_valid(self, form): object = form.save() object.refresh_from_db() self.new_object = object return super().form_valid(form) I get the requester like this: @login_required def create(request): #return render(request, 'app_client/create.html') if request.method == 'POST': if request.POST['value'] and request.POST['products']: logged_user = request.user user_obj = get_object_or_404(User, username=logged_user) requestor_obj = get_object_or_404(Profile, user=user_obj) .... -
Why we can't host django app like laravel in apache server? [closed]
Got a question and curious if it's possible to do ... I configured apache server and it runs .py files and print html to request while visiting localhost JUSt like how .php file sendback response . we can easily copy laravel app in htdocs and it starts from index.php in laravel framework BUT things get messy with django , you have production server comes with django framework itself, and you need to connect with with some extension to apache. why we can't do the same with python django. I can write a semi framework inside htdocs with python that works like laravel and app starts from index.py etc etc ... just like laravel, Is this kind of thing related to framework itself or it is something technical and related to language itself ? -
Is this the right format of data send over ajax
This is how my data is going via ajax request. Is this is the right format? connection: 80 trans_data[0][name]: conditional_transformation trans_data[0][display_name]: Conditional Transformation trans_data[0][trans_text]: statement trans_data[0][trans_type]: condition Because my back-end system is looking for the keyword trans_data. But due to this structure the back-end is not able to process API. -
Get Serialize data of more than 1 models
i have 3 model class Camera(models.Model): CameraId = models.AutoField(primary_key=True, db_column='CameraId') CameraName = models.CharField(max_length=50) class DeviceType(models.Model): DeviceTypeId = models.AutoField(primary_key=True, db_column='DeviceTypeId') DeviceType = models.CharField(max_length=50) class Device(models.Model): DeviceId = models.AutoField(primary_key=True, db_column='DeviceId') DeviceName = models.CharField(max_length=50) CameraId = models.ForeignKey(Camera, on_delete=models.CASCADE, db_column='CameraId', related_name='cameras') DeviceTypeId = models.ForeignKey(DeviceType, on_delete=models.CASCADE, db_column='DeviceTypeId') i want result of Device serialize JSON data , related to Device { 'DeviceId' : DeviceId , 'DeviceName' : DeviceName , 'CameraId' : CameraId, 'CameraName': CameraName , 'DeviceTypeId' :DeviceTypeId , 'DeviceType' :DeviceType } How can i do it ? -
Django MaterializeCSS - working, but not sure the right way to set css and js?
I'm working on Django project with Materializecss design - Built a page with floating button for example. It's corrently working but I'm trying to understand better why it's actually working. I started using exactly the template from the website: https://materializecss.com/getting-started.html and updated from the CDN part in the page: <!--Import materialize.css--> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> And added at the bottom: <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> The floating button didn't work - After reading some posts, I use a suggestion to add the below, and it worked: Why the updated version of the files is not working? What's the right way to install it for production? Thanks a lot! The full HTML with the 'ADDED PART THAT MAKE IT WORK': <!DOCTYPE html> <html> <head> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!--Import materialize.css--> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <!--Let browser know website is optimized for mobile--> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> </head> <body> <div class="fixed-action-btn"> <a href="#" class="btn-floating btn-large waves-effect waves-light red"><i class="material-icons">add</i></a> <ul> <li><a href="#" class="btn-floating btn-large blue"> <i class="large material-icons">filter_drama</i></a></li> <li><a href="#" class="btn-floating btn-large green"> <i class="large material-icons">insert_chart</i></a></li> </li> </ul> </div> <!--JavaScript at end of body for optimized loading--> <script type="text/javascript" src="js/materialize.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> ADDED PART THAT MAKE IT WORK: <!--JavaScript at end of body for … -
Django channels live chat save sent messages
So I have a Django app in which I used channels to implement live chat. My consumer looks like this: import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] username = self.scope["user"] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message, 'user': username.username } ) # Receive message from room group def chat_message(self, event): message = event['message'] user=event['user'] print(user) # Send message to WebSocket self.send(text_data=json.dumps({ 'message': message, 'user':user })) So I am looking for a way to save the sent messages (because currently they are lost on refresh). I have created a Messages model that has a CharField for the message text. I think I can save new messages if I do this in my chat_message function: new_message=Messages(text=message) new_nessage.save() My question is how do I preload the last 10 messages whenever a user gets connected to the chat? -
Django 301 Redirect configuration from old websites
I'm building a website builder in Django and customers are moving their old website to my service. I'm wondering how I could set up 301 redirects the right way so they dont lose backlinks / traffic from existing external links. My url conf is: domain.com/post-name Their old conf could be: domain.com/YYYY/MM/DD/post-name or domain.com/blog/post-name (and post-name might not be the same from old and new) So ideally, I'd like to build a scalable way for them to set up 301 redirects from a variety of different URL patterns. Would I create a catchall URL conf (which allows slashes) and check that first? Or check that if nothing was found at domain.com/post-name? I could add an old_url field to the Post model and check that after a post isn't found. -
Django pagination returning %20 whitespace in URL
I cannot figure out why Django pagination sometimes adds whitespace (%20) to the URL: https://example.com/accounts/?page=2%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20&q=%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20&ordering=-date_joined It happens if I click the Next or a specific page button so I assume it has to do with the way the pagination is written. More spoecifically I think it has to do with request.GET.items. Do context managers use request.GET.items? pagination: {% if page_obj.has_next %} <a class="btn btn-default btn-inactive mb-4 m-1" href="?page={{ page_obj.next_page_number }}{% for key, value in request.GET.items %} {% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">Next</a> <a class="btn btn-default btn-inactive mb-4 m-1" href="?page={{ page_obj.paginator.num_pages }}{% for key, value in request.GET.items %} {% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">Last</a> {% endif %} view: class AccountStatusListView(AccountSearchMixin, ListView): model = Employee template_name = 'employees/account_list.html' paginate_by = 15 def get_ordering(self, *args, **kwargs): ordering = self.request.GET.get('ordering', '-is_active') return ordering def get_queryset(self, *args, **kwargs): queryset = super(AccountStatusListView, self).get_queryset() queryset = queryset.filter(Q( supervisor__exact=self.request.user)) | queryset.filter(Q( supervisor__isnull=False)) | queryset.filter(Q( is_active__exact=False)) ordering = self.get_ordering() if ordering and isinstance(ordering, str): ordering = (ordering,) queryset = queryset.order_by(*ordering) return queryset Anybody have any idea what is going on here? -
GET without unrequired fields in Django
Hope the title makes sense. I want to be able to search the Yelp API using a location (required) and a name (not required). Right now you are allowed to leave the name field blank but it will still use that in a search, therefore returning nothing no matter what. base.html <form action="{% url 'venue_list' %}"> <!-- NOT required --> {% render_field search_form.search_name.label %}: {% render_field search_form.search_name class="form-control" %} <!-- required --> {% render_field search_form.search_location.label %}: {% render_field search_form.search_location class="form-control" %} <input type='submit' value='SEARCH'> </form> yelp_api.py def get_name(location, term=None): url = 'https://api.yelp.com/v3/businesses/search' if term != None: params = { 'location': f'{location}', 'term': f'{term}' } else: params = { 'location': f'{location}' } headers = {'Authorization': f'Bearer {YELP_API_KEY}'} *etc etc* forms.py class SearchForm(forms.Form): search_name = forms.CharField(required=False, label='Name') search_location = forms.CharField(required=True, label='City, State, or Zip Code') views_venues.py def venue_list(request): search_location = request.GET.get('zip_code') search_name = request.GET.get('name') if not Venue.objects.filter(zip_code=search_location).exists(): venues = yelp_api.get_name(search_location) venues = Venue.objects.filter(zip_code=search_location).order_by('name') else: venues = Venue.objects.filter(zip_code=search_location).order_by('name') return render(request, 'restroom_rater/venue_list.html', { 'venues': venues, 'search_location': search_location}) views_venues.py i know is only set up to search for the location because that's how I originally had it set up. Getting stuck trying to do just location or location AND name. Let me know if there's … -
How Can make PyCharm's autocomplete work on django?
I am using pycharm community , I make test project on django and in template I make degree.html file. I have the following code in degree.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>welcome to degree site of {{student_id}}</title> </head> <body> {%for item in degree%} <h4> {{item.student_dgree}} </h4> <h4> {{item.student_id}} </h4> {%endfor%} </body> </html> I can't complete instruction like "for , endfor , .. etc" I install django from cmd and from pycharm's terminal too using pip. and from File -> Settings -> Project Interpreter I add django Package and install it help please ! -
Django upload image for current user for him cars
I am trying to make a uploading form for images with a choice of a car in the field, but in the field there should be only cars of the current dealer I have the following models: class Photo(BaseDateAuditModel): image = models.ImageField(upload_to='photos/') position = models.SmallIntegerField(default=1, validators=[MinValueValidator(limit_value=1)]) car = models.ForeignKey('cars.Car', on_delete=models.CASCADE, related_name='photos') class Dealer(User): city = models.ForeignKey('City', on_delete=models.SET_NULL, null=True, blank=False) class Car(BaseDateAuditModel): properties = models.ManyToManyField(Property) objects = CarManager.from_queryset(CarQuerySet)() views = models.PositiveIntegerField(default=0, editable=False) slug = models.SlugField(max_length=75) number = models.CharField(max_length=16, unique=True) dealer = models.ForeignKey("dealers.Dealer", on_delete=models.CASCADE, related_name='cars', null=True, blank=False) model = models.ForeignKey('CarModel', on_delete=models.SET_NULL, null=True, blank=False) color = models.ForeignKey('Color', on_delete=models.SET_NULL, null=True, blank=False) Form for upload images: class ImageForm(forms.ModelForm): class Meta: model = Photo fields = ['image', 'car'] widgets = { 'image': forms.ClearableFileInput(attrs={'multiple': True}), } View: class UpdateImageView(FormView): model = Photo form_class = ImageForm template_name = 'image-update.html' def get_success_url(self): return reverse('cars:cars-list') def form_valid(self, form): form.save() return super().form_valid(form) # 1st way, get list all car, not only for current user def get_queryset(self): ''' return a list of cars of the current user for example: my current dealer(user) have one car and this method return: Car.objects.filter(id__in=car_list) == <CarQuerySet [<Car: Audi >]> ''' user = self.request.user car_list = Dealer.objects.filter(username=user).values_list('cars', flat=True) return Car.objects.filter(id__in=car_list) # # def post(self, request, *args, **kwargs): … -
How to play an audio file through http response in Django
I want to know how to play an audio file in the browser How to play an audio file in the browser? -
Is it possible to target the single object's attributes among the objects QuerySet in Django ListView?
I want to get the attributes just for a single object in the object_list, but there is no way for me to access it as the contexts were only objects_list. I would like to access the attribute/field in the Post model(eg. Author/likes) in views.py in order to set an if statements and return the context e.g.: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) post = context['post'] if post.likes.filter(id=self.request.user.id).exists(): context['is_liked'] = True return context -
Serializing a block of text django rest-framework and displaying paragraphs with react
I am creating a blog and using djangorestframework as my backend and react for my frontend. When I serialize my data, I lose the formatting for my blog enteries (which are written in paragraphs). Is there a way to fix this. So: Blog Post This is my blog post, and this is my formatting. My second paragraph. becomes. [{ "title": "blog post", content: "This is my blog post, and this is my formatting My second paragraph." } ] When i pass it through my react it remains This is my blog post, and this is my formatting My second paragraph. -
Variables are not rendenring [DJANGO]
I m making a blog site.And I have been trying to render drom a model RecentPosts objects rpost1 ..etc in my template blogs-base.html which is my blogs details page. But it is not rendenring. Any solution?? views.py from django.http import HttpResponse from django.shortcuts import render from blog.models import Post from django.contrib import messages from django.views.generic import ListView , DetailView from .models import Post , RecentPosts , Comment ,Contact ,Populars from datetime import datetime from .forms import CommentForm def index(request): return render(request, 'index.html') def path(request): return render(request, 'blog.html') def cv(request): return render(request, 'cv.html') class HomeView(ListView): model = Post template_name = 'listview.html' class ArticleDetailView(DetailView): model = Post template_name = 'base2.html' def rpost(request): template_name = "blogs-base.html" rpost = RecentPosts.objects.all() context = {'rpost' : 'rpost'} return render(request ,template_name,context) This is url portion. urls.py from django.urls import path from . import views from .views import HomeView ,ArticleDetailView ,contact ,Comment_page,popular urlpatterns = [ path('', views.index, name='index'), path('index.html', views.index, name='index'), path('cv.html', views.cv, name='cv'), path('blogs/',views.HomeView.as_view(),name="blogs"), path('blogs/<slug:slug>',ArticleDetailView.as_view(),name='base2'), path('contact/', views.contact, name='contact'), path('contact.html/', views.contact, name='contact'), path('comment.html/', views.Comment_page, name='comment'), path('popular', views.popular, name='popular'), ] This is the model portion. models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse from django.utils.timezone import now # Create your models here. class Post(models.Model): … -
Django, check if an object present in query set using exists() method
I have a below model, class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) head = models.CharField(max_length=255) authors = models.ManyToManyField(Author) I have created an object in Entry model, when I try to check if there is any objects in Entry model it shows error as attached image -
bash: /python/run/venv/bin/activate: No such file or directory
I'm trying to deploy my django app through AWS elastic beanstalk, & I've been running into an issue for the past 2 days which i've narrowed down more. A command in the deployment process is failing, this command is as follows: container_commands: 01_migrate: command: "python3 manage.py migrate" leader_only: true The section of the AWS EB console logs that tell me this refer me to cfn-init.log, checking this tells me the same thing. In cfn-init-cmd.log however, i see this 2020-06-19 18:24:24,753 P5019 [INFO] Command 01_migrate 2020-06-19 18:24:24,771 P5019 [INFO] -----------------------Command Output----------------------- 2020-06-19 18:24:24,771 P5019 [INFO] Traceback (most recent call last): 2020-06-19 18:24:24,771 P5019 [INFO] File "manage.py", line 10, in main 2020-06-19 18:24:24,771 P5019 [INFO] from django.core.management import execute_from_command_line 2020-06-19 18:24:24,771 P5019 [INFO] ModuleNotFoundError: No module named 'django' 2020-06-19 18:24:24,771 P5019 [INFO] 2020-06-19 18:24:24,771 P5019 [INFO] The above exception was the direct cause of the following exception: 2020-06-19 18:24:24,771 P5019 [INFO] 2020-06-19 18:24:24,772 P5019 [INFO] Traceback (most recent call last): 2020-06-19 18:24:24,772 P5019 [INFO] File "manage.py", line 21, in <module> 2020-06-19 18:24:24,772 P5019 [INFO] main() 2020-06-19 18:24:24,772 P5019 [INFO] File "manage.py", line 16, in main 2020-06-19 18:24:24,772 P5019 [INFO] ) from exc 2020-06-19 18:24:24,772 P5019 [INFO] ImportError: Couldn't import Django. Are you … -
Iterate json response data to loop in django
$(document).ready(function(){ $("button").click(function(){ $.ajax( { type:"GET", url: "{% url 'updatetable' %}", data:{ year_id :1}, success: function( data ) { console.log(data) ; $("#loadtable").html(data); } }); }) ; }); <div class="table-responsive" > <table class="table table-striped"> <thead class="thead-dark"> <tr> <th scope="col">S.N</th> <th scope="col">Name</th> <th scope="col">Post</th> </tr> </thead> <tbody id="loadtable" > {%for dt in data %} <tr> <th scope="row">{{ forloop.counter }}</th> <td>{{dt.name}}</td> <td>{{dt.post}}</td> </tr> {%endfor%} </tbody> </table> -
Python list of dicts not converting properly in javascript GET handler
i am sending data from views.py in Javascript Ajax function, but it was not converting string to dict here is my code //////////////////////////////////// views.py def SortShop(request,shortby): items = Item.objects.order_by(shortby) item_list = [] for item in items: item_list.append({'name':item.item_name,'title':item.item_titile, 'pricse':item.item_FrashPricse,'dicsount':item.item_Discount_pricse, 'image':item.item_image}) return HttpResponse([item_list]) ///////////////////////////////////////////ajax function $('#sorting').on('change', function(e) { selected_value = this.value $.ajax({ type: 'GET', url: '/shopsorting/' + selected_value, // data: formData, encode: true, success: function(data) { y = JSON.stringify(data) x = JSON.parse(y) console.log(x) } }); }); }); ////////////////////////////Result's is [{'name': 'Shoulder Bag', 'title': 'Boys Shoulder Bag (Yellow )', 'pricse': 15.99, 'dicsount': 0.0, 'image': <ImageFieldFile: man-1.jpg>}, {'name': 'Sweeter', 'title': 'Cotton Sweeter', 'pricse': 19.9, 'dicsount': 0.0, 'image': <ImageFieldFile: product-6.jpg>}, {'name': 'Shirt', 'title': 'Full Sleeves Shirt', 'pricse': 20.99, 'dicsount': 12.99, 'image': <ImageFieldFile: man-4.jpg>}, {'name': 'Jacket', 'title': 'Jackson Jacket', 'pricse': 20.25, 'dicsount': 0.0, 'image': <ImageFieldFile: man-3.jpg>}, {'name': 'Yellow Shoes', 'title': 'Leopard Shoes', 'pricse': 29.99, 'dicsount': 25.99, 'image': <ImageFieldFile: man-2.jpg>}, {'name': 'Bag', 'title': 'Mini Cary Bag', 'pricse': 14.99, 'dicsount': 12.99, 'image': <ImageFieldFile: women-4.jpg>}, {'name': 'Coat', 'title': 'Overcoat (Gray)', 'pricse': 17.7, 'dicsount': 0.0, 'image': <ImageFieldFile: product-3.jpg>}, {'name': 'TOWEL', 'title': 'Pure Pineapple', 'pricse': 19.9, 'dicsount': 0.0, 'image': <ImageFieldFile: women-2.jpg>}, {'name': 'Coat', 'title': 'Pure Pineapple', 'pricse': 17.9, 'dicsount': 11.9, 'image': <ImageFieldFile: product-1.jpg>}, {'name': 'TOWEL', 'title': 'Pure Pineapple (White)', 'pricse': 17.9, … -
ModuleNotFoundError: Apache, Bitnami, Django app failing to import from virtual env
I'm attempting to get a very simple Django app deployed on an AWS Lightsail instance for the first time. I provisioned an AWS Apache instance set up with bitnami and django, and followed the tutorial without a virtual environment successfully but have since spent hours attempting to add my own project with a virtual environment. Most things seem set up correctly and I start Apache fine, only to navigate by browser to my url and find in the error logs a ModuleNotFoundError: No module named 'requests' error. This is the first import of any pip-installed module in my code and so suggests my virtual env has not made it into my PYTHONPATH. I just found a solution by hardcoding the path to my site-packages and appending it using sys.path.append(...) in my wsgi.py file, but I don't think this is the correct way to configure mod_wsgi with a django app and am worried it will lead to unexpected problems later. All django projects on the server are located at /opt/bitnami/apps/django/django-projects/. Following the tutorial, this directory contained projects "Project" and "tutorial". To separate my requirements.txt file and virtual environment env frome these projects, I decided to locate my project (a very simple … -
How do I add a polymorphic class in Django?
I am trying to make an application for a restaurant in django; I have to create a menu for different types of items, and all of those different types of items have to essentially be a product, so that I can add that product to a user's corresponding cart. Here are my menu items: from django.db import models from django.contrib.auth.models import User class Product(models.Model): price = models.DecimalField(decimal_places=2, max_digits=10) class Pizza(Product): pizzatype = models.CharField(max_length=15) extras = models.TextField(max_length=50) size = models.CharField(max_length=10) class Subs(Product): name = models.TextField(max_length=64) size = models.CharField(max_length=10) class DinnerPlatters(Product): name = models.TextField(max_length=64) size = models.CharField(max_length=10) class Pasta(Product): name = models.TextField(max_length=64) class Salads(Product): name = models.TextField(max_length=64) As can be seen, I tried deriving the models for different types of menu items from a single model Product, but while running makemigrations, I get the following message on the terminal: You are trying to add a non-nullable field 'product_ptr' to dinnerplatters without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py I tried googling … -
django.db.utils.IntegrityError: UNIQUE constraint failed: first_app_topic.top_name
I'm a beginner Django user... I have this code in my models.py file from django.db import models # Create your models here. class Topic(models.Model): top_name = models.CharField(max_length=264, unique=True) def __str__(self): return self.top_name class Webpage(models.Model): topic = models.ForeignKey(Topic, on_delete=models.SET_NULL) # added on_delete parameter, because DJANGO > v2.0 is name = models.CharField(max_length=264, unique=True) url = models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.ForeignKey(Webpage, on_delete=models.SET_NULL) # same on_delete needed to be added otherwise t>python manage.py migrate fails date = models.DateField() def __str__(self): return str(self.date) The above code is updated for Django version > 2.0 (ie with on_delete=models.SET_NULL) included as an argument. I then run the following commands in the command console python manage.py makemigrations registers the changes to your application. python manage.py migrate python manage.py shell >>> from first_app.models import Topic >>> print(Topic.objects.all()) <QuerySet [Topic: Social Network]> >>> t = Topic(top_name="Social Network") >>> t.save() This gives the following error log Traceback (most recent call last): File "C:\....\MyDjangoEnv\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\....\MyDjangoEnv\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: first_app_topic.top_name The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> … -
Cross checking field input in Python
I am writing a web application using oTree and Django and I am totally new to both. I am willing to ask the user to compile a form with two fields on the same page. I need to have a validation that checks whether the sum of the two values inserted in the two fields is less than a maximum value (e.g. 10). If the sum is bigger, I need to raise an error not letting the user switch to the next page. That's the code in the html file relative to the user input: {% formfield player.attribute_1 label="Your attribute 1 (from 0 to 10):" %} {% formfield player.attribute_2 label="Your attribute 2 (from 0 to 10):" %} {% next_button %} And that's the relative piece of code in the models.py file: class Player(BasePlayer): attribute_1 = models.CurrencyField( min=0, max=10, doc="""Your attribute 1""" ) attribute_2 = models.CurrencyField( min=0, max=10, doc="""Your attribute 2""" ) Currently it checks each single formfield to be in the range 0-10. How can I check the sum to be less than 10 instead? Thank you very much in advance for any help. -
How can I get the kwarg of the current url in Django
I am calling a view via an async AJAX call to lazy load blog posts. Now I am searching for a solution to get the category keyword (or named) arguments (kwarg) of the current url to use it for the database query within the view. So I either have to somehow pass that category via AJAX to the view or call it in the view directly. I do neither know which solution is the better one nor how to implement them. What I have: urls urlpatterns = [ path('<category>', render_blog_category, name='HotStocks'), path('<category>', render_blog_category, name='AsiaPacific'), path('<category>', render_blog_category, name='Europe'), path('<category>', render_blog_category, name='America'), path('<category>', render_blog_category, name='Pennystocks'), path('<category>', render_blog_category, name='Charts'), url(r'^$', render_blog_main, name='render_blog'), url(r'^lazy_load_posts/$', lazy_load_posts, name='lazy_load_posts'), url(r'^lazy_load_search/$', lazy_load_search, name='lazy_load_search'), ] blog.html which extends base.html <script type="text/javascript"> // A CSRF token is required when making post requests in Django // To be used for making AJAX requests in script.js window.CSRF_TOKEN = "{{ csrf_token }}"; </script> <div id="blog-wrapper"> <!-- Latest Posts --> <div id="latest-posts-ctn"> <div id="posts">{% include 'blog/posts.html' %}</div> </div> <div id="lazyLoad-ctn"> <a id="lazyLoadLink" href="javascript:void(0);" data-page="2"><div id="loadmore-button">Load More Posts</div></a> </div> </div> <!-- Close Blog-Wrapper --> base.html <ul id="navbar-navigation"> <li class="navigation-item"> <a href="{% url 'AsiaPacific' category='Asia Pacific' %}">Asia Pacific</a> </li> <li class="navigation-item"> <a href="{% url 'Europe' category='Europe' …