Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter error sub-select returns 2 columns - expected 1
I would like to suggest same post categories on the current page detail So I try the following code: My views : def recipe(request, slug, message=''): post = get_object_or_404(Post, slug=slug) post_category = post.category.all() # get the categories of the post posts_same_category = Post.objects.filter( Q(category__name__icontains= post_category) # filter the same categories of the other posts ).filter(published=True).exclude(slug=slug) # exclude the current post and no publish posts My models : class PostCategory(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=250, null=True, blank=True) category = models.ManyToManyField('PostCategory', blank=True) mealtype = models.ManyToManyField('MealType', blank=True) I have a error on the post detail page : sub-select returns 2 columns - expected 1 I think the problem is with the ManytoManyField but what am I doing wrong ? Thanks in advance for your help ! -
Can I have a field name with spaces in Django Rest Framework?
Is there a way to remap the names of Django Rest Framewok SerializerFields to strings that contain spaces? I have the following sort of code: models.py: class Author(models.Model): author_name = models.CharField() serialisers.py: class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ["author_name"] This will return JSON like: { "author_name": "William Shakespeare" } But I want it to return JSON like: { "The Author": "William Shakespare" } I know that I can use a different name for a serializer field using the source kwarg, but that still requires a valid python name. I'm specifically wondering if I can use a name with spaces in it. Thanks. -
How to use stored procedure or function created in mysql in django?
As I am learning django and MySql , I am creating a web page and want to use PlSql queries like triggers and procedure in my website using django. I have made connection of MySql and django. Can anyone help me how to proceed further. Thank you in advance! -
What is the most efficient way to insert a value into an integer ranked list?
I have a database that has a list of "Experience Levels", using Django Python. Each level comes with a unique rank attribute, which is a positive integer greater than one. The lower value rank is the first skill on a dropdown, and the highest value rank is the last, so a "Senior" with rank 3 is also everything below. I am creating an endpoint to update and insert values into this ranked list but I am having a lot of issues. In order to insert a new value, I need to change everything above the new rank and then insert it in. What is the most efficient way to do this? -
Bootstrap slider animation issue
I'm working with a bootstrap slider and the images are there, they switch every few seconds, almost everything works fine. But it won't display the animation, it's like suddenly it'll change the image. Here's the code: <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> </ol> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-100" src="{% static 'img/slider1.png' %}" alt="First slide"> </div> <div class="carousel-item"> <img class="d-block w-100" src="{% static 'img/slider2.jpg' %}" alt="Second slide"> </div> <div class="carousel-item"> <img class="d-block w-100" src="{% static 'img/slider3.jpg' %}" alt="Third slide"> </div> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> Note: I'm using Django and I loaded {% static %} previously, so that isn't the issue. I also inserted the scripts from bootstrap. -
How to access a specific Wagtail page slug in a template
I have created a number of Wagtail snippets to represent a link to a page and the text to display. E.g. I might want to have a link to Contact us in many many pages, always with the same text that can be edited by the user. models.py @register_snippet class PageLink(models.Model): link_text = models.CharField(max_length=100) related_page = models.ForeignKey( 'wagtailcore.Page', null=True, blank=False, on_delete=models.SET_NULL, related_name='+', ) panels = [ MultiFieldPanel( [ FieldPanel('link_text'), PageChooserPanel('related_page'), ], heading = "Text and page", ) ] def __str__(self): return self.link_text class Meta: verbose_name = "Page link" verbose_name_plural = "Page links" register_snippet(PageLink) templatetags/link_tags.py @register.inclusion_tag("snippets/your_harmony_link.html", takes_context=True) def links(context): return { 'links': PageLink.objects.all(), 'request': context['request'], } your_harmony_link.html {% for link in links %} {{ link.url }} * {{ link.text }} <p> <a href="{{ link.url }}"> {{ link.text }} </a> </p> {% endfor %} I really just want to show one url here but I am looping through them just to sure I have got the model right. When the page is displayed I see all of the links as expected, but I can only see the link.text, not the link.url How can I get the url for a particular link? -
Can I use android studio in place of Pycharm for learning Django .. If No.. why? and if Yes ..how?
I am learning Django and the tutorial requires downloading Pycharm, which looks almost similar to my android studio IDE. So, can I do the same with android studio or I will have to download Pycharm ? -
Django, how to return a file after form submit?
I want to let the user submit a form with some filter criteria and respond with a csv file. This is my code: template: <form action="{% url 'filter_tracks' %}" method="get" id="filter-form"> <various filter params> ... <a class="md-btn" href="javascript:void(0)" onclick="$('#filter-form').submit();" id="csv_btn">Export</a> </form> views.py filename = "TRACKS_EXP{x}_{z}.csv".format(x=int(time.time()), z=lang) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="{x}"'.format(x=filename) response.write(u'\ufeff'.encode('utf8')) writer = csv.writer(response, delimiter=',', dialect='excel', quotechar = "\"", lineterminator='\r\n',) for track in track_list: writer.writerow([...]) return response Although it works, I get the data inside my HTML page and not in a downloadable file. What am I doing wrong? -
Error while migrating Key (Category_id)=(1) is not present in table (after makemigration i put the default value=1 so problem came)
class Category(models.Model): type = models.CharField(max_length=100) def __str__(self): return self.type class Destination(models.Model): category = models.ForeignKey(Category,models.CASCADE) name = models.CharField(max_length=100) img = models.ImageField(upload_to='pics') desc = models.TextField() price = models.IntegerField() offer = models.BooleanField(default = False) sittayma = models.BooleanField(default= True) vid = models.FileField(upload_to='Video') -
How to assign objects in Foreign Keys in DRF?
My model: class Status(models.Model): COURSE_STATUS = ( ('COMPLETED', 'Completed'), ('ASSIGNED', 'Assigned'), ('PROGRESS', 'In progress'), ) course_status = models.CharField(max_length=9, choices=COURSE_STATUS, default='ASSIGNED' ) course_completion_date = models.DateField(blank=True, null=True, ) course = models.ForeignKey(TrainingCourse, on_delete=models.CASCADE, related_name="courses") user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="students") Serializer: class AssignUserSerializer(serializers.ModelSerializer): class Meta: model = Status fields = '__all__ View: class StatusView(ModelViewSet): serializer_class = AssignUserSerializer queryset = Status.objects.all() permission_classes = [AllUsersProfileOnly, IsAuthenticated] I wanna make POST REQUEST and create and add to some users{id} to specific course such a "id": 35, "course_status": "PROGRESS", "course_completion_date": "2010-09-09", "course": 29, **"user": 3,** "id": 36, "course_status": "PROGRESS", "course_completion_date": "2010-09-09", "course": 29, **"user": 4,** now I got error like "Incorrect type. Expected pk value, received str." if try to send more than one id into user field error from Postman -
Problem in displaying 3 columns in my Django Blogapp....Only one column is shown...Its in masonry grid system
I made a blogapp using Django framework. Iam facing problem in displaying the posts.I want posts to be displayed in 3 columns but its showing in just 1 column...Please help me in editing my code... This is the code: **** {{ post.title }} {{ post.category }} {{post.created_date}} {{ post.text | slice:":200"}} -
SocketIo integration with Django
I have been trying to integrate socketio with Django, And I am getting the following error. [31/Mar/2020 14:50:27] "GET /socket.io/?EIO=3&transport=polling&t=N4n4ds4&b64=1 HTTP/1.1" 200 117 [31/Mar/2020 14:50:27] "POST /socket.io/?EIO=3&transport=polling&t=N4n4dsj&b64=1&sid=9053be92266c46148304c09833b2ebe8 HTTP/1.1" 200 2 Traceback (most recent call last): File "/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/lib/python3.7/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/Users/murali/yourenv/lib/python3.7/site-packages/django/contrib/staticfiles/handlers.py", line 68, in __call__ return self.application(environ, start_response) File "/Users/murali/yourenv/lib/python3.7/site-packages/engineio/middleware.py", line 60, in __call__ return self.engineio_app.handle_request(environ, start_response) File "/Users/murali/yourenv/lib/python3.7/site-packages/socketio/server.py", line 558, in handle_request return self.eio.handle_request(environ, start_response) File "/Users/murali/yourenv/lib/python3.7/site-packages/engineio/server.py", line 377, in handle_request environ, start_response) File "/Users/murali/yourenv/lib/python3.7/site-packages/engineio/socket.py", line 108, in handle_get_request start_response) File "/Users/murali/yourenv/lib/python3.7/site-packages/engineio/socket.py", line 152, in _upgrade_websocket return ws(environ, start_response) File "/Users/murali/yourenv/lib/python3.7/site-packages/engineio/async_drivers/eventlet.py", line 16, in __call__ raise RuntimeError('You need to use the eventlet server. ' RuntimeError: You need to use the eventlet server. See the Deployment section of the documentation for more information. [31/Mar/2020 14:50:27] "GET /socket.io/?EIO=3&transport=websocket&sid=9053be92266c46148304c09833b2ebe8 HTTP/1.1" 500 59 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 52220) Traceback (most recent call last): File "/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 720, in __init__ self.handle() File "/Users/murali/yourenv/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 174, in handle self.handle_one_request() File "/Users/murali/yourenv/lib/python3.7/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: … -
How to deploy bootstrap theme "QuixLab" in django?
I know similar questions have been answered before but believe me this is not replication. I have gone through each and every bit of answer but not able to solve my problem. I am just trying to deploy a bootstrap theme in django. I have done everything, that should be done but still css and jquery is not getting picked up in html forms. Settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] index.html , all links have been set like these: <link href="{% static 'assets/css/lib/font-awesome.min.css' %}" rel="stylesheet"> <link href="{% static 'assets/css/lib/themify-icons.css' %}" rel="stylesheet"> <link href="{% static 'assets/css/lib/menubar/sidebar.css' %}" rel="stylesheet"> <link href="{% static 'assets/css/lib/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'assets/css/style.css' %}" rel="stylesheet"> <script src="{% static 'assets/js/lib/owl-carousel/owl.carousel.min.js' %}"></script> <script src="{% static 'assets/js/lib/owl-carousel/owl.carousel-init.js' %}"></script> <script src="{% static 'assets/js/scripts.js"></script> Everything is in its place but css is not getting picked up while I have seen that all images are getting picked up that means static folder is getting accessed properly. When I see terminal, I finds lines like these: [31/Mar/2020 20:10:44] "GET /static/assets/js/lib/weather/jquery.simpleWeather.min.js HTTP/1.1" 404 1773 [31/Mar/2020 20:10:44] "GET /static/assets/js/lib/weather/weather-init.js HTTP/1.1" 404 1737 [31/Mar/2020 20:10:44] "GET /static/assets/js/lib/owl-carousel/owl.carousel.min.js HTTP/1.1" 404 1764 [31/Mar/2020 20:10:44] "GET /static/assets/js/lib/owl-carousel/owl.carousel-init.js HTTP/1.1" 404 1767 For testing, I deploy another … -
Updating the axis of a highcharts chart object using jquery after inital render (django)
I can seem to figure out a basic question I’ve got a highcharts chart in my django app that is getting loaded in the template. The data for the chart is getting populated via ajax. I’d like to add a button above the chart which if clicked toggles the axis to logarithmic (instead of the default, linear) but I can’t seem to make this work Here’s my code HTML <button id="target" type='button' > switch to log </button> <div id="container1" style="width:100%; height:400px;"></div> Javascript <script> $(document).ready(function() { var chartOptions = { chart: { renderTo: 'container1', type: 'line', }, title: {text: null}, xAxis: {title: {text: null}, labels: {rotation: -45}}, yAxis: {title: {text: 'Item counts'}, type: 'linear', stackLabels: {enabled: true}, }, plotOptions: {column: {dataLabels: {enabled: false}, stacking: 'normal'}}, series: [{}], }; var chartDataUrl = "{% url 'global_trend_chart' %}" ; $.getJSON(chartDataUrl, function(data) { chartOptions.xAxis.categories = data['chart_data']['date']; chartOptions.series[0].name = 'Global counts'; chartOptions.series[0].data = data['chart_data']['item_counts']; var chartA = new Highcharts.Chart(chartOptions); }); $( "#target" ).click(function() { chartA.update({ yAxis: { type: 'logarithmic', } }); }); } ); </script> I appreciate the help -
I can't add a record from the django form into a database
I have this function in views.py file that responsible for adding a record into the Database def add_academy(request,pk): child = get_object_or_404(Child_detail, pk=pk) academic = Academic.objects.get(Student_name=child) form = AcademicForm(request.POST, instance=academic) if form.is_valid(): form.save() return redirect('more',pk=pk) #it will redirect but can't create a new record else: form=AcademicForm() context = { 'academic':academic, 'child':child, 'form':form, } return render(request,'functionality/more/academy/add.html',context) And here is my form.py file class AcademicForm(forms.ModelForm): class Meta: model=Academic fields='Class','Date','Average_grade','Overall_position','Total_number_in_class' labels={ 'Average_grade':'Average Grade', 'Overall_position':'Overall Position', 'Total_number_in_class':'Total Number In Class' } Date = forms.DateField( widget=forms.TextInput( attrs={'type': 'date'} ) ) And here is my model.py file class Academic(models.Model): Student_name = models.ForeignKey(Child_detail,on_delete = models.CASCADE) Class = models.CharField(max_length = 50) Date = models.DateField() Average_grade = models.CharField(max_length = 10) Overall_position = models.IntegerField() Total_number_in_class = models.IntegerField() def __str__(self): return str(self.Student_name) And also this is my template will be used to display form <div class="card-body"> <form action="" method="POST" autocomplete="on"> {% csrf_token %} <div class="form-group"> {{form | crispy}} <input type="submit" value="Save" class="btn btn-primary btn-block"> </form> </div> -
How do I redirect away from the login page, if the user is already logged in and goes to login page in Django?
I'm using built in authentication system of Django 2.1. Example Case: User logs in by providing his credentials, once he is directed to the home page and presses browser's back button he'll land in the login page again. It'll again ask for the credentials but actually the user is already logged in. How do we redirect the user to the home page in this case? -
Slider in django website using bootstrap4 carousel
i want to create a carousel slider in my django website where i could easily add/remove images from my admin panel. <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> </ol> <div class="carousel-inner"> {% for obj in projects %} {% if forloop.first %} <div class="carousel-item active "> {% else %} <div class="carousel-item "> {% endif %} <img class="d-block w-100 h-50" class="h-50 d-inline-block" src="{{ obj.thumbnail.url}}" alt="{{obj.title}}"> </div> {% endfor %} </div> -
django_session table is not found after making migrations?
enter image description here I changed model and deleted migrations, pycache folders as well sqlite db file of the application in the project. then tried python manage.py makemigrations appname python manage.py migrate appname -
issue with rendering chart with django and chart.js
I am learning how to integrate charts in django app with chart.js as well as the rest framework from django and I am running into an issue that I have no clue how to go about. when running the server, I don't any error, simply a blank page and I cannot figure out why my chart is not displaying. Here attached my html page, view.py and urls.py because I think that the issue is somewhere in here! from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, Http404 from .models import top_sellers, Classification, ClassificationSerializer,stock_anormal, stock_negatif, niveau_service from django.views.generic import View from django.http import JsonResponse class HomeView(View): def get(self, request, *args, **kwargs): return render(request, 'dashboard/base.html', {}) def get_classification(request, *args, **kwargs): labels = ["red", "blue"] data = { 'labels' : labels, 'class' : ['AA, A'], 'inventory_dollars' : [12,15]} return JsonResponse(data) {% extends 'dashboard/base.html' %} <script> {% block jquery %} var endpoint= '/class/' var defaultData = [] var labels = ["red", "blue"] $.ajax({ method: "GET", url: endpoint, sucess: function(classification){ labels = data.labels defaultData = data.defaul console.log(data) }, error: function(error_data){ console.log("error") console.log(error_data) } }) var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: '# of … -
Django - Images aren't loading in second app
I got two apps 1. main, 2. contact inside my Django project. Both use the base.html file to get the head and the footer. Inside the footer is a image which perfectly work in the main app but inside the contact app it is not shown, there is no images displayed. I tryed to change the settings but everything was set correct. I implement the static and media root STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' and inside the urls.py I do urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), path('contact/', include('contact.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) If i open the inspector in firefox the path is the right one but the console throws a 404 GET http://localhost:8000/static/media/contact/contact_image.jpg 404 (Not Found) How couldnt it work when the media folder is in the root of the app and the settings are the same in both apps? -
Samesite error in Django app while using Datatables Cloudflare CDN file
Can someone tell me how to resolve the warning/error on my django site? A cookie associated with a cross-site resource at http://datatables.net/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032. 127.0.0.1/:1 A cookie associated with a cross-site resource at http://cloudflare.com/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032. 127.0.0.1/:1 A cookie associated with a cross-site resource at https://cloudflare.com/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032. (index):329 Uncaught ReferenceError: $ is not defined at (index):329 Console Log -
Django merging between two querysets by adding an element from one queryset to the other every nth element
Assume I have in my model "movies" of several types: E.g.: Action, Drama, Fantasy etc... In my template I would like to list the 50 most recent movies (sorted by date). Which is rather straight forward E.g.: Movies.order_by('-date')[0:50] However, I have an additional requirement: I would like to list Action movies (sorted by date) every 3 movies of other types: E.g.: (0) Drama 12/3 (1) Adventure 11/3 (2) Science 10/3 **(3) Action 11/3** (4) Sci-Fi 9/3 (5) Sci-Fi 8/3 (6) Adventure 4/3 **(7) Action 8/3** (8) Drama . . . (50) ... In other words, merge two query sets: movies sorted by date of all movies excluding action movies. movies sorted by date of only actions movies. The new query set (or list?) should be 3 items from the first query set and 1 item from the other query set. -
Visual Studio - Error: Unable to download installation files
I'm following a nice tutorial on hosting Django on Apache, for that I need to install mod_wsgi using pip. This needs c++ 14.0 or higher .. I've been trying to install visual studio community edition and it's tools using the microsoft installer. However, a bugging error keeps chacing me: "Unable to download installation files. Check your internet connection and try again" Now my internet connection is fine, I also did many attempts to restart, and re-download - cmd commands for offline installation and many many attempts. I need help here as It is driving me crazy!:D can anybody please help? all the best -
How to access ForeignKey child model's ID? int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method
i keep getting error: Line number: 1 - int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method' Im trying to access the child models id to sort by the company instance for each store. It works if i upload the data through the child model but trying to do the opposite throws errors? model.py class Parent(models.Model): store = models.IntegerField(primary_key=True) state = models.CharField(max_length=250, blank=True) # pylint: disable=R0903 def __str__(self): return '{}'.format(self.store) class Child(models.Model): id = models.BigIntegerField(primary_key=True) store = models.ForeignKey('Parent', on_delete=models.CASCADE, null=True) company = models.CharField(max_length=250, blank=True) rank = models.IntegerField(blank=True, default='') # pylint: disable=R0903 def __str__(self): return '{}'.format(self.company) admin.py class ParentResource(resources.ModelResource): state = fields.Field(attribute='state', column_name='State') store = fields.Field(attribute='store', column_name='Store') company = fields.Field(attribute='company', column_name='Company', widget=ForeignKeyWidget(Child, 'company')) class Meta: model = Parent import_id_fields = ('store', 'state',) fields = ('store', 'state', 'company',) def before_import_row(self, row, **kwargs): company = row.get('Company') store = row.get('Store') store = Parent.objects.get_or_create(store=store) rank = row.get('Rank') company = Child.objects.get_or_create(store=store[0], company=company, rank=rank, id=id) class ParentAdmin(ImportExportModelAdmin): inlines = [ChildInline] resource_class = ParentResource list_display = ['store', 'state'] class Meta: model = Parent -
Django overwrite header value in request object
I am writing middleware that, when it receives a request containing a header 'foo', modifies its value, before passing the request on. Django makes direct assignment illegal, so these do not work: request.headers['Foo'] = 'bar' request['Foo'] = 'bar' I do have a working solution, but it's a bit hacky: request.headers.__dict__['_store']['foo']=('Foo','bar') Is there a cleaner way of doing it that I've missed?