Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to join two tables in Flask using mysqldb
I have two tables: the client table and the task table. I have added clients like 1) id , name,emai, phone,project. now I have to use this client in my second table task when I add a task it shows the client name automatically in task table form. how to get this using Flask and mysqldb (not sqlalchemy) i will get empty value insted of it shwo client -
django test.py changes the autoincrement of table
In the test.py I make new entry id=10000 for testing purpose(id is auto increment, current auto increment number is 36) temp = sm.mytable(id=10000,created_by="test",created_at=datetime.datetime.now()) temp.save() After test, this row is removed() automatically. However autoincrement number start from 10000~ Why this happen? database control in test.py affect the real database? -
why my second app doesn't want import to first app Django
File "C:\python mini\PyCharm Community Edition 2021.1.1\MyBlog\mysite\mysite\urls.py", line 3, in <module> from mysite.register import views ModuleNotFoundError: No module named 'mysite.register' Why do you think this error might occur? Why doesn't django see the app being imported? maybe I should try setting up mysite/blog urls? project structure: settings.py ` from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent STATIC_DIR = os.path.join(BASE_DIR, 'static') CRISPY_TEMPLATE_PACK = "bootstrap4" STATIC_URL = '/static/' SECRET_KEY = '' DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'menu', 'register.apps.RegisterConfig', ] mysite/urls.py from django.contrib import admin from django.urls import path, include from mysite.register import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path("register/", views.register, name="register"), ] ` If i try write just from register import views import underlined in red -
What do I have to do to make a django project available to my company's internal network?
Recently I developed a simple django project to be used by my colleagues. The goal was to have the project only available within the network so no one outside the company could access it. The company has a server, with a certain IP that will host the project. What steps do I have to take, either in django or on the company server, to make the project available to everyone in the company? Do I have to install python in the server? I tried to put the servers IPs in allowed_hosts but it doesn't work. Thanks for helping, Edward -
Getting incorrect title in the URL path Django
I have an app with a bunch of POST request on a path that looks like this: path("auctions/<str:title>", views.listing, name="listing") It's a sort of auction app, where users can create listings, and others can place bids and purchase these items. When a user clicks on one of these items, ive got this function that takes them to a page where they can get all details about the listing that they have just clicked and they can do things like place a bid or place the item in their watchlist. views.py def listing(request, title): if request.method == "POST": if watchlist.is_valid(): if "watchlist" in request.POST: watchlist_data = Watchlists.objects.all().filter(title=title, user=username).first() if watchlist_data: watchlist_data.delete() else: true_wtchlist = Watchlists.objects.create(title=title, user=username) ps: watchlist here is just an example of one of the conditions under my function, i just posted it as an example, even though i will appreciate any errors beign pointed out if any is noticed. I can usually get the title of the listing that was clicked from the title argument that gets passed here def listing(request, title): , and i use this title to query the database. Now I am trying to add a 'Close listing' button to the page so that the … -
Django admin inline: Clone entry
I`m using a GenericStackedInline in my django admin. I would like to have the option to duplicate the inline object when editing the parent object. I can think of two ways of doing this: Using django-inline-actions to add a "clone" button. This did not work, because it does not show when using a fieldset in the GenericStackedInline Adding another checkbox next to "delete" checkbox with label "clone". When activating the checkbox and saving parent object, it should clone the inline object with new id. Is there an easy way to add another checkbox and add a action to handle cloning? -
video steaming using django Rest Framework
RestAPI Streem Video How i can do for this based requeste input:Video,Timesteemp, output: Return Based on Timeframe or base64 data Next Video Chunks send back -
Django suddenly refuses to load statics [closed]
Sorted this problem out before with "python manage.py collectstatic", but Django started to refuse loading static files for no reason. The error message on the terminal is: Not Found: /img/undraw_profile.svg What should I do? I cleared cache, made command 'collectstatic' again, checked root directory in settings.py but still could not find why. -
Django make pizza [closed]
Manage Toppings As a pizza store owner I should be able to manage toppings available for my pizza chefs. It should allow me to see a list of available toppings It should allow me to add a new topping It should allow me to delete an existing topping It should allow me to update an existing topping It should not allow me to enter duplicate toppings Manage Pizzas As a pizza chef I should be able to create new pizza master pieces It should allow me to see a list of existing pizzas and their toppings It should allow me to create a new pizza and add toppings to it It should allow me to delete an existing pizza It should allow me to update an existing pizza It should allow me to update toppings on an existing pizza It should not allow me to enter duplicate pizzas Can you guys help on how do I do this in Django project. -
How to fix {detail: Authentication credentials were not provided.} in Django Rest Framework
I have struggling with getting information from Django rest framework as a backend and from the frontend using flutter. The sequence of the project of the project is that I login and receive a {"key":"XXXXXXXXXXXXX"} Just for testing purposes I am trying to manully add the key to get access. I keep getting {detail: Authentication credentials were not provided.} I am not sure whether the error is because of Django Rest Framework setting or Flutter front end Here is the Fetch user() in the homescreen: Future<User> fetchUser() async { var url = Uri.parse(Config.apiURL + Config.userProfileAPI); print(url); final response = await http.post( url, // headers: { // HttpHeaders.authorizationHeader: // 'Bearer XXXXXXXXXXXXX', headers: { "Authorization": 'JWT XXXXXXXXXXXXX' // 'Authorization: ', },); final responseJson = jsonDecode(response.body); print(responseJson); if (response.statusCode == 200) { return User.fromJson(jsonDecode(response.body)); } else { throw Exception('Failed to load User'); }} class User { int? pk; String? username; User({this.pk, this.username}); User.fromJson(Map<String, dynamic> json) { pk = json['pk']; username = json['username'];} Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['pk'] = this.pk; data['username'] = this.username; return data;}} class HomeScreen extends StatefulWidget { const HomeScreen({super.key}); @override State<HomeScreen> createState() => _HomeScreenState();} class _HomeScreenState extends State<HomeScreen> { late Future<User> futureUser; @override … -
How do I change the verbose name of django table header
Since I can't use the verbose name of the model (Using jsonfields), I need a function which redefines the header's verbose name. As the docs say (Link to docs): In order of preference, this will return: The column’s explicitly defined verbose_name The model’s verbose_name with the first letter capitalized (if applicable) Fall back to the column name, with first letter capitalized. But how can I change this behaviour? I want to set the name of the columns header to something different. Currently I use def get_top_pinned_data(self): So I can show the verbose names on the top, but I want to sort it too. -
Django request.POST loop
How can I loop through the request data and post it as one line in to the database, user can submit multiple descriptions, lengths and so on, problem I have is in the DB its creating massive amounts of rows to get to the correct format of the last one A1 but the user could submit A1,1,1,1,1; A2,2,2,8,100 and so on as its a dynamic add form) descriptions = request.POST.getlist('description') lengths = request.POST.getlist('lengthx') widths = request.POST.getlist('widthx') depths = request.POST.getlist('depthx') quantitys = request.POST.getlist('qtyx') for description in descriptions: for lengt in lengths: for width in widths: for depth in depths: for quantity in quantitys: newquoteitem = QuoteItem.objects.create( qdescription=description, qlength=lengt, qwidth=width, qdepth=depth, qquantity=quantity, quote_number=quotenumber, ) bottom entry is correct post system -
Django celery task unable to use cairo svg2pdf
I have a small task that reads a svg file from a path and uses cairo svg2pdf to convert the svg to pdf. If I run the function without using celery delay then the function runs fine and converts the file to pdf. If I run the function as a celery task then I get some errors: Traceback (most recent call last): File "/..../tasks.py", line 24, in create_download_pdf svg2pdf(bytestring=bytestring, write_to=completeName) File "/.../lib/python3.10/site-packages/cairosvg/__init__.py", line 67, in svg2pdf return surface.PDFSurface.convert( File "/.../lib/python3.10/site-packages/cairosvg/surface.py", line 131, in convert instance = cls( File "/.../lib/python3.10/site-packages/cairosvg/surface.py", line 202, in __init__ self.cairo, self.width, self.height = self._create_surface( File "/.../lib/python3.10/site-packages/cairosvg/surface.py", line 242, in _create_surface cairo_surface = self.surface_class(self.output, width, height) File "/.../lib/python3.10/site-packages/cairocffi/surfaces.py", line 876, in __init__ Surface.__init__(self, pointer, target_keep_alive=write_func) File "/.../lib/python3.10/site-packages/cairocffi/surfaces.py", line 158, in __init__ self._check_status() File "/../lib/python3.10/site-packages/cairocffi/surfaces.py", line 170, in _check_status _check_status(cairo.cairo_surface_status(self._pointer)) File "/../lib/python3.10/site-packages/cairocffi/__init__.py", line 88, in _check_status raise exception(message, status) OSError: [Errno cairo returned CAIRO_STATUS_WRITE_ERROR: b'error while writing to output stream'] 11 Here is the function: @app.task(name="create_download_pdf") def create_download_pdf(folder_path: str, svg_data=None, filename=None, file_path=None) -> None: try: completeName = os.path.join(folder_path, f"{filename}.pdf") if svg_data: svg2pdf(bytestring=svg_data, write_to=completeName) elif file_path: with open(file_path, 'r') as f: bytestring=f.read() print(bytestring) svg2pdf(bytestring=bytestring, write_to=completeName) except (OSError, ValueError): logger.exception( f"PDF creation and download exception: Unable to download | create … -
Logic on serializer fields
I am trying to work out how to run some logic to get certain objects from within my serializer (or elsewhere). I have the following: class Parent(models.Model): name = models.CharField(max_length=255) class Child(models.Model): name = models.CharField(max_length=255) parent = models.ForeignKey( Parent, related_name='children', on_delete=models.CASCADE) class ChildSerializer(serializers.ModelSerializer): class Meta: model = Child fields = ( 'id', 'name', ) class ParentSerializer(serializers.ModelSerializer): children = ChildSerializer() class Meta: model = Parent fields = ( 'id', 'name', 'children', ) class ParentViewSet(viewsets.ModelViewSet): serializer_class = ParentSerializer queryset = Parent.objects.all() class ChildViewSet(viewsets.ModelViewSet): serializer_class = ChildSerializer queryset = Child.objects.all() I would like to add a field to the parent response: first_child which is the first child alphabetically by name (this logic would be slightly more complex in reality, the largest value of the sum of multiple fields for example). I will also remove the children field in favor of this first_child field as the number of those will be too high to display in-line like this. -
Django doesn't return data from database on same HTML page as form
This is my final project for my college class and they required us to take many unnecessary steps in development I think may have overcomplicated my code but I am not sure what the best way to fix it is. I can get the data from the form into the database and then pass that data to the appropriate view where it queries yelp and puts it into a JSON file and then particular fields from the JSON file are saved to the database. My problem is that I can't seem to display the database data. After reviewing my code I think there may be too many steps along the way. I am thinking there is a simpler way to go about this but I don't want to destroy what I have trying to figure out and make it worse I am also concerned that I have made such a mess of things it needs an overhaul but I may be panicking lol. I am ok with the mess if I can get the information to display on the HTML page but I would like to know what the best way to write this would be if someone would like … -
Django admin foreignkey field in form
I have a model like class Info(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class Detail(models.Model): info = models.ForeignKey(Info) ... In admin when I add Detail I want all the fields of Info model as a form field without + sign just as normal fields. How is this possible ? -
Trying to edit a profile using Django but keep running into bugs
I am really struggling to allow users to update the Profile model in my app. I'm working on building a web application that helps people set up a diet. The general structure is a website visitor shows up and immediately gets directed to a Sign In and either Registers or Signs In. When they register, a Profile is automatically created. The thought process was I would add the user data (height, weight, etc.) gets added to the Profile model. Right now a new user goes Sign in -> Register -> Sign In -> Profile (which is filled with blank data) -> and Edit Profile. The edit profile is where I'm stuck. No matter what I try, I keep running into errors and have been spinning my wheels too much. I would really appreciate some help. Models from django.db import models from django.contrib.auth.models import User from django.dispatch import receiver #add this from django.db.models.signals import post_save #add this SEX = [('Male', 'Male'), ('Female', 'Female')] ActivityLevels = [('Sedentary', 'Sedentary'), ('Lightly active', 'Lightly active'), ('Moderately active', 'Moderately active'),('Active', 'Active'), ('Very active', 'Very active')] # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) massLbs = models.IntegerField("Weight in Lbs", null=True, blank=True) heightFeet … -
Automaticaly downloadable invoice pdf
I want to create an option to download a pdf file having an invoice with the following properties in the django database admin: models.py: from django.db import models from appsystem.models import Outlet from core.models import Item, Supplier from location.models import Warehouse, Zone, Section, Level class MainPurchases(models.Model): METHOD_A = 'CASH' METHOD_B = 'CREDIT' PAYMENT_METHODS = [ (METHOD_A, 'CASH'), (METHOD_B, 'CREDIT'), ] product = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField() purchase_price = models.DecimalField(max_digits=6, decimal_places=2) paid_amount = models.DecimalField(max_digits=6, decimal_places=2) date_created = models.DateTimeField(auto_now_add=True) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) I need this to be a printable invoice slip with the specified values but I just can't get anywhere. -
ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2._psycopg' django
My site was working well in cpanel. when i add google search console for seo, after one day I am seeing such error. Passenger.log file My os is Windows. Please help guys. I would be very grateful. I installed psycopg2-binary as psycopg2 didnt work. -
Django template comparing strings returning false?
I have in my template a button that should only be visible if 1 The user is signed in and; 2 The user is the one who posted the listing but doesnt show up even if all the above conditions have been met, so i have this in my template: {% if user.username == "{{ users }}" %} <form action="listing" method="GET"> <input class="btn btn-primary" type="submit" value="Close Listing" name="close"> </form> {% endif %} where "{{users}}" is the username of whoever posted the listing, and thus if its a match, this user gets the button views.py listing = Listing.objects.all().filter(title=title).first() user = listing.user passing it to the template: return render(request, "auctions/listing.html", { "users": user }) Cant find what i am doing wrong -
Django count using in object list
I have two models - Book and Tags connected by ManyToMany. After filtering the list of books, I want to get the list of tags used in these books and the count for each tag. class Tag(models.Model): name = models.CharField(max_length=255) description = models.CharField(max_length=255) type = models.CharField(max_length=255, default='tag') is_showing = models.BooleanField() using_count = models.IntegerField(default=0) def __str__(self): return self.name class Meta: constraints = [ models.UniqueConstraint( fields=['name', 'type'], name='unique_migration_host_combination' ) ] @property @lru_cache def count(self): cnt = self.book_set.count() return cnt class Book(models.Model): name = models.CharField(max_length=255) tag = models.ManyToManyField(Tag) def __str__(self): return self.name @property def tags_count(self): return self.tag.filter(type='tag').count() @property def genres_count(self): return self.tag.filter(type='genre').count() @property def fandoms_count(self): return self.tag.filter(type='fandom').count() The last time I manually took out a list of tags from each book and put them in a dictionary, after which I got a dictionary of the number of tags used, which was not very convenient to use in the django template engine -
how to render data from list in python over a html page?
lists = ['data1','data2','data3'] for in i lists time.sleep(5) //I would like to write a function that will take i as an //argument renders that in an html page something like this hello data1 after 5 seconds if we refresh the page hello data2 I am new to web development and I dont know how to implement it if some one could guide me it would be helpful -
in django how can i reverse to that page when info submitted
class ModelCreateView(CreateView): model = Message fields=['message'] template_name = "page.html" succes_url = reverse='page' No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model. this is error but if i put get absolute url reverse going detail page -
How can i create a Array Custom Model Field
class PermsField(models.Field): def db_type(self, connection): return 'CharField' def __init__(self, *args, **kwargs): kwargs['max_length'] = 64 kwargs['verbose_name'] =_('permission') super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["max_length"] del kwargs["verbose_name"] return name, path, args, kwargs I want to create a custom model Field who behaves like an array but i can't use an array. I don't understand because my code doesn't work, the permsField work like an str. But i want it work like an array (or list) of str -
Javascript Fetch Function returns [object Promise]
I'm currently working on a project, which includes a website, built and run by Django. On this website, I'm trying to load data through fast API and try to load this data through JavaScript and the Fetch API. But I always get instead of the Data provided through the API, an [object Promise]. I've tried many different methods but none seem to work. Any help will be greatly appreciated! I've tried for example: document.getElementById("1.1").innerHTML = fetch('the URL') .then(response => response.text()) or document.getElementById("1.1").innerHTML = fetch('the URL') .then(response => response.text()) .then((response) => { console.log(response) }) and many other methods. I've also checked and the API request works perfectly, returning a string.