Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
excel export and testing excel file api
i am testing a drf api which takes a excel file as a input . so i want to create a excel workbook with Sheet1 as a name cause my api is written to take that format and after creating the workbook i am saving in my application but im not able give path to it so that my api can take the excel file as input. like the workbook is getting created and it is saved in my application but when im giving its path im getting error. my putput: xls <HttpResponse status_code=200, "application/vnd.ms-excel"> responsefffffffffff <_io.TextIOWrapper name='drftesting1.xls' mode='r' encoding='UTF-8'> fileee E ====================================================================== ERROR: upload_staff_test (accounts.tests.JWTTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/narayana/bin/lets_eduvate/accounts/tests.py", line 376, in upload_staff_test resp_post = client.post('/accounts/teacherexcel/', data=bulk, HTTP_AUTHORIZATION=self.auth, format='json') File "/home/narayana/.local/lib/python3.6/site-packages/rest_framework/test.py", line 300, in post path, data=data, format=format, content_type=content_type, **extra) File "/home/narayana/.local/lib/python3.6/site-packages/rest_framework/test.py", line 212, in post data, content_type = self._encode_data(data, format, content_type) File "/home/narayana/.local/lib/python3.6/site-packages/rest_framework/test.py", line 184, in _encode_data ret = renderer.render(data) File "/home/narayana/.local/lib/python3.6/site-packages/rest_framework/renderers.py", line 105, in render allow_nan=not self.strict, separators=separators File "/home/narayana/.local/lib/python3.6/site-packages/rest_framework/utils/json.py", line 28, in dumps return json.dumps(*args, **kwargs) File "/usr/lib/python3.6/json/__init__.py", line 238, in dumps **kw).encode(obj) File "/usr/lib/python3.6/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python3.6/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) … -
Filtering with multi field in django orm
I have some fields that I can use them for filtering a list. I can use all of this fields or some of them in filter query. MY view is like below. But I can not get a right answer. It means that some records that I expect to have been selected are not selected. class UserListAPIView(ListAPIView): serializer_class = serializers.UserListSerializer pagination_class = AdminPagination permission_classes = (IsAuthRolePermission,) filter_backends = (filters.OrderingFilter,) ordering_fields = '__all__' def get_queryset(self): full_name = self.request.query_params.get('full_name', '') email = self.request.query_params.get('email', '') facility_name = self.request.query_params.get('facility_name', '') user_state = self.request.query_params.get('user_state', '') if full_name or email or facility_name or user_state: queryset = User.objects.filter(full_name__icontains=full_name, email__icontains=email, facility_name__icontains=facility_name, user_state__icontains=user_state) \ .annotate(facility=F('facility_name'), state=F('user_state'), last_access=F('lastAccess')) \ .order_by('-id').distinct() else: queryset = User.objects.all()\ .annotate(facility=F('facility_name'), state=F('user_state'), last_access=F('lastAccess'))\ .order_by('-id') return queryset -
Form errors not displaying in UpdateView
I have an UpdateView that will display a form to either create the user profile or update the user profile. It works well, however, for some reason I can't get it to show the form errors. There should be form errors based on the ValidationErrors I have put in the model form. I suspect my views.py to be the cause of the form not displaying the errors. Here's my view: class ProfileSettings(UpdateView): model = Profile template_name = 'profile/settings.html' form_class = ProfileForm success_url = reverse_lazy('profile:settings') def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) if form.is_valid(): bio = form.cleaned_data['bio'] gender = form.cleaned_data['gender'] avatar = form.cleaned_data['avatar'] Profile.objects.update_or_create(user=self.request.user, defaults={'avatar':avatar, 'bio':bio, 'gender':gender}) return HttpResponseRedirect(self.success_url) -
How to pass an instance ID to an Update view when using Bootstrap Modal in Django?
I started learning Django around 7 months ago and earlier this week I got called in for an internship interview for a software development company and I have to go in and present a challenge on Monday. I have to build a phone catalog website with a basic CRUD and a few other options. Basically just implement a table that displays name, email and phone number, with options to add, remove and update contacts. On my own I decided I wanted to use Bootstrap Modals to handle the add and update templates. This is my Model: class Contacts(models.Model): id = models.AutoField(primary_key=True, unique=True, null=False) name = models.CharField(max_length=100, null=False) address= models.CharField(max_length=150, null=False) phone = models.CharField(max_length=14, null=False) email = models.CharField(max_length=100, null=False) gender = models.CharField(max_length=1, null=False) birth = models.CharField(max_length=10, null=False) And this is my home view: def home(request): #create form form = now_contact_form(request.POST or None) contacts = Contact.objects.all() #edit form edit_form = edit_contact_form(request.POST or None, instance=Contacts) #dictionary data = {'form': form, 'contacts': contacts, 'edit_form': edit_form, } #save if form.is_valid(): contato = form.save(commit=False) contato.save() return redirect('index') if editar_form.is_valid(): editar = editar_form.save(commit=False) editar.save() return redirect('index') return render(request, 'index.html', dados) When I try to run like this, this is what I get. Now, I know the problem … -
django How to create a model value without setting a field's value?
In the table field x is auto-created by database //postgres create table t( id serial primary key x integer default nextval("x-auto-add") ) I had created a serial named 'x-auto-add' and when I exec insert into t(id) values(1) the result is right ,the x field is auto-add by 1. However,when I use restful api by django x = serializers.IntegerField(required=False) x = models.IntegerField(auto_created=True) when I post {"id":4} table t add a record 4,null Help!!!!!!!!!!!!!!!! -
Django executable app built by PyInstaller on Ubuntu can't find static files
I have an following error in running executable app on Ubuntu 18.04 developed based Django-1.8 and converted by PyInstaller3.4. TypeError at /static/css/style.css expected str, bytes or os.PathLike object, not NoneType Request Method: GET Request URL: http://localhost:8000/static/css/style.css Django Version: 1.8 Exception Type: TypeError Exception Value: expected str, bytes or os.PathLike object, not NoneType Exception Location: django/views/static.py in serve, line 54 Python Executable: /home/ksi/Projects/abcalarm/dist/webapp/webapp Python Version: 3.6.7 Python Path: ['/home/ksi/Projects/abcalarm/dist/webapp/base_library.zip', '/home/ksi/Projects/abcalarm/dist/webapp'] Server time: Fri, 1 Feb 2019 15:52:36 +0000 Traceback Switch to copy-and-paste view django/core/handlers/base.py in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ... ▶ Local vars django/views/static.py in serve fullpath = os.path.join(document_root, newpath) ... ▶ Local vars When I run Django source in development environment It runs ok. But the converted app by PyInstaller is not finding static path. -
Why is this form invalid?
the models.py contains 2 classes, class ageGen() and class group1(),which works fine . forms.py from app1.models import ageGen,group1,group2,group3 from django import forms class ageGenForm(forms.ModelForm): class Meta(): model=ageGen fields='__all__' class group1form(forms.ModelForm): class Meta(): model=group1 fields="__all__" what I am trying to do is .. the ageGenForm will accept the age and gender of the player and then it will check weather the player is above 18 years old . if he is below 18 years , then he has to fill up a form specifying his name and the games he wants to participate in and this data is stored in the database . views.py from django.shortcuts import render from app1.forms import ageGenForm,group1form,group2form,group3form from django.http import HttpResponse # Create your views here. def home(request): return render(request,'home.html') def formpage(request): form=ageGenForm() if(request.method=='POST'): form=ageGenForm(request.POST) if(form.is_valid()): age = form.cleaned_data['age'] if(age<=18): return group1(request) else: return HttpResponse("adult category") return render(request,'formpage.html',{'form':form}) def group1(request): form=group1form() if(request.method=='POST'): form=group1form(request.POST) if(form.is_valid()): form.save() return HttpResponse("thankyou!") else: return HttpResponse("invalid") return render(request,'group1.html',{'form':form}) it renders the formpage.html but doesnt render the group1.html . It returns form invalid ! formpage.html and group1.html (same code for both): <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <h1>formpage</h1> <form method="POST"> {% csrf_token %} {{form.as_p}} <input type="submit" name="" value="SUBMIT"> … -
Django, DRF (& React) Foreign key, how to display the name value instead of the foreign key id
There are two Django models - ClientCompany & Proposal and the foreign key of ClientCompany is within the Proposal model. In Proposal how do I display the name of the ClientCompany instead of the foreign key id? models.py: class ClientCompany(models.Model): name = models.CharField("Client Name", max_length=255) abn_acn = models.BigIntegerField("ABN / ACN") def __str__(self): return self.name class Proposal(models.Model): proj_name = models.CharField("Project Name", max_length=255) loc_state = models.CharField( max_length=3, ) proj_type = models.CharField( max_length=30, ) prop_status = models.CharField( max_length=20, ) client = models.ForeignKey(ClientCompany, on_delete=models.CASCADE) oneic = models.ForeignKey( User, on_delete=models.CASCADE, related_name='main_engineer') twoic = models.ForeignKey( User, on_delete=models.CASCADE, related_name='second_engineer') created_at = models.DateTimeField(default=datetime.now) def __str__(self): return self.proj_name serializers.py: class ClientSerializer(serializers.ModelSerializer): class Meta: model = ClientCompany fields = ('id', 'name', 'abn_acn') class ProposalSerializer(serializers.ModelSerializer): class Meta: model = Proposal fields = ('id', 'proj_name', 'loc_state', 'proj_type', 'prop_status', 'client', 'oneic', 'twoic',) queryset api.py: class ProposalViewSet(viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticated, ] queryset = Proposal.objects.all() serializer_class = ProposalSerializer currentlyshows the client foreign key id I've been stuck on this, tried to apply the existing solutions recommended for similar problems but had no luck... if someone can tell me what I'm missing - thanks -
Django/PayPal : How can i retrieve Data from PayPal checkout.js?
i am building an online store for learning purposes and i am using PayPal (Client Integration). i opted for this button right here: https://developer.paypal.com/demo/checkout/#/pattern/buynow Now if You click on VISA or MASTERCARD, you'll get a form that you have to fill in order to complete the purchase. Since i am using PayPal, i am having trouble extracting Customer Data from that form so i can use it for my Order Model. Example with Stripe: billingName = request.POST['stripeBillingName'] <-- Like this billingAddress1 = request.POST['stripeBillingAddressLine1'] billingCity = request.POST['stripeBillingAddressCity'] `billingPostCode = request.POST['stripeBillingAddressZip'] How can i retrieve Data from PayPal checkout.js ? -
How to filter a response in Django
I'm creating a test posts limited to user. i try to get post of user but i don't know how i filter response data. def test_posts_limited_to_user(self): """Test retrieving posts for user""" user2 = get_user_model().objects.create_user('admin@admin.com', 'adminPASS@123') sample_post(user=user2) sample_post(user=self.user) res = self.client.get(POSTS_URL, {'user': self.user.id}) posts = Post.objects.filter(user=self.user) serializer = PostSerializer(posts, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(len(posts), 1) self.assertEqual(res.data, serializer.data) but it return all posts -
How to create nested serializer for extended User module with user_id as foreign key
I'm using django-rest-framework and working on application where I have default User module, then UserProfile to extend it and trying to implement "Favorites" feature and for that reason I added additional table Favorites. So there is my UserProfile module: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... and there is my Favorite module: class Favorite(models.Model): user = models.ForeignKey(User, related_name='user_favorite', on_delete=models.CASCADE) song = models.ForeignKey('Song', related_name='song_favorite', on_delete=models.CASCADE) I plan to add another field to favorites for movies. There is my Serializers: class FavoriteSerializer(serializers.ModelSerializer): class Meta: model = Favorite fields = [ 'user', 'song' ] class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ( "id", "email", "first_name", "last_name", "username", "is_active" ) class UserAuthSerializer(serializers.ModelSerializer): user = UserSerializer(required=True) favorite = FavoriteSerializer(many=True, read_only=True) class Meta: model = UserAuth fields = '__all__' ... I also have some create function in UserAuthSerializer but I don't think that it is relevant in this case. I've tried to put this part favorite = FavoriteSerializer(many=True, read_only=True) into UserSerializer but result is the same. So as you can see I added favorite into UserAuthSerializer and fields should display all fields, but I don't have favorite in my response! There is no error, but it just missing this field my view for this … -
Generate jwt when registering user using djangorestfrfamework-simplejwt
Hi i'm playing with django and djangorestframework-simplejwt and wrote a simple app to register users. Now it seems from reading the documentation and searching online the only way of generating a token is by passing the username, and password to the url url(r'^api/token/$', TokenObtainPairView.as_view(), name='token_obtain_pair'). So it seems i have to create the user first and upon successfully creating the user then send the username, and password again to the url to generate a token. But i want to be able to create a token when the user is created and not have to resend the username and password after user is created. Is there an easier away to generate a jwt when registering a user. -
Django 2.0+ and SQL Server interface question
Why is it necessary to have both Pyodbc and django-pyodbc-azure installed to interface with recent SQL Server versions with Django? Why can't django just use Pyodbc out of the box? -
Firefox SPNEGO Negotiate protocol - multiple connections?
I'm using gssapi/Kerberos authentication in my web application, and I want single sign on via the browser. The problem is, Firefox sends an initial request to the server with no authentication, and receives a 401. But it includes a keep-alive header: Connection: keep-alive If the server respects this keep-alive request, and returns a WWW-Authenticate header, then Firefox behaves correctly and sends the local user's Kerberos credentials, and all is well. But, if the server doesn't keep the connection alive, Firefox will not send another request with the credentials, even though the response has the WWW-Authenticate header. This is a problem because I'm using Django, and Django doesn't support the keep-alive protocol. Is there a way to make Firefox negotiate without the keep-alive? In the RFC that defines the Negotiate extension, there's nothing about requiring that the same connection be re-used. Alternatively, is there a way to make Firefofx preemptively send the credentials on the first request? This is explicitly allowed in the RFC. -
Django - Where to create classes to manipulate database
Where i must create classes in order to manipulate data of the database? I have 4 app in my project. Can i create an app specially for that, and create all the classes/functions in the models.py ? -
Django annotate with multiple tables
Given the models: class Member(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) class MemberAction(models.Model): member = models.ForeignKey(Member, on_delete=models.CASCADE) action = models.CharField(max_length=200) datetime = models.DateTimeField() points = models.IntegerField() class MemberMention(models.Model): member = models.ForeignKey(Member, on_delete=models.CASCADE) date = models.DateTimeField() points = models.IntegerField() I want to get the top five Members with the most combined MemberAction and MemberMention points for a given week. I also want the query to return all of a member's MemberAction rows for the given dates. Any idea how to do this? I got as far as the code below, but the number returned for points_action is incorrect. Oddly enough, when I remove the annotate call for points_news, it works correctly. def index(request): today = timezone.now() week_ago = today - timedelta(7) ma_w_dates = MemberAction.objects.filter(datetime__date__gte=week_ago,datetime__date__lte=today) mention_pts = Sum('membermention__points', filter=Q(membermention__date__date__gte=week_ago,membermention__date__date__lte=today)) action_pts = Sum('memberaction__points', filter=Q(memberaction__datetime__date__gte=week_ago,memberaction__datetime__date__lte=today)) members = Member.objects.annotate(points_actions=action_pts).annotate(points_news=mention_pts).order_by('-points_actions').prefetch_related(Prefetch('memberaction_set', queryset=ma_w_dates))[:5] context = {'members':members} return render(request, 'data/index__text.html', context) -
Migrate a PositiveIntegerField to a FloatField
I have an existing populated database and would like to convert a PositiveIntegerField into a FloatField. I am considering simply doing a migration: migrations.AlterField( model_name='mymodel', name='field_to_convert', field=models.FloatField( blank=True, help_text='my helpful text', null=True), ), Will this require a full rewrite of the database column? How well might this conversion scale for larger databases? In what circumstances would this conversion fail? -
View test in Django failing
I'm following a tutorial: https://simpleisbetterthancomplex.com/series/2017/09/18/a-complete-beginners-guide-to-django-part-3.html I'm running a test, but the error I'm getting is: ERROR: test_board_topics_view_not_found_status_code (boards.tests.BoardTopicsTes ts) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Inetpub\wwwroot\myproject2\myproject2\boards\tests.py", line 31, in t est_board_topics_view_not_found_status_code response = self.client.get(url) File "C:\Inetpub\wwwroot\myproject2\venv_two\lib\site-packages\django\test\cli ent.py", line 527, in get response = super().get(path, data=data, secure=secure, **extra) File "C:\Inetpub\wwwroot\myproject2\venv_two\lib\site-packages\django\test\cli ent.py", line 339, in get **extra, File "C:\Inetpub\wwwroot\myproject2\venv_two\lib\site-packages\django\test\cli ent.py", line 414, in generic return self.request(**r) File "C:\Inetpub\wwwroot\myproject2\venv_two\lib\site-packages\django\test\cli ent.py", line 495, in request raise exc_value File "C:\Inetpub\wwwroot\myproject2\venv_two\lib\site-packages\django\core\han dlers\exception.py", line 34, in inner response = get_response(request) File "C:\Inetpub\wwwroot\myproject2\venv_two\lib\site-packages\django\core\han dlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Inetpub\wwwroot\myproject2\venv_two\lib\site-packages\django\core\han dlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Inetpub\wwwroot\myproject2\myproject2\boards\views.py", line 12, in b oard_topics board = Board.objects.get(pk=pk) File "C:\Inetpub\wwwroot\myproject2\venv_two\lib\site-packages\django\db\model s\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Inetpub\wwwroot\myproject2\venv_two\lib\site-packages\django\db\model s\query.py", line 399, in get self.model._meta.object_name boards.models.Board.DoesNotExist: Board matching query does not exist. ---------------------------------------------------------------------- Ran 5 tests in 0.039s FAILED (errors=1) Destroying test database for alias 'default'... (venv_two) C:\Inetpub\wwwroot\myproject2\myproject2> I'm new to Django and Python and MVC, so I'm confused. tests.py from django.urls import reverse from django.urls import resolve from django.test import TestCase from .views import home, board_topics from .models import Board class HomeTests(TestCase): def test_home_view_status_mode(self): url = reverse('home') response … -
Django Modal with multiple pictures
i'm just trying to make Django display images in modal popup. My problem is, if several images are used, that only the first image is displayed in the modal popup. In the scaled down images that are used as a button, the correct images are displayed. Therefore I do not understand what is wrong here. What should it look like? {% block content %} {% if object.image_count %} <div class="row"> <div class="col-lg-12"> {% for img in object.image_set.all %} {% thumbnail img.file "150x150" crop="center" as im %} <!--a href='{{ img.file.url }}' data-lightbox="lightbox[{{ object.id }}]" title="{{ object.title }}"> <img itemprop="image" src='{{ im.url }}' alt='{{ object.title }}' title='{{ object.title }}' width="{{ im.width }}" height="{{ im.height }}" class="img-rounded"/> </a--> <!-- image trigger modal --> <a data-toggle="modal" data-target="#myModal"> <img src="{{ im.url }}"> </a> <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">{{ object.title }}</h4> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> </div> <div class="modal-body"> <img itemprop="image" src='{{ img.file.url }}' class="img-rounded" style="width:100%"> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> {% endthumbnail %} {% endfor %} </div> </div> {% endif %} {% endblock %} -
No module named PIL in ckeditor_upload inside Docker
I have two Linux environments where I have running django projects. Everything works but now I want to create Docker image but the project is not working because of PIL/Pillow dependency. I know there is a new fork of PIL named Pillow so I added new version of Pillow in Docker file. I also tried version 4.2.1 from one of my other environments but I still get error. Error looks like classic missing package problem: ModuleNotFoundError at / No module named 'PIL' Request Method: GET Request URL: http://localhost/ Django Version: 2.1.5 Exception Type: ModuleNotFoundError Exception Value: No module named 'PIL' Exception Location: /usr/local/lib/python3.6/site-packages/ckeditor_uploader/views.py in <module>, line 14 Python Executable: /usr/local/bin/python Python Version: 3.6.8 Python Path: ['/opt/services/gis-backend/src/gis-backend', '/opt/services/gis-backend/src', '/usr/local/bin', '/usr/local/lib/python36.zip', '/usr/local/lib/python3.6', '/usr/local/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/site-packages'] Server time: Fri, 1 Feb 2019 22:00:24 +0100 ... /usr/local/lib/python3.6/site-packages/ckeditor_uploader/views.py in <module> from PIL import Image My Dockerfile: FROM python:3.6 RUN mkdir -p /opt/services/gis-backend/src WORKDIR /opt/services/gis-backend/src RUN apt-get update &&\ apt-get install -y binutils libproj-dev gdal-bin RUN pip install gunicorn django django-ckeditor django-cors-headers django-dia djangorestframework djangorestframework-gis django-rest-auth django-allauth psycopg2 image RUN pip install Pillow RUN cd /opt/services/gis-backend COPY test.py /opt/services/gis-backend/src RUN python ./test.py # copy our project code COPY . /opt/services/gis-backend/src # expose port 8000 EXPOSE 8000 # … -
How can I upload multiple files in single form at Django?
I have product form, I can upload single file with filefield in form but I need upload multiple files and insert to different relationship file model with my product model. How can I do it with single form? I think I am so close to solving :) I used betterforms module but I couldn't it. model.py from django.db import models from django.db.models import F from ckeditor.fields import RichTextField class ProductImage(models.Model): product_id = models.ForeignKey("Product", on_delete = models.CASCADE, verbose_name = "Product") product_image = models.FileField(upload_to='product_images/') cover_image = models.BooleanField(default=False) upload_date = models.DateTimeField(auto_now_add = True, verbose_name="Upload Date") class Product(models.Model): seller = models.ForeignKey("auth.User", on_delete = models.CASCADE, verbose_name = "Seller") category = models.ForeignKey("Category", on_delete = models.CASCADE, verbose_name = "Category Name") title = models.CharField(max_length = 50, verbose_name="Product Title") size = models.ForeignKey("Size", on_delete = models.CASCADE, verbose_name = "Size") color = models.ForeignKey("Color", on_delete = models.CASCADE, verbose_name = "Color") last_used_date = models.DateTimeField(verbose_name="Last Used Date") description = RichTextField() created_date = models.DateTimeField(auto_now_add = True, verbose_name="Created Date") product_image = models.ManyToManyField("ProductImage", verbose_name = "ProductImages") forms.py from django import forms from .models import Product, Category, Size, Color, Brand, Shipping, Comission, ProductImage from betterforms.multiform import MultiModelForm class ProductForm(forms.ModelForm): class Meta: model = Product fields = ["category","title", "description","price", "income", "active_product",] images = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class ProductImageForm(forms.ModelForm): class Meta: … -
tinys3 not recognizing folder on upload (django) (s3)
My code: csv = pd.read_html(table)[0].to_csv('datasource_files/testtable7.csv',index=False,header=False) conn = tinys3.Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY,endpoint='s3-us-west-2.amazonaws.com/') csv_file=open('datasource_files/testtable7.csv') csv_file=open('datasource_files/testtable7.csv','rb') csv_name= 'datasource_files/testtable7.csv' conn.upload(csv_name,csv_file,'datafix1') ds = DataSource.objects.create(file=csv_name,datatype="CSV",creator=mike, title="title",description="desc") DataSource is a Django model, file is a models.FileField(). Currently, ds.file is http://datafix1.s3-us-west-2.amazonaws.com/datasource_files/testtable7.csv but that file doesn't exist. In order to access the file uploaded I need to go to http://datafix1.s3-us-west-2.amazonaws.com//datasource_files/testtable7.csv (which has an empty directory appended at the beginning of the pathname, because tinys3 is not recognizing the already existing (important) "datasource_files" folder (at least I believe that is the reason, I may be wrong). Can anyone help? Thanks in advance. -
Error: Server Error The server encountered an error and could not complete your request. Please try again in 30 seconds
Estou tentando instalar o Django no Google Cloud. Segui esse tutorial: cloud.google.com/python/django/appengine?hl=pt-br Porém, ao finalizar dá esse erro sempre: `Error: Server Error The server encountered an error and could not complete your request. Please try again in 30 seconds. Quando faço o Deploy, está ok. Veja o Deploy: PORÉM, SEMPRE DÁ O ERRO: Error: Server Error The server encountered an error and could not complete your request. Please try again in 30 seconds. -
I am having trouble linking Css File to Django Template
I just started learning django framework and i tried to add and use static files to design a template(to change the background) of webpage with simple css but my css file doesn't seem to link with html template as the background did not change. I looked up various solutions and it doesn't seem i am doing anything wrong in the code but it still doesn't work. Please look at the code, what could i be missing? Here is the code for the template; {% load staticfiles %} <link rel="stylesheet" type="text/css" href="music/style.css"> {% if all_albums %} <h3>My Albums</h3> <ul> {% for album in all_albums %} <li><a href="{% url 'music:detail' album.id %}">{{album.album_title}}</a></li> {% endfor %} </ul> {% else %} <h3>You don't have any albums</h3> {% endif %} Here is the css; body{ background: white url("images/blackbackground.jpg"); } I expected the background to change but it didn't. The server returned error message "Not Found: /music/music/style.css [01/Feb/2019 12:15:26] "GET /music/music/style.css HTTP/1.1" 404 2559" guys what am i missing? -
from django.urls import path import error: cannot import name path
Hello I'm looking a udemy tutorial and I'm writing the same code as the instructor but I'm having a issue: cannot import name path. I'm using the latest version o django and version 3.6 of python. Here's the code: from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static import jobs.views urlpatterns = [ path('admin/', admin.site.urls), path('', jobs.views.home, name='home'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)