Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ERROR: ServiceError - Failed to deploy application. on elastic beanstalk django
erorrs while deploying my application version is created in applications version list but not deployed to environment. -
Django pass list of tuples as url parameter
type = [('name1', 'value1'), ('name2', 'value2'), ('name3', 'value')] want to pass above list through url as queryparams. Can not parse it for searching. It returns as string. -
How can I make sms web service on python to send sms to every where?
I want to make a sms service(sms API) on python I don't how can I make this to send sms to every where? -
CloudFoundry: SFTP connection breaks with 'paramiko.ssh_exception.SSHException: Error reading SSH protocol banner'
I have a Django application deployed on CloudFoundry. I am trying to access an SFTP server using pysftp, but I am getting an exception. Below is the screenshot. Surprisingly, this connection was working couple of days back and I am unsure as what must have gone wrong. I am able to connect to the same SFTP instance using pysftp on my local development machine and another application that is deployed on AWS. What could possibly be going wrong here? -
How to send a list of numbers / strings with scrapyd to a spider when using scrapyd.schedule
I'm trying to start my scrapy bot from a Django application and I need to pass in a list of strings and also a list of numbers that the bot requires to function. This is my code in the views.py of my Django application: task = scrapyd.schedule('default', 'arc', settings=settings, numIds=numIds, formOp=formOp) numId is the list of the numbers I need to pass and fromOp is the list of strings I need to pass. I tried extracting them in the scrapy spider file using: kwargs.get('numIds') kwargs.get('formOp') for some reason, it only gives me the first number/string in the list even if I try and send a JSON object. is there a way to pass the entire list through scrapyd? -
Django filtering ManyToMany Field
i have these models on my Django Project class CarBundle(PolymorphicModel): name = models.CharField(_('Bundle Name'), max_length=255) car = models.ManyToManyField( 'cars.car', verbose_name=_('Car'), related_name='car_bundle', ) class Car(TimeStampedModel): name = models.CharField(_('Car Name'), max_length=50) manager = models.ForeignKey( 'cars.Manager', verbose_name=_('Car Manager'), related_name='cars', on_delete=models.CASCADE ) class Manager(models.Model): name = models.CharField(_('Name'), max_length=50) from CarBundle objects im trying to filter by Manager name, how do i do that? i tried adding manager_name on the response, but i get django.core.exceptions.FieldError: Cannot resolve keyword 'manager_name' into field. i also tried this (getting error though) CarBundle.objects.filter(car__manager__name__contains='john doe') Am i missing something? -
Django REST Framework - Django capitalized in `pip3 list`
I'm building an API using Django REST Framework. I'm getting a ModuleNotFoundError: No module named 'django' error when I try to test python3 manage.py. I've been going through the long list of issues it could be (reinstall django, need to add an __init__.py in the root, etc) and someone recommended checking my modules list with pip3 list. Here's what I see: Package Version ------------------- ------- asgiref 3.3.1 dj-database-url 0.5.0 Django 3.1.4 django-filter 2.4.0 django-heroku 0.3.1 djangorestframework 3.12.2 gunicorn 20.0.4 Is there a reason why Django's capitalized? Could that be why it isn't finding it in manage.py? If so, how do I go about fixing it? -
Django - Create a way for a user to upload an image, and display the image on website (Beginner help)
I'm new to Django and would like to create a way for a user to upload a photo to a post, when they are creating the post. Then that photo would also display on the post's individual page. I've been following this very closely: https://djangocentral.com/uploading-images-with-django/ But I cannot seem to get it to work. There isn't an error, but no image displays on either page. On the listing page if I click 'upload' nothing happens. The page stays the same. On the create page to create a listing, I haven't figured out yet how to get the html to work also. Would it be better to put the code for uploading an image, into the function for creating a post? I'm not sure if that might be the issue. Any help is appreciated! views.py for uploading the image: def image_upload_view(request): """Process images uploaded by users""" if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() # Get the current instance object to display in the template img_obj = form.instance return render(request, 'index.html', {'form': form, 'img_obj': img_obj}) else: form = ImageForm() return render(request, 'index.html', {'form': form}) urls.py path('upload/', views.image_upload_view), models.py class Image(models.Model): class Image(models.Model): title = models.CharField(max_length=200) image = models.ImageField(upload_to='images') … -
I'm getting a ImproperlyConfigured error when I run my code
It says that my CreateView is missing a queryset, but I think it doesn't need one. So the form won't appear on the page. In my previous projects it doesn't need a get_queryset function. I tried to find code with the similar error but the cause of those problems where misspells and other syntax error. I am using django 3.1.4 [This is the error][1] Here is my views.py: class AboutView(TemplateView): template_name = "about.html" class PostListView(ListView): model = Post def get_queryset(self): return Post.objects.filter(publish_date__lte=timezone.now()).order_by('-publish_date') class PostDetailView(DetailView): model = Post class PostCreateView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = 'blogapp/post_detail.html' model = Post form_class = PostForm def get_queryset(self): class PostUpdateView(LoginRequiredMixin, UpdateView): login_url = '/login/' redirect_field_name = 'blogapp/post_detail.html' model = Post form_class = PostForm class PostDeleteView(LoginRequiredMixin, DeleteView): model = Post success_url = reverse_lazy('post_list') class DraftListView(LoginRequiredMixin, ListView): login_url = '/login/' redirect_field_name = 'blog/post_list.html' model = Post def get_queryset(self): return Post.objects.filter(publish_date__isnull=True).order_by('create_date') I need urgent help! -
Spyne + Django return Array (json) when same tag have more than one child return only the last
using Spyne + Django return Array (json) when same tag have more than one child return only the last child. example: @ rpc(String, String, _returns=Array(Data_obtenerAccion)) def obtenerAccion(ctx, ORIGEN_ACCION, CODIGO_ACCION): '''same query to get participants and contruct json to response, i dont put the example query becasue also with only json dont work.''' res = [] res.append( { "participantes":{ "participante":{ "name": "Jose" }, "participante":{ "name": "Jose" } } } ) return res How i can return this as complete children?. -
404 Error with Django URL even though it is included in url patterns
Here's the error I'm getting: Page not found (404) Request Method: GET Request URL: http://localhost:8000/bet/4/update Using the URLconf defined in chessbet.urls, Django tried these URL patterns, in this order: admin/ [name='bet-home'] bet/int:pk [name='bet-detail'] bet/int:pk/update/> [name='bet-update'] about/ [name='bet-about'] bet/new/ [name='bet-create'] register/ [name='register'] login/ [name='login'] logout/ [name='logout'] yourprofile/ [name='yourprofile'] ^media/(?P.*)$ The current path, bet/4/update, didn't match any of these. Now from what I see the current path is equivalent to the path I laid out for bet-update. What am I doing wrong here? Here is my urls.py: urlpatterns = [ path('', BetListView.as_view(), name = "bet-home"), path("bet/<int:pk>", BetDetailView.as_view(), name="bet-detail"), path("bet/<int:pk>/update/>", BetUpdateView.as_view(), name="bet-update"), path('about/', views.about, name = "bet-about"), path("bet/new/", BetCreateView.as_view(), name="bet-create") ] Bet detail which does something very similar works fine but bet update does not. Any help would be much appreciated. -
Unable to close flash message in Django
I am developing a sample application using python and Django framework . In this i have shown flash message with cancel [x] icon to close the message using Django Messages Framework in index.html using base.html as (template inheritance). PROBLEM : The problem is although i am able to display the message in index.html , but i cannot cancel it. Below are the code files base.html <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <title>{% block title %}{% endblock title %} Harry Ice Creams</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="#">Harry Ice Creams</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="/">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="/about">About Us</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Services </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="/services">Ice Cream</a></li> <li><a class="dropdown-item" href="#">Waffle</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="#">Shake</a></li> </ul> </li> <li class="nav-item"> <a class="nav-link" href="/contact">Contact Us</a> </li> </ul> <form class="d-flex"> <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success" type="submit">Search</button> … -
django.db.utils.DatabaseError: file is not a database
Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\backends\utils.py", line 82, in _execute return self.cursor.execute(sql) File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 411, in execute return Database.Cursor.execute(self, query) sqlite3.DatabaseError: file is not a database The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\user\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inn er_run self.check_migrations() File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\core\management\base.py", line 459, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\migrations\executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\migrations\loader.py", line 53, in init self.build_graph() File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\migrations\loader.py", line 216, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\migrations\recorder.py", line 77, in applied_migratio ns if self.has_table(): File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\migrations\recorder.py", line 56, in has_table tables = self.connection.introspection.table_names(cursor) File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\backends\base\introspection.py", line 48, in table_na mes return get_names(cursor) File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\backends\base\introspection.py", line 43, in get_name s return sorted(ti.name for ti in self.get_table_list(cursor) File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\backends\sqlite3\introspection.py", line 74, in get_t able_list cursor.execute(""" File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\user\PycharmProjects\myweb\venv\lib\site-packages\django\db\backends\utils.py", line … -
RuntimeWarning: DateTimeField DateClass.date_hour received a naive datetime (2021-01-12 00:00:00) while time zone support is active
Boa noite, estou tentando criar um modelo em django para salvar um DateTimeField, porém apresenta o seguinte erro: RuntimeWarning: DateTimeField DateClass.date_hour received a naive datetime (2021-01-12 00:00:00) while time zone support is active. vi em vários lugares que preciso transformar minha data em ciente do fuso horário, mas não sei como implementar os conceitos que foram apresentados. Alguma dica de como posso resolver essa questão? -
Template class view from URL with variables in it not displaying
I currently am trying to have this class template view render with the variabels in the URL. For example I have http://localhost:8000/confirm/?email=hello@example.com&conf_num=641484032777 as the URL My class view looks like this class Confirm(TemplateView): template_name = 'confirm.html' def get_context(self, request, *args, **kwargs): context = super(Confirm, self).get_context() sub = Newsletter.get(email=request.GET['email']) if sub.conf_num == request.GET['conf_num']: sub.confirmed = True sub.save() context['email'] = request.GET['email'] context['action'] = 'added' else: context['email'] = request.GET['email'] context['action'] = 'denied' return context my urls.py looks like this path('confirm/', views.Confirm.as_view(), name='confirm'), And my confirm.html looks like this <!doctype html> <html> <head> <title> Email Newsletter </title> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> </head> <body> <div class="container"> <div class="col-12"> <h1>Email Newsletter</h1> </div> <div class="col-12"> <p>{{ email }} has been {{ action }}.</p> </div> </div> </body> </html> But for some reason it never displays of updates the email or the action. Any help would be appreciated -
Getting an invalid JWT token when I try to register a django user
trying to figure out why I'm getting an invalid token error given my code below. I'm testing registration and authentication via my API. I create a dummy account and then check my email for the verification link. Everything is working great until I click on the link in the email and receive a 400 bad request and due to my debugging the error is caused by an "Invalid Token". Here is my code: views.py import jwt from django.urls import reverse from django.contrib.sites.shortcuts import get_current_site from django.conf import settings #from rest_framework_simplejwt.views import TokenObtainPairView from rest_framework import generics ,status from rest_framework.response import Response from rest_framework import views from rest_framework.views import APIView from rest_framework_simplejwt.tokens import RefreshToken from rest_framework.permissions import AllowAny from drf_yasg.utils import swagger_auto_schema from drf_yasg import openapi from .models import NewUser from .serializers import RegisterSerializer, EmailVerificationSerializer, LoginSerializer from .utils import ConfirmEmail class CustomUserCreate(generics.GenericAPIView): permission_classes = [AllowAny] serializer_class = RegisterSerializer def post(self, request, format='json'): user = request.data serializer = self.serializer_class(data=user) serializer.is_valid(raise_exception=True) serializer.save() user_data = serializer.data user = NewUser.objects.get(email=user_data['email']) token = RefreshToken.for_user(user).access_token current_site = get_current_site(request).domain relativeLink = reverse('users:email-verify') absurl = 'http://'+current_site+relativeLink+"?token="+str(token) email_body = 'Hi '+user.username + \ ' Use the link below to verify your email \n' + absurl data = {'email_body': email_body, 'to_email': … -
calculate working hours for current week in django
let us consider start time, end time and Break time as def record_working hours(request): records = Records.objects.filter(created_by__client=request.user.client) now = timezone.now() today = timezone.now().date() week_start = today - timedelta(days=(today.weekday())) date_list = [week_start + timedelta(days=x) for x in range(5)] week_last = date_list[-1] working_time = records.filter(date__gte=week_start,date__lte=week_last) for record in records: work_hours = record.start_time - record.end_time - record.break_time return redirect(reverse('record_list')) Hear i need to calculate total working hours for current week but i am getting the error as " type object 'datetime.datetime' has no attribute 'datetime'" and when i print my start time, end time and break time i am getting as start_time = datetime.time(8, 30) end_time = datetime.time(18, 30) break_time = 0.5 -
Get image full url on Django Channel Response
I have created a socket with Django channels that return the serialized data of Category Object. But in the response, there is no full URL(the IP address is not there). This problem is similar to this question Django serializer Imagefield to get full URL. The difference is that I am calling the Serializer from a Consumer(Django Channels). Whereas in the link, Serializer is called from a View. In a Consumer, there is no request object as mentioned in the solution. The Django Channels says that scope in Consumers is similar to request in Views. So how can I get the full image url in this case? -
AttributeError at /tickets/ticket/1/like/ 'str' object has no attribute 'fields'
I have a url that is called when a button is pressed but I am getting an attribute error. The strange thing is I only get the attribute error when I run my app on Heroku, when it is running locally I don't get any errors at all. I have checked and heroku is running my latest code in github so I am really confused as to what is happening here! Traceback: Environment: Request Method: GET Request URL: https://dm-issuetracker.herokuapp.com/tickets/ticket/1/like/ Django Version: 1.11 Python Version: 3.6.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_forms_bootstrap', 'accounts', 'tickets', 'checkout'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware'] Template error: In template /app/templates/base.html, error at line 0 'str' object has no attribute 'fields' 1 : {% load staticfiles %} 2 : 3 : <html> 4 : 5 : <head> 6 : <meta charset="UTF-8"> 7 : <meta name="viewport" content="width=device-width, initial-scale=1.0"> 8 : <meta http-equiv="X-UA-Compatible" content="ie=edge"> 9 : <title>IssueTracker{% block page_title %}{% endblock %}</title> 10 : <link rel="icon" href="media/img/bug.jpg"> Traceback: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/tickets/views.py" in ticket_vote 71. return … -
How do I upload an image and go to the uploaded image page to change the properties of this model?
I have a list of images, there is a button to upload an image. It is necessary to validate the form in two fields and after successful loading they should get to the page of this image. models.py: class Picture(models.Model): url = models.URLField(blank=True, verbose_name='Ссылка на изображение') image = models.ImageField(upload_to='pictures/%Y/%m/%d', width_field='image_width', height_field='image_height', blank=True, verbose_name='Изображение') image_width = models.IntegerField(default=0, blank=True, verbose_name='Ширина изображения') image_height = models.IntegerField(default=0, blank=True, verbose_name='Высота изображения') is_active = models.BooleanField(default=True, verbose_name='Актуальность изображения') created = models.DateField(blank=True, null=True, default=timezone.now, verbose_name='Дата создания записи') updated = models.DateField(blank=True, null=True, default=timezone.now, verbose_name='Дата ред-ия записи') forms.py: class PictureCreateForm(forms.ModelForm): class Meta: model = Picture fields = ('url', 'image') class PictureChangeForm(forms.ModelForm): class Meta: model = Picture fields = ('image_width', 'image_height') urls.py: urlpatterns = [ path('', views.home, name='home'), path('add_picture/', views.add_picture, name='add_picture'), path('picture_detail/<int:id>/', views.picture_detail, name='picture_detail'), # re_path('picture_detail/(?P<id>[0-9]+)/$', views.picture_detail, name='picture_detail') ] views.py: def add_picture(request, id): if request.method == 'POST': form = PictureCreateForm(data=request.POST, files=request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('home:picture_detail')) else: messages.error(request, 'Ошибка, проверьте данные') else: form = PictureCreateForm() return render(request, 'add_picture.html', locals()) def picture_detail(request, id): picture = get_object_or_404(Picture, id=id) new_form = None if request.method == 'POST': form = PictureChangeForm(data=request.POST) if form.is_valid(): new_form = form.save(commit=False) new_form.picture = picture new_form.save() return redirect('home:picture_detail') else: messages.error(request, 'Ошибка, проверьте данные') else: form = PictureChangeForm() return render(request, 'picture_detail.html', locals()) -
JQuery appendTo working fine but not rendering on the page
im doing some ajax function and everything is working well , im adding clients with their custom form and then sending data to a view how give a JsonResponse so the ajax call is working , but when i wanna add the created client with JQuery its show me on the dev tool that the DIV is added but like nothing is showed on the page like its transparant their is my code and thank you for your help : $(document).ready(function(){ var csrfToken = $("input[name=csrfmiddlewaretoken]").val(); $("#btn-submit").click(function() { var serializedData = $("#ClientForm").serialize(); console.log("hey hey clients!"); $.ajax({ url: $("ClientForm").data('url'), data : serializedData, type: 'post', success: function(response) { console.log(response.client.name) console.log($("#ClientList")) var block ='<div class="heading-section animate-box"> <h2>Client </h2> </div> </div> <div class="col-md-12"> <div class="fh5co-blog animate-box"> <div class="inner-post"> <a href="#"><img class="img-responsive" src="images/user.jpg" alt=""><i class="fa fa-user fa-5x" style="margin: 20px;"></i></a> </div> <div class="desc" style="padding-bottom: 2rem;"> <span class="posted_by"></span> <span class="comment"></a></span> <h3>'+ response.client.name +'</h3> <h3>'+ response.client.email +'</h3> <a href="addexercise.html" class="btn btn-success" style="margin-bottom: 1rem; margin-right: 2rem;">Add / Edit Exercises</a></div> <a href="client.html" class="btn btn-warning" style="margin-bottom: 1rem;">View</a> </div> ' var test = '<h2>'+ response.client.name +'</h2>' var card = '<div class="card mt-2" id="taskCard">'+ response.client.name +'<div class="card-body" ></div></div>'; $(block).appendTo("#clientList") $("#clientList").append(test).html(); } }) $("#ClientForm")[0].reset() }); }); <div class="fh5co-herome"> <div class="fh5co-overlay-5"></div> <div class="fh5co-cover" data-stellar-background-ratio="0" style="background-image: url({% … -
Django PayPal pour l’association d’un envoi de mail automatique
Hi everyone I would like to know how you were able to manage once the customer clicks on the paypal payment button in your Django app, I would like to know how you were able to automatically manage sending an email in his mailbox indeed I can already manage the sending of emails automatically for a button button that I created myself but the case where I used the integration of paypal on the client side, I can't do it -
How to serve static files in django 3.1
I'm use django 3.1 when I have the option DEBUG = True in my settings.py the static files are serve fine, but when I use DEBUG = False the static files are not serve I all ready try with this solution: 404 Static file not found - Django In the answer like in de official docs of django use this: from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # ... the rest of your URLconf goes here ... ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) But still doesn´t works. Someone have any idea why still doesn't works. -
Django urls are the same but I want to call different functions
I have the following URLs file: from django.conf.urls import url from .views import get_tickets, ticket_detail, create_or_edit_ticket, ticket_vote, ticket_vote_list urlpatterns = [ url(r'^$', get_tickets, name='get_tickets'), url(r'^(?P<pk>\d+)/$', ticket_detail, name = 'ticket_detail'), url(r'^(?P<pk>\d+)/$', ticket_vote, name = 'ticket_vote'), url(r'^ticket/(?P<pk>[0-9]+)/like/$', ticket_vote_list, name='ticket_vote_list'), url(r'^ticket/(?P<pk>[0-9]+)/like/$', ticket_vote, name='ticket_vote'), url(r'^new/$', create_or_edit_ticket, name = 'new_ticket'), url(r'^(?P<pk>\d+)/edit/$', create_or_edit_ticket, name = 'edit_ticket') ] and I have my views.py file: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth.decorators import login_required from django.shortcuts import render, get_object_or_404, redirect from django.utils import timezone from .models import Ticket from .forms import TicketsForm, TicketCommentForm def get_tickets(request): """ Create a view that will return a list of tickets that were published and render them to 'issuetrackertickets.html' template """ tickets = Ticket.objects.filter(published_date__lte=timezone.now ()) return render(request, "issuetrackertickets.html", {'tickets':tickets}) def ticket_detail(request,pk): """ Create a view that will return a single ticket object based on the ticket id and render it to the 'ticketdetail.html' template """ print("ticket detail") ticket = get_object_or_404(Ticket,pk=pk) ticket.views +=1 ticket.save() # Display comments comments = ticket.ticketcomment_set.all().order_by('comment_date') # Form for adding a comment if request.method == 'POST' and request.POST.get('submit'): comment_form = TicketCommentForm(request.POST, request.FILES) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.author = request.user.username comment.ticket = ticket comment.save() return redirect(ticket_detail, pk=ticket.pk) # Form for upvoting tickets elif request.method == 'POST' … -
Django - Export CSV in ManytoMany Field
How to export the name of category on M2M relationship? I've tried to use .all() but return everything wihout format, so is not useful #---------- class Category(models.Model): name = models.CharField(verbose_name='Name', max_length=254) class SubCategory(models.Model): name = models.CharField(verbose_name='Name', max_length=254) category = models.ManyToManyField(Category, blank=True) #---------- from django.http import HttpResponse import csv def csv_export(request): # Get database information qs = SubCategory.objects.all() # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="export_file.csv"' writer = csv.writer(response) writer.writerow(['name','category']) for rule in qs: writer.writerow(['name','category']) return response