Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Iterate and append the value in JSON in python
I'm trying to the iterate and append the QId and Answer from the payload, desired output would be like 12|Yes&&13|Yes&&14|Yes&&15|Yes&&16|Yes&&17|Yes&&18|Yes&&19|Yes&&. I have tried to get only 12|Yes&& and 13|Yes&& separately. All I wanted is to concatenate QId and Answer before it saves to the database. How could I achieve this Qstans = str(qid)+'|'+ answer+'&&' this line which append the values payload 0: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 150…} 1: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "No", QId: 151…} 2: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 152…} 3: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 153…} 4: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "No", QId: 154…} 5: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 155…} 6: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "No", QId: 156…} What I tried @api_view(['POST']) def SaveUserResponse(request): if request.method == 'POST': data = [] cursor = connection.cursor() for ran in request.data: auditorid =ran.get('AuditorId') print('SaveUserResponse auditorid---', auditorid) ticketid = ran.get('TicketId') qid = ran.get('QId') answer = ran.get('Answer') sid = ran.get('SID') print('sid--', sid) TicketType = ran.get('TicketType') TypeSelected = ran.get('TypeSelected') agents = ran.get('Agents') supervisor = ran.get('Supervisor') Comments = ran.get('Comments') action … -
Making backup of db skiping part of data in django
I need to make backup of production db, for development purpose. but whole db is to heavy and take too long to restore it fully locally. so I need to drop part of data, but I don't want to drop whole models. Is there any package that would allow me to write script that would chose which data would be present in backup before making it without actually deleting this data from production db? -
How to add a search field for Django Admin Change/Add forms?
CONTEXT I am making a birthday app where the Admin can input their friends birthdays and gifts they wish to buy for them. The gifts are in a separate table and the friends_birthday table refers to this gifts table by a manytomanyfield. When creating a piece of data for their friend (i.e. firstname, birthday, etc.) the Admin must first create a gift for them via the gift table, then create a row in the 'friends_user' table that adds their info and gift(s). Problem When the Admin is adding the gifts to their friends, the default setting is a box populated by many gifts, some of which they are assigning to their other friends. However, if the project scales, then the box would overflow and simply highlighting the choices would not work. Hence, I want to create a search bar in the add/change form in Django Admin. Any ideas? Thanks in advance. -
Python nested json
Can any one have solution for this, i want there should be api data in this manner ?? I wanted api data in for similar state comes in one hood rather than seprate, different state data can be different obj, data = [{ state_name:New_jersi, data:{ category:Phishing, sub_cat_data:[{ name:SubCat1, count:20 }, { name:SubCat2, count:30 }] } category: malware, sub_cat_data:[{ name:SubCat1, count:20 }, { name:SubCat2, count:30 }] }, { state_name:Washinton, data:{ category:Phishing, data:[{ name:SubCat1, count:20 }, { name:SubCat2, count:30 }] } }] But may api response be: { "state": "South Carolina", "state_count": 2, "Website Compromise/Intrusion": { "sub_category": { "Insecure Direct Object Reference": 2, "Memory Corruption": 2, "SQLI": 1, "Stack Overflow": 1, "XSRF": 1, "Heap Overflow": 1, "Security Misconfiguration": 1 } } }, { "state": "South Carolina", "state_count": 1, "Phishing": { "sub_category": { "Spear Phishing Attacks": 2, "Fast Flux": 2, "Rock fish": 2, "Identify Theft/Social Engineering": 1, "Phishing Redirector": 1, "Pharming": 1, "Exploitation of Hardware Vulnerability": 1 } } }, i wanted same state data be in same object buut in my case state data comes in seprate object because of data comes through category, rather that seprate. My logic are below cat_count = incnum.values('incident_category__cat_name','incident_category__cat_id').annotate(count=Count('incident_category__cat_id')) subcat_count = incnum.values('incident_sub_category__sub_cat_name','incident_sub_category__cat_id','incident_sub_category__id').annotate(count=Count('incident_sub_category__cat_id')) reporter_state_count1 = incnum.values('incident_category__cat_id','reporter__comp_individual_state','reporter__comp_individual_state__name').annotate(count=Count('incident_category__cat_id')) for x, … -
Django with React: csrf token is undefined in cookies
part of react code: settings.py: views.py: btw, @ensurecsrf decorator is useless and will give you 403 forbidden error about csrf being not set any idea? -
pip install confluent-kafka gives error in mac
When i tried pip install confluent-kafka got the following error #include <librdkafka/rdkafka.h> ^~~~~~~~~~~~~~~~~~~~~~ 1 error generated. error: command '/usr/bin/gcc' failed with exit code 1 I'm using python version 3.9 and macOs Monterey -
How can I fix the paginator and the filter problem for Django?
To simply explain, I have a model product with columns: (Product model): name type (Order model): order price quantity I am using the django built-in Paginator and the django-filter. The paginator works so well and it really filters the items but the problem is, when the paginator is involved, the "Next" or "Previous" button I created will not work well to see the filtered items on the next or previous page because it reloads the whole template and the filter form will be erased. Example: I have mouse and keyboard as "choices" on the "Type" column of the product. I have 25 mice, and the paginator divides it by 10. I can filter the items and shows 3 pages for the mice but when I turn to the next page, the keyboard items will show because the filter form is reset. Any help or suggestion will be appreciated. I need to hear any thoughts for this. -
TemplateSyntaxError: 'for' statements should use the format 'for x in y'
I'm creating a listing page that emulates Stack Overflow's page limit feature; a user can choose to modify the number of questions listed whether it be 10, 15, or 25 on a page. In the process of creating an URL link for each page limit number within the template it's raising the following error: TemplateSyntaxError: 'for' statements should use the format 'for x in y': for limit in [10, 15, 25] What is it about the template for-loop that is causing this error to be raised? @register.simple_tag(takes_context=True) def set_page_number_url(context, page=None, limit=None): request = context['request'] request_resolver = resolve(request.path) query_string = QueryDict(request.META['QUERY_STRING']) query_tab, search_query = [ query_string.get("tab", "newest"), query_string.get("q") ] if page: page_data = { "pagesize": page.paginator.per_page, "page": page.number, "tab": query_tab, } else: page_data = { 'pagesize': limit, 'page': 1, 'tab': query_tab } _path = f"posts:{request_resolver.url_name}" if request_resolver.url_name == "tagged": tags = "+".join(tag for tag in context['tags']) path = reverse(_path, kwargs={'tags': tags}) query_string = urlencode(page_data) return f"{path}?{query_string}" if request_resolver.url_name == "search" and search_query: page_data.update({'q': search_query}) query_string = urlencode(page_data) path = reverse(_path) return f"{path}?{query_string}" <div class="page_range_options_wrapper"> {% for limit in [10, 15, 25] %} <a class="inactive_page page_num" href="{% set_page_number_url limit %}">{{ limit }}</a> {% endfor %} </div> -
Heroku Django postgres migration merge: psycopg2.errors.DuplicateTable: relation already exists
This is a Heroku-specific issue with a Django project 1.11.24 running Python 3.6.5 and a Heroku postgres database. During testing of two different branches during development, different conflicting migration files were deployed at different times to the Heroku server. We recognized this, and have now merged the migrations, but the order the Heroku psql db schema was migrated is out of order with the current migration files. As a result, specific tables already exist, so on deploy applying the updated merged migration files errs with: psycopg2.errors.DuplicateTable: relation "table_foo" already exists In heroku run python manage.py showmigrations -a appname all of the migrations are shown as having run. We've followed Heroku's docs and done the following: Rolled back the app itself to before when the conflicting migrations took place and were run (https://blog.heroku.com/releases-and-rollbacks) Rolled back the postgres db itself to a datetime before when the conflicting migrations took place and were run (https://devcenter.heroku.com/articles/heroku-postgres-rollback) However, despite both app and db rollbacks, when we check the db tables themselves in the rollback in pql shell with \dt, the table causing the DuplicateTable err still exists, so the db rollback doesn't actually seem to effect the django_migrations table. It's Heroku, so we can't fake … -
Why am I getting a "The connection was reset" error when trying to run my Django application on a Docker container?
I'm trying to containerize my Django app for the millionth time, and always seem to keep running to issues with mysql connection (or permissions?) issues. I still don't really understand what's going on during this process, and I keep running into the same general error. I'm seriously about to pull my hair out. Can someone please point out where I'm going wrong when trying to set up the container? My config files are at the end of this post. I'm in my project root (where my docker-compose.yml resides), and I try running docker-compose up --build. But, I get this error sportsbet-web-1 | Watching for file changes with StatReloader sportsbet-web-1 | Exception in thread django-main-thread: sportsbet-web-1 | Traceback (most recent call last): sportsbet-web-1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection sportsbet-web-1 | self.connect() sportsbet-web-1 | File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner sportsbet-web-1 | return func(*args, **kwargs) sportsbet-web-1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/base.py", line 200, in connect sportsbet-web-1 | self.connection = self.get_new_connection(conn_params) sportsbet-web-1 | File "/usr/local/lib/python3.9/site-packages/django/utils/asyncio.py", line 26, in inner sportsbet-web-1 | return func(*args, **kwargs) sportsbet-web-1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 234, in get_new_connection sportsbet-web-1 | connection = Database.connect(**conn_params) sportsbet-web-1 | File "/usr/local/lib/python3.9/site-packages/MySQLdb/__init__.py", line 130, in Connect sportsbet-web-1 | return Connection(*args, **kwargs) sportsbet-web-1 | File … -
OneToOne connection between User and Profile in Django
I am creating an app in django in which after user model is created, via the signal I create a profile: from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() But as far as I feel, this does not guarantees me that profile id always equals user's one Is there any smart way to do this safer? I think about creating a signal which will delete profile model after user one and opposite, but I still feel that not all cases are covered -
Django login user never come true
I am having problems with my Django login. The below if statement (if user is not None:) always resolves as false, so it moves onto the else. I'm not sure why and I would appreciate any help Thanks VIEWS.PY from django.shortcuts import render,redirect from django.contrib.auth import authenticate,login,logout from django.contrib import messages # Create your views here. def login_user(request): if request.method == 'post': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('index.html') else: messages.success(request,("there is an error....")) return redirect('login') else: return render (request ,'login.html', {}) urls.py from django.urls import path from accounts import views urlpatterns = [ path('login_user', views.login_user ,name= 'login'), ] main urls.py "" from django.contrib import admin from django.urls import path,include from availability import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('availability.urls'), name='index'), path('accounts/', include('django.contrib.auth.urls')), path('accounts/', include('accounts.urls')), ] ''' And here is the login form: <form action="" method="post"> {% csrf_token %} <div class="input-group mb-3"> <input type="text" class="form-control" name='username' placeholder="username"> <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-user"></span> </div> </div> </div> <div class="input-group mb-3"> <input type="password" class="form-control" name='password' placeholder="Password"> <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-lock"></span> </div> </div> </div> <div class="row"> <div class="col-8"> <div class="icheck-primary"> <input type="checkbox" id="remember"> <label for="remember"> … -
fetch data from pre-existing table and paste it into view of another django model
How can I make realtime changes of my view using django model and a pre existing table ? I have a table of random data of people like this people table and I have a model with class Todo(models.Model): title = models.CharField(max_length=100) memo = models.TextField(blank=True) voyageur = models.PositiveIntegerField(default=1) # set to current time created = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) # user who posted this user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title I want the data from the people table to be changed in the memo textfields in real time as I change the value of voyageur which can be associated to the primary key of "people" visualize in real time data as I change value of voyageur is this possible ? do I have to pass from a front end app like react to do that ? -
Reverse for 'Add' with arguments '('',)' not found. 1 pattern(s) tried: ['agregar/(?P<producto_id>[0-9]+)/\\Z']
I'm doing a tutorial from django, and i getting this error when trying to add an href button, i use django 4.0.4 version and python 3.9 version. Models.py class Producto(models.Model): serie_producto = models.CharField(max_length=30) nombre = models.CharField(max_length=30) codigo = models.CharField(max_length=15) marca = models.CharField(max_length=30) precio = models.IntegerField() created_date = models.DateTimeField(default=timezone.now) urls.py ... urlpatterns = [ ... path('agregar/<int:producto_id>/', agregar_producto, name="Add"), ... ] template catalogo that causes te error. The message error highlights {% url 'Add' producto.id %} {% for producto in response %} <div class="col-6"> <div class="card" style="height: 10rem; width: 23rem; margin: 5px 0px;"> <div class="card-body"> <h5 class="card-tittle">{{producto.nombre}}</h5> <p class="card-text">{{producto.marca}}</p> <p class="card-text">{{producto.precio}}</p> <a href="{% url 'Add' producto.id %}" class="btn btn-primary">Agregar al carrito</a> </div> </div> </div> {% endfor %} view.py from tienda.models import Producto from tienda.carrito import Carrito def catalogo(request): url = "http://127.0.0.1:8000/api/Producto/" response = requests.get(url, auth=('admin','duoc')) datos = response.json() return render(request, 'catalogo.html', {'response' : datos }) def agregar_producto(request, producto_id): carrito = Carrito(request) producto = Producto.objects.get(id=producto_id) carrito.agregar(producto) return redirect("Tienda") The Problem When i got to the catalogo template i get the before mentioned error, the api works perfectly when i dont use the {% url 'Add' producto.id %}, i think that is something with the id, cant read it maybe??, i dont know if … -
How to make Django using Pillow to crop only new image?
I can make Django crop images, but I got a problem. When I go to change form to update one of the images, all images got cropped again and again after every new save - which means all images get smaller and smaller. How to make Django only crop new images and leave old images alone? Each of my images got a crop count field - when set to 0 the image could be cropped and if set to 1 the image could not be cropped. Each image also got a created_date field which automatically generated a timestamp. Can any of these extra fields be used to create a condition in which an image won't get cropped twice when a whole model got updated? Example: product 1 = got image_1, image_2, image_3, -- image_1 got crop_count and created_date fields, same goes for all other images. -- I want is to go to image_1 to update it with a newer image, and I don't want to see image_2 and image_3 got cropped - but only image_1 gets cropped. How? I know how to use signal in Django, so should this be post-save or pre-save? -
Email Not Sending in AWS SES
Settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'email-smtp.us-west-2.amazonaws.com' EMAIL_HOST_USER = config('SMTP_USER') EMAIL_HOST_PASSWORD = config('SMTP_PW') EMAIL_PORT = 587 VERIFIED_IDENTITY = config('VERIFIED_IDENTITY') I have a verified email in my AWS SES and I am trying to send a message. I get a sent message everytime I use my contact form but no message actually gets sent. if 'contactForm' in request.POST: #print('Contact form') contact_form = ContactForm(request.POST) if contact_form.is_valid(): contact_form.save() email_subject = f'New contact {contact_form.cleaned_data["email"]}: {contact_form.cleaned_data["subject"]}' email_message = contact_form.cleaned_data['message'] print(email_subject,email_message) try: send_mail(email_subject, email_message,settings.VERIFIED_IDENTITY,[settings.VERIFIED_IDENTITY]) except BadHeaderError: print('bad') -
Making a dropdown list based on an IntegerField's value django
I want to display the Nombre_des_Emplacments IntegerField in the Rayons model as a dropdown menu in the References Model below, for example the number inputted is 44, I want for the dropdown menu to show the numbers between 1 and 44 as choices to select from, and after a number is selected and saved after adding the References, it has to be taken out from the choices and not show up again when adding a new Reference, Exp: if 20 is selected next time the dropdown menu will show all the numbers from 1 to 44 except 20 just so you know the Nombre_des_Emplacments IntegerField is also suppossed to be dependent on Rayons.Nom from the same Model which will also be a dropdown menu So when adding a reference and I get to the Emplacment field, I select the Rayon and depending on what I selected the second dropdown menu will show the correlated numbers with that Rayons here's the code: models:py class Rayons(models.Model): Nom = models.CharField(max_length=100, blank=False, null=True) Nombre_des_Emplacments = models.IntegerField() def __str__(self): return self.Nom class References(models.Model): Ref = models.CharField(max_length=255, blank=False, null=True) Designation = models.CharField(max_length=100, blank=False, null=True) Indice = models.CharField(max_length=100, blank=False, null=True) Emplacment = models.ForeignKey(Rayons, blank=False, null=True, on_delete=models.CASCADE) Client … -
How to fix this problem in django? about subprocess.Popen and session
this is my views.py @csrf_exempt def tictactoe_ai(request): context = {'current_url' : '/tictactoe'} if request.method == "GET": my_ai = Tic_ai.objects.create() request.session['tictai_id'] = str(my_ai.id) return render(request,'static_page/tictactoe_ai.html',context) if request.is_ajax(): res = {} the_id = int(request.session['tictai_id']) my_ai = Tic_ai.objects.get(id = the_id) rest = request.POST x,y = rest.get("x"),rest.get("y") a = str(x) + ' ' + str(y) + '\n' message = my_ai.in_stuf(a) res["x"],res["y"] = message.split(" ") return JsonResponse(res) this is my models.py class Tic_ai(models.Model): ai = subprocess.Popen( r"D:\duoduo2\DDQK-Caesar\ddqk-caesar\static_page\tictac_ai.exe", stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) def in_stuf(self,a): self.ai.stdin.write(a.encode()) self.ai.stdin.flush() return self.ai.stdout.readline().decode().replace('\n','').replace('\r','') def finish(self): self.ai.kill() I found that although the code "my_ai = Tic_ai.objects.create()" was excecute. but the ai are all the same. I want to have different ai in different Tic_ai. But the "ai" are all the same please. This trouble had disturbed me for a whole day -
How to easily find patch target in unittest?
I have the following module structure within a Django app: subscriptions - api - views.py - serializers.py - tests test_some_view.py - models.py - signals.py In models.py I have a GooglePlayOrder model, and in signals.py I have a signal: @receiver(post_save, sender=GooglePlayOrder) def save_google_play_order(sender, instance, created, **kwargs): pass The GooglePlayOrder instance is being created in a serializer GooglePlayOrderSerializer from api/serializers.py, which is called by some GooglePlayOrderView in api/views.py. And now I want to run a test from api/tests/test_some_view.py, where I want to mock the save_google_play_order signal. Unfortunately, this implementation does not work, as I (AFAIK) should follow the imports for patching something: @patch('subscriptions.signals.save_google_play_order') def test_normal(self, mock): So, how should I understand in this case what exactly I should use as a target of patch decorator? -
django.db.utils.IntegrityError: NOT NULL constraint failed: pages_add_music.upload error
i wrote a code to upload images of music and it works ,but when i try to edit older posts (i hadnt add img field yet) it shows this error django.db.utils.IntegrityError: NOT NULL constraint failed: pages_add_music.upload my models: class add_music(models.Model): name = models.CharField(max_length=100) artist = models.CharField(max_length=100) nation = models.CharField(max_length=100) language = models.CharField(max_length=100) year = models.DecimalField(max_digits=4,decimal_places=0,null=True) genre = models.TextField() duration = models.DecimalField(max_digits=3,decimal_places=2,null=True) upload = models.DateTimeField(auto_now_add=True) img = models.ImageField(blank=True,null=True,upload_to='images/') def __str__(self): return self.name.title()+" by "+self.artist views: def edit_music_view(request,music_id): my_object = add_music.objects.get(id=music_id) if request.method != 'POST': form = add_music_form(instance=my_object) else: form = add_music_form(instance=my_object,data=request.POST) if form.is_valid(): form.save() context={'form':form,'my_object':my_object} return render(request,'pages/edit_music.html',context) and template: {% extends 'pages/base.html' %} {% block content %} <p>{{ my_object }}</p> <form action="{% url 'pages:edit_music' my_object.id %}" method='post' enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit" value="yes">save</button> </form> {% endblock %} whats wrong with it?can u hlp me pls? -
ValueError: Unknown metric function: top_2_accuracy. Please ensure this object is passed to the `custom_objects` argument
I'm working on a CNN classification project, and I've used the top 2 Accuracy (top_k_categorical_accuracy) as the accuracy matrix for training. the function in the model notebook is: from tensorflow.keras.metrics import top_k_categorical_accuracy def top_2_accuracy(y_true, y_pred): return top_k_categorical_accuracy(y_true, y_pred, k=2) then I used it as model.compile(optimizer = Adam(lr = 4e-3), loss='categorical_crossentropy', metrics=['accuracy', top_2_accuracy]) Now I need to load the model to use it in an application I tried to use this code: model = tf.keras.models.load_model('model.h5') but an error occurred while loading Unknown metric function: top_2_accuracy. Please ensure this object is passed to the `custom_objects` argument. See https://www.tensorflow.org/guide/keras/save_and_serialize#registering_the_custom_object for details. then I've googled and tried this too: model = tf.keras.models.load_model('model.h5', custom_objects={'top_k_categorical_accuracy(y_true, y_pred, k=2)':top_2_accuracy}) but it generated another error model = tf.keras.models.load_model('model.h5', custom_objects={'top_k_categorical_accuracy(y_true, y_pred, k=2)':top_2_accuracy}) NameError: name 'top_2_accuracy' is not defined How can I solve this?? -
How to change in Sqlite the order of the results?
I'm working on a site where I showing results on a timeline chart but I like to show only the last three results. In ASC order the the first point of the chart starts on the left side but if I have more than three results the first three appears and thats ot what I want. If I order my result in DESC by the date it changing the order and it is OK but the last three results (that I need) takes the firs places on the left side (like on the image). I like to show the last three results from left to right. How could I do that? This is what I have now: SELECT * FROM table GROUP BY strftime("%%Y-%%m", date) ORDER BY max(strftime("%%Y-%%m", date)) DESC LIMIT 3 -
IntegrityError at /listing/1/ NOT NULL constraint failed: auctions_comments.user_id. I am trying to save comments and need help resolving this error
I am trying to make an e-commerce site (CS50 Project 2) that saves comments. The comments were previously saving, but then I added ForeignKeys to my comment model to link it to the Listings and User models. Now whenever I try to save a comment this error occurs. IntegrityError at /listing/1/ NOT NULL constraint failed: auctions_comments.user_id Request Method: POST Request URL: http://127.0.0.1:8000/listing/1/ Django Version: 3.2.5 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: auctions_comments.user_id And this line of code is highlighted comment.save(). This is my models.py: class User(AbstractUser): pass class Listings(models.Model): CATEGORY = [ ("Miscellaneous", "Miscellaneous"), ("Movies and Television", "Movies and Television"), ("Sports", "Sports"), ("Arts and Crafts", "Arts and Crafts"), ("Clothing", "Clothing"), ("Books", "Books"), ] title = models.CharField(max_length=64) description = models.CharField(max_length=500) bid = models.DecimalField(max_digits=1000000000000, decimal_places=2) image = models.URLField(null=True, blank=True) category = models.CharField(max_length=64, choices=CATEGORY, default=None) class Comments(models.Model): listing = models.ForeignKey(Listings, on_delete=models.CASCADE, default="") user = models.ForeignKey(User, on_delete=models.CASCADE, default="") comment = models.CharField(max_length=500) views.py @login_required(login_url='login') def listing(request, id): listing = Listings.objects.get(id=id) comment_obj = Comments.objects.filter(listing=listing) form = CommentForm() if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.listing = listing comment.save() else: return render(request, "auctions/listing.html",{ "auction_listing": listing, "form": form, "comments": comment_obj }) return render(request, "auctions/listing.html",{ "auction_listing": listing, "form": form, "comments": comment_obj … -
For some reason my modle data is nto displying in my view
I have been working on a blog project for some time and I have run into a big issue. When I go to a specific blog posts page the data for that page does not load. It is not a problem with the URL bc the URL is unique for every blog post. Any help would be appreciated. views from django.shortcuts import render, reverse from django.http import HttpResponseRedirect from django.views import generic from . import models from django.contrib.auth import get_user_model User = get_user_model() from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin # Create your views here. class create_blog_post(generic.CreateView, LoginRequiredMixin): model = models.Blog_Post template_name = 'blog_app/creat_post.html' fields = ('post_title', 'blog_content') success_url = reverse_lazy('blog_app:all') class view_blog_post(generic.TemplateView): model = models.Blog_Post template_name = 'blog_app/view_post.html' class delet_blog_post(generic.DeleteView, LoginRequiredMixin): model = models.Blog_Post template_name = 'blog_app/delete_post.html' def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user_id = self.request.user.id) def delete(self, *args, **kwargs): messages.success(self.request, 'Post Deleted') return super().delete(*args, *kwargs) class all_blog_posts(generic.ListView): model = models.Blog_Post template_name = 'blog_app/all_posts.html' #slug_url_kwarg = "slug" modles.py from django.db import models from taggit.managers import TaggableManager # Create your models here. class IpModel(models.Model): ip = models.CharField(max_length=100) def __str__(self): return self.ip class Blog_Post(models.Model): slug = models.SlugField(max_length=1000, editable=False, null=True) post_title = models.CharField(max_length=100, editable=True, blank=False, null=True) blog_content = models.TextField(max_length=10000, blank=False, editable=True, … -
If an app has multiple models with the same field, whats the best practice for keeping things DRY?
For example, if I have 3 models that look like this: class CallLog(models.Model): lead_id = models.BigIntegerField("Lead ID") # other fields class EmailLog(models.Model): lead_id = models.BigIntegerField("Lead ID") # other fields class TextLog(models.Model): lead_id = models.BigIntegerField("Lead ID") # other fields Do I add lead_id to each model individually or is there a way to only type it once?