Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error 1064, "You have an error in your SQL syntax" Python Django
I am receiving multiple SQL errors in my Django website post setup. I believe it's a version issue but can't point it out. The site was created with mysqlclient, but I have moved it to mysqlconnector. Full example error messages are: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'OPTION max_matches = 1000' at line 1") (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'group, denomination, location, affiliation, released_by, affiliations, filetypes' at line 1") MySQL Version: 8.0 (used just for sphinx) Database using Postgres Using mysqlconnector init.py (main for site) imports pymysql, using install_as_MySQLdb() I auto-created models.py using python manage.py inspectdb>models.py, but am not sure if that even helped anything (the site was given with model files only controlled by app). Django is 2.0.13, python is 3.9 running with Six -
Bokeh datatable not rendering
I am getting below error while rendering BokehJS datatable component in template. bokeh-2.3.2.min.js:166 Uncaught (in promise) Error: Model 'StringFormatter' does not exist. This could be due to a widget or a custom model not being registered before first usage. I tried to manually include below styles and scripts, however issue still remains same and datatable is not displayed on UI. <link href="https://cdn.bokeh.org/bokeh/release/bokeh-0.12.9.min.css" rel="stylesheet" type="text/css"> <link href="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.9.min.css" rel="stylesheet" type="text/css"> <link href="https://cdn.bokeh.org/bokeh/release/bokeh-tables-0.12.9.min.css" rel="stylesheet" type="text/css"> <script src="https://cdn.bokeh.org/bokeh/release/bokeh-0.12.9.min.js"></script> <script src="https://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.9.min.js"></script> <script src="https://cdn.bokeh.org/bokeh/release/bokeh-tables-0.12.9.min.js"></script> Datatable code: from django.shortcuts import render from .models import Trend_Chart import pandas as pd from bokeh.models import NumeralTickFormatter, HoverTool, ZoomInTool, PanTool, ResetTool, SaveTool, ColumnDataSource from bokeh.models.widgets.tables import TableColumn, DataTable, StringFormatter, StringEditor from bokeh.plotting import figure, output_file, save from bokeh.embed import file_html, components from bokeh.resources import CDN # Construct Raw data data = dict( timeseries=["placeholdertext"], testvalue1=["placeholdertext"], testvalue2=["placeholdertext"], testvalue4=["placeholdertext"], testvalue5=["placeholdertext"] ) source = ColumnDataSource(data) columns = [ TableColumn(field="timeseries", title="Time Series"), TableColumn(field="testvalue1", title="Test Value1"), TableColumn(field="testvalue2", title="Test Value2"), TableColumn(field="testvalue3", title="Test Value3"), TableColumn(field="testvalue4", title="Test Value4"), ] data_table = DataTable(source=source, columns=columns, width=400, height=280) # save the results to a file # output_file("temp.html") # doc = curdoc() script, div = components(p) script1, table = components(data_table)``` Is there any other way to include simple datatable in django template? Any reference … -
In Django 3.2 I am getting this error: app ImportError: Module 'apps.articles' does not contain a 'ArticlesConfig' class
Research Preamble: What have I tried? I'm new to Django and learning my way through while trying to follow best practices. I'm working my way through Two Scoops of Django 3.x. Any questioning of structure should be directed to the authors. I'm hopeful that the question is solid enough to not be deleted in the first few minutes as I'm really stuck on this one. If this question is to be deleted I would appreciate guidance on how to improve how I ask questions in the future. I've read the how to ask good questions blog and am hopeful I'm following this guidance. If I did miss something please do more than provide a link to the blog. Please note that I have researched this question and the closest I came was a Q&A for Django 1.7 here: Django 1.7 app config ImportError: No module named appname.apps: This solution did not work for me (although it did give me a good path to try). Interestingly, they chose the exact same application structure as I did, over 5 years earlier. Please note that providing the projectname in config did not solve this for me as it did the OP. Other questions … -
What is the complete list of ways that the database can be updated with Django and the Django ORM?
I need the complete list of code paths that can update the database through the Django ORM. So far, I've found: A model's save method Queryset methods (update) Manager methods (bulk_*) Are there more? Is it possible to monkey-patch code in that runs every time one of these methods is called? -
How to determine the direction for displaying div elements?
I'm creating a website. I have a problem displaying div elements because they are displayed upwards. But I want them to appear downwards as in the second picture. How to solve this problem? How they display now: How I want them to display(I have done this manually): My HTML file: </form> {% if searched %} <div class="results"> {% for user in users_list %} <a href="{% url 'user_page' pk=user.pk %}"> <div class="result"> <div class="photo-circle"> <p class="userphoto"></p> </div> <p class="username">{{ user }}</p> </div> </a> {% endfor %} </div> {% else %} <p>Nic jste nevyhledali</p> {% endif %} My CSS file: .results { position: absolute; left: 50%; top: -10%; display: flex; flex-direction: column; gap: 50px; transform: translate(-50%,-50%); } .result { background-color: #FFFFFF; border-radius: 50px/50px; transform: translate(-50%,-50%); width: 35vw; height: 17vh; } .photo-circle { height: 15vh; width: 15vh; background-image: linear-gradient(to bottom right, #0390e2, #611be4); border-radius: 50%; position: absolute; top: 50%; left: 2%; transform: translate(0, -50%); } .userphoto { color: white; font-size: 400%; font-family: 'Quicksand', sans-serif; font-weight: 700; position: absolute; margin-left: 50%; margin-top: 45%; transform: translate(-50%,-50%); } a { text-decoration: none; } .username { font-family: 'Quicksand', sans-serif; font-weight: 650; text-indent: 10vw; color: black; font-size: 150%; position: absolute; top: 35%; transform: translate(0, -50%); } -
How do these different Django 'context' construction differ?
The basic concept of context in Django are well explained here and here, as well as Django doc. But I don't understand the following code that works in the Mozilla Django tutorial: class BookListView(generic.ListView): model = Book def get_context_data(self, **kwargs): context = super(BookListView, self).get_context_data(**kwargs) context['author_books'] = Book.objects.filter(author=self.kwargs['pk']) return context Why is it necessary to define context twice? Is it the same as: author_books = # 'author_books' defined book_list = # 'book_list' defined context ={ 'author_books': author_books, 'book_list': book_list, } Testing in Django shell didn't work for me as I'm still struggling with how to extract data from foreign-key items. -
Form object has no attribute 'save_m2m' when overriding the save method
I made a custom Admin form in which I overrode the save method: def save(self, commit=True): product = Product.objects.create( title=self.data.get("title"), user=USER_MODEL.objects.get(id=self.data.get("user")), date=date, ) File.objects.create( file=self.data.get("file_xls"), product=product, user=USER_MODEL.objects.get(id=self.data.get("user")), date=date, ) ProductOption.objects.create( product=product, file=xls_file, name=ProductOption.XLS ) return product The problem now is that I get a 'ProductForm' object has no attribute 'save_m2m' even though the model doesn't have any M2M fields. -
get() missing 1 required positional argument: 'args'
I was following this tutorial to make direct messaging on my web. All my code is same as in the tutorial, but whenever I python manage.py runserver and go to the url -get() missing 1 required positional argument: 'args'- pops up. Code in views: class ListThreads(View): def get(self, request, *args, **kwargs): threads = ThreadModel.objects.filter(Q(user=request.user) | Q(receiver=request.user)) context = { 'threads': threads } return render(request, 'inbox.html', context) class CreateThread(View): def get(self, request, *args, **kwargs): form = ThreadForm() context = { 'form': form } return render(request, 'create_thread.html', context) def post(self, request, *args, **kwargs): form = ThreadForm(request.POST) username = request.POST.get('username') try: receiver = User.objects.get(username=username) if ThreadModel.objects.filter(user=request.user, receiver=receiver): thread = ThreadModel.objects.filter(user=request.user, receiver=receiver)[0] return redirect('thread', pk=thread.pk) elif ThreadModel.objects.filter(user=receiver, receiver=request.user).exists(): thread = ThreadModel.objects.filter(user=receiver, receiver=request.user)[0] return redirect('thread', pk=thread.pk) if form.is_valid(): thread = ThreadModel( user=request.user, receiver=receiver ) thread.save() return redirect('thread', pk=thread.pk) except: return redirect('create-thread') Code in modules: class ThreadModel(models.Model): user = models.ForeignKey(AppUser, on_delete=models.CASCADE, related_name='+') receiver = models.ForeignKey(AppUser, on_delete=models.CASCADE, related_name='+') class MessageModel(models.Model): thread = models.ForeignKey('ThreadModel', related_name='+', on_delete=models.CASCADE, blank=True, null=True) sender_user = models.ForeignKey(AppUser, on_delete=models.CASCADE, related_name='+') receiver_user = models.ForeignKey(AppUser, on_delete=models.CASCADE, related_name='+') body = models.CharField(max_length=1000) date = models.DateTimeField(default=timezone.now) -
What processes affect performance django/ajax
I have a process in my django application that is painfully slow. It does involve a database write and I have tested it on sqlite and mysql and the results are the same. I am happy working at the high level of django and javascript, but have no understanding of the underlying interaction of these packages with the os. The process is complex and I cannot give a minimal working example, but I have timed some parts of the process and I cannot reconcile what is happening. In my javascript I have the following code function saveMessage(text) { if (text) { var t0 = performance.now(); $.ajax( { type:"GET", url: "save-message/"+text, cache: false, success: function(context) { var t1 = performance.now() console.log("Elapsed " + (t1 - t0) + " msec.") ... } } ) } } This process takes on average 2.7 seconds (which is unacceptable) In my django view I have class SendMessage(View): @staticmethod def get(request, text): message = Message(request.user.pk, text) t1_start = process_time() message.save() t1_stop = process_time() print("save:", t1_stop - t1_start) return JsonResponse(context, safe=False) message is a django model and is not onerous in its requirements. This save takes on average 0.038 seconds However, if I comment out the save, … -
Video doesn't display (Django)
Here is the HTML code: {% load static %} <img src="{% static 'images/image.jpg' %}"> <video src="{% static 'images/video.mov' %}"></video> The image displays properly, but I cannot see the video... What to do??? -
Django Query Time Lookup That's TZ Aware?
I'm just trying to get all songs with a datetime (stored in the DB as UTC), that occurred during the same month & day each year. That'd be simple without timezones. Since I'm using timezones though, I have to use the time lookup & Django seems to be ignoring the tzinfo part of the time and just returning stuff 'on this day' according to the UTC time. So, something that was first_heard at 10p in 'US/Eastern' will show up on the wrong date. I can't figure out how to make Django check the tzinfo on the time's, and searching for an answer hasn't helped. What am I missing?? In the following code snippet, start & end are tz aware datetimes in the US/Eastern tz. start_time = datetime.time(start.hour,0,0,tzinfo=start.tzinfo) end_time = datetime.time(end.hour,end.minute,end.second,tzinfo=start.tzinfo) otd = Song.objects.filter(first_heard__month=end.month, first_heard__day=end.day, first_heard__time__range=(start_time,endtime), ) I'm using Python 3.x & Django 3.1, on Ubuntu. -
deploying Node.js and Django to same domain/server
Objective: Give my Django App (with Python backend [written] and react/redux/js frontend [written]) a Smartsheet API OAuth page that redirects users off the main website until auth is done, and then back to website (that utilizes Smartsheet API in features) Crux: A hunch said that the OAuth should be in node.js to match front end more, and I found a working sample code for how to do Smartsheet OAuth in Node. It worked great on its own! Then when I tried to integrate this node.js page into Django, I got errors from which ever server I set up second, that there is already a server on that given (12.0.0.1:{port}) local url. Maybe OAuth should be written in python instead, but I couldn't find sample code for it, so it would be great if I could keep it in Node. Question- Is there a way to deploy components from both Node and Django to the same server/domain? It's weird to have users go to one site, finish their oauth, just to be pushed to a totally separate domain. This may also pose security risks. My attempt- I thought I would just create a simple landing page and then after being logged … -
Django REST Framework, display specific foreign key data objects
I'll get straight to my point Here is my API output: In pictures, I need to display objects that have primary_placeholder set to True. I can't find answer on how to do it, I've tried searching in REST Api documentation but nothing seems to work, it always displays every single picture serializers.py: views.py Models.py (Theese two that I'm currently working with) Does anyone know what is the easiest and fastest way to do it? I have absolutely no idea and I've been trying figure it out for about 2 days now. Database currently has no pictures with primary_placeholder set to True if anyone is confused -
problem uploading a django project to AWS
Hello I am trying to put my django's project to AWS. I have done the following things the tutorial (https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html#python-django-configure-for-eb) Mi configuration file django.config is: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebdjango.wsgi:application container_commands: 01_postgresql: command: sudo yum -y install gcc python-setuptools python-devel postgresql-devel 02_postgresql: command: sudo easy_install psycopg2 I create an enviroment (eb create django-env1). Then it says me the following thing when I do (eb status). Environment details for: django-env1 Region: us-west-2 Deployed Version: app-b7ea-210708_181635 Environment ID: e-ax2b7ff3bb Platform: arn:aws:elasticbeanstalk:us-west-2::platform/Python 2.6 running on 64bit Amazon Linux/2.9.15 Tier: WebServer-Standard-1.0 CNAME: django-env1.eba-b3pwjnx2.us-west-2.elasticbeanstalk.com Updated: 2021-07-08 16:19:37.455000+00:00 Status: Ready Health: Green Alert: Your environment is using a retired platform branch. It's no longer supported. I don't know why because I don't why. Thank you -
Using BUKU to create Django bookmark add link
Buku is a great new python library to add bookmarks to browsers. I want create a bookmark link in which I can add my Django website webpage to your bookmarks list. <li class="fa fa-bookmark" style="width:46px; height:46px; color:#b5dce9; padding-right:4px;" aria-hidden="true"></li> <li> I just don't know how to do it: Here is the buku command: $ buku -w 'macvim -f' -a https://www.example.com search engine, privacy The link will have Django objects: "https://www.example.com/{{ city|slugify}}" where city is a django object from views. Any idea how to use buku to create a bookmark for this Django URL? -
How to limit which database objects are rendered in Django admin space
I have a Django app which is used for tracking inventory of products at my company. We have since expanded into multiple locations. Now my goal is to create multiple admin spaces where the products that are shown limited by product location. I have not found any good resources on the best way to do this. Any recommendations would be greatly appreciated! models.py class dboinv_product(models.Model): pk_product_id = models.UUIDField( default = uuid.uuid4, primary_key=True, null=False ) product_creation_time = models.DateTimeField( auto_now_add=True, null=True ) product_name = models.CharField( max_length=50, null=False ) product_description = models.CharField( max_length=500, null=True ) current_cost = models.DecimalField( max_digits=5, decimal_places=2, null = True ) current_qty = models.IntegerField( null=False ) obsolete = models.BooleanField( null=True ) fk_location_name = models.ForeignKey( dboinv_location, verbose_name="Location name", default='Boston', on_delete=models.CASCADE, null=True, blank=True ) Admin.py @admin.register(dboinv_product) class dboinv_productAdmin(admin.ModelAdmin): form = CreateProductForm pass for example if a user were to go to 'Boston/admin', they should only be able to see the products where 'fk_location_name' = 'Boston' NOTE: I want to retain original admin space for myself, but I will make a seperate URL so that the website has no link to it -
Using django-import-export together with django-parler
I'm trying to import and export models using django-import-export while having TranslatedFields from django-parler. Although I explicitly added Description to the Meta fields in ChildInsurancePlanResource it's not showing up when importing items. Name is showing up. I don't know how to make django-import-export recognize those fields and import them as the default language. My admin.py looks like this: class ChildInsurancePlanResource(resources.ModelResource): class Meta: model = InsurancePlan fields = ( "id", "Name", "Description" ) class ChildInsurancePlanAdmin(TranslatableAdmin, PolymorphicChildModelAdmin, ImportExportModelAdmin): resource_class = ChildInsurancePlanResource base_form = TranslatableModelForm base_model = InsurancePlan admin.site.register(ChildInsurancePlan, ChildInsurancePlanAdmin) The model is defined like this: class InsurancePlan(PolymorphicModel): Name = models.CharField(max_length=128) class ChildInsurancePlan(InsurancePlan, TranslatableModel): objects = InsurancePlanManager() translations = TranslatedFields( Description=models.TextField(_("Description"), max_length=5000), ) -
I can't use my customized Django manager methods in nested mode
I'm learning the Django framework and I have a problem with the model managers. Lets look at an example: class PostManager(models.Manager): def sorted(self): return self.order_by('created_at') def published(self): return self.filter(is_public=True) class Post(models.Model): # ... objects = PostManager() # ... The above code is my model and manager implementation. Now, this is my usage: Post.objects.sorted() # ok Post.objects.published() # ok Post.objects.published().filter(...something...) # ok Post.objects.published().sorted() # ERROR Post.objects.sorted().published() # ERROR The errors are AttributeError. Actually, this means what i return in the manager methods has not the same manager properties. What i have to do? -
Python Django error "no module named ..." after manage.py runserver. Did I organize my files correctly?
I'm new to Python and Django. I'm trying to create a user authentication system with Djoser following an online tutorial. I am getting this error "no module named "auth_system"" when I try to run the server to test the connection with Postman. Is it because of the way that I organized the folders that my "auth_system" file is not recognized? Also, is the way that I put all the files into the virtual environment folder correct? -
Django "type object X has no attribute POST"
For some reason, I cannot do this without result in an error. How does TodoForm have no attribute to POST? All the other example shows it's valid. from django.shortcuts import render from .models import Todo from .forms import TodoForm def index(request): return render(request, 'home.html') def todoPanel(request): if request.method == 'POST': form = TodoForm.POST(request.POST) if form.is_valid(): print('steve') else: form = TodoForm() return render(request, 'todo_panel.html', {'form': form}) -
django-q and azure app service. Unable to start backend process in azure app service
I am using django application for my web based application, now to implement async functionality I am using django q package. Using this I have put some functionality behind the user interface and it is working locally. But once code is deployed into the azure app service (Linux plan) it is not working. It is not working because as part of Django-q we have to run the cluster in the backend. It looks like this python manage.py qcluster As I am not able to start the background process in-app service this specific functionality is not working. I have tried to add the custom startup command in app service but nothing is working out. Tried creating a custom shell script and placed it in the /home directory but that is also not working and tried calling the script from startup command but not working. Note :- The application is being deployed to app service via azure devops pipelines. Thanks for your help. -
Error when running collecstatic with Django
I am getting an extremely frustrating error when I run collectstatic on a django project I have. Here is the error: django.core.exceptions.SuspiciousFileOperation: The joined path (/home/carhea/dev-server/CAM-Freiburg/font/roboto/Roboto-Thin.eot) is located outside of the base path component (/home/carhea/dev-server/CAM-Freiburg/staticfiles) I am running this on a Ubuntu 20.4 server using Django 2.2 and python v.3.7 My static settings in settings.py are quite standard... This only recently happened! STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage ' Any help would be greatly appreciated! I also assume that I didn't give enough information :P -
Timer setup with django
I want to create an app for exam room types. I don't know how to set up the timer. An admin can start the timer. but I want to know how I can implement a function where everyone will see the timer going on. like the exam starts at 10 am, so if anyone enters the room at 10.20 am he will see 20 has passed already. can anyone help me with it? any suggestion is appreciable. -
How do I download xlsx file with Django?
I try to make a button for downloading a xlsx file using django. I followed this tutorial https://xlsxwriter.readthedocs.io/example_django_simple.html I have an HTTP response but no download prompt is showing. There is some parts of my code : views.py: def xlsx(request): if request.method == "POST": output = io.BytesIO() workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet("hello") worksheet.write(0,0, 'Client') workbook.close() output.seek(0) filename = 'EdedocBilling.xlsx' response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename) return response index.html <form>...</form> <button type = "button" id = "saveID" onclick = "$.ajax({ type: 'POST', url: 'xlsx', async: false, data: $('form').serialize(), success : console.log(' Success') })"> Generate </button> I remove the part were I process the data since the xlsx file generated works fine (I tested creating the file on the server and it worked). Here is the HTTP response headers: HTTP/1.1 200 OK Date: Thu, 08 Jul 2021 14:47:37 GMT Server: WSGIServer/0.2 CPython/3.8.8 Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet Content-Disposition: attachment; filename="EdedocBilling.xlsx" X-Frame-Options: DENY Content-Length: 5252 X-Content-Type-Options: nosniff Referrer-Policy: same-origin Does somebody has a solution? Thanks ! -
two models issue in django tryung to connect them
i create two model name subject and section if i create a model name maths i want to create some section in it which is one to one so i am trying to load the page of a section acc to the subject like i click on maths link only the section which is relate to math open no other section open i think you understand so here is my code my models.py class Subject(models.Model): name = models.CharField(max_length=80, blank=False,) thumbnail = models.ImageField(upload_to='subject thumbnail', blank = False) total_Section = models.FloatField(default='0') joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Section(models.Model): subject = models.OneToOneField(Subject, on_delete=models.CASCADE) sub_section = models.CharField(max_length=500, blank=True) title = models.CharField(max_length=5000, blank=False) teacher = models.CharField(max_length=500, blank=False) file = models.FileField(upload_to='section_vedios', blank=False) price = models.FloatField(blank=False) content_duration = models.DurationField(blank=False) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title my views.py for subject @login_required def home(request): subject_list = Subject.objects.all() return render (request, 'home.html', {'subject_list': subject_list }) my views.py for sections @login_required def sections(request): return render (request, 'sections.html',) my html for subject it worked <ul> {% for subject in subject_list %} <li class="sub"> <a name='thumb' class="thumb" href="{% url 'subjects:section' %}"><img class="thumbnail" src="{{ subject.thumbnail.url }}" alt=""> <span><strong> {{ subject.name }} </strong> </span> </a> <p>No …