Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError at /update/ 'Personas' object has no attribute 'is_valid'
I have in models from django.db import models # Create your models here. class Personas(models.Model): Nombre = models.CharField(max_length=50) Apellido = models.CharField(max_length=50) Cedula = models.IntegerField() Direccion = models.CharField(max_length=30) Colegio_Electoral = models.IntegerField() Centro_De_Votacion = models.CharField(max_length=50) Sexo = models.CharField(max_length=13) Telefono = models.CharField(max_length=30) Email = models.EmailField(max_length=50) Edad = models.IntegerField() Sector = models.CharField(max_length=50) def __str__(self): return self.Nombre + " " + (self.Apellido) and views def update(request): if request.method == 'POST': form = Personas(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('formulario.html') else: form = Personas() return render(request, 'formulario.html', { 'form':form }) -
NoReverseMatch exception when creating integration test for REST API with Python Django
I've created a REST API accepting a POST request in Django. The request itself works great when calling from a React front end, there should be nothing wrong with the API itself. I want to create integration test for the API. I've written the below test, which is basically copy/paste from the Django Documentation adapted to my API: from django.urls import reverse, path from rest_framework import status from rest_framework.test import APITestCase class SendLoginEmailTest(APITestCase): def test_post_withValidData_loginEmailIsSent(self): url = reverse('send_login_email') data = {'email': 'validemail@email.com', 'token': '4d4ca980-cb0c-425d-8d2c-7e38cb33f38e'} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) I run the test using the command: python3 manage.py test The test fails with the following exception: django.urls.exceptions.NoReverseMatch: Reverse for 'send_login_email' not found. 'send_login_email' is not a valid view function or pattern name. Any ideas what I'm doing wrong? -
Django how to convert FileField & DateTime field to JsonResponse?
I am finally making progress converting some things over to create some api endpoints, with an already existing web app. I have a BuyerForm, and on POST request, everything validates besides the model fields with a DateTime field and FileField. Can anybody assist me with converting that data to a JSON response? if request.method == 'POST': form = BuyerForm(data=json.loads(request.body)) if form.is_valid(): form.save(commit=False) form.buyer = request.user form.disclosures = request.FILES['disclosures'] form.save() data = form.cleaned_data return JsonResponse(data, safe=False) else: data = form.errors.as_json() return JsonResponse(data, status=400, safe=False)``` -
django unique filename extra argument
I want to make my file names unique to prevent collide. image = models.ImageField(upload_to=unique_string_generator, unique=True, blank=True) this is my field. def unique_string_generator(instance: any, filename: str, *, path: str) -> str: """ :param instance: Instance to pass :param filename: filename of the uploaded file :param path: path where to upload :return: where the file will be uploaded """ extension = filename.split('.')[-1] unique_value = uuid.uuid4() filename = f'{unique_value}-{instance.pk}.{extension}' return os.path.join(path, filename) This is my function, how can I pass path='somewhere' to field, because django takes my function as an arguement. A small question, what should be passed for annotation django instance? I just passed instance: any because I couldn't figure out what to annotate? Thanks in advance! -
Django Loop through imputed text from a form
I have the below Django code and I want to be able to loop through the inputted text for name however I do not know the best way to do this. For example in python I have done this by setting the input value as variable and then I can loop through that variable. Is it possible to do that on Django too. Python Code: name = input("Enter name: ").lower() for letter in name: Django HTML code: <form method="post" class="container text-center"> {% csrf_token %} <div> <label for="name">Enter Your Name: </label> <input id ="name" type="text" name='text'> <input type="submit" name="Submit"> </div> </form> <p> {% for letter in "name" %} {% endfor %} <p/> -
launching a django project from a github on my computer with help of visual studio
I have a question about launching a project from a github on my computer. I downloaded this project: https://github.com/justdjango/django-ecommerce Using Visual Studio, first created a new project from existing code, then added the environment (according to the requirements file). But when I start the server, such an error is issued. enter image description here Please tell me what I'm doing wrong. Or the github code itself is not working -
How to deploy simple chatbot (in python,anaconda) in django website?
*enter code here* List itementer link description here -
Queryset - How find a word in foreign key in django?
How find a word in a foreign key? There are classes: class Customers(models.Model): customer = models.CharField(max_length=255, unique=True) order = models.ForeignKey('Order') class Orders(models.Model): orderName = models.CharField(max_length=255) There are these records in Customer and order tables: Order: +-----+------------------+ | id | orderName | +-----+------------------+ | 1 | Apple juice | +-----+------------------+ | 2 | Apple pie | +-----+------------------+ | 3 | Banana juice | +-----+------------------+ | 4 | Banana pie | +-----+------------------+ | 5 | Apple ice cream | +-----+------------------+ | ... | ... | +-----+------------------+ Customer: +-----+----------+-------+ | id | Customer | Order | +-----+----------+-------+ | 1 | A | 2 | +-----+----------+-------+ | 2 | B | 3 | +-----+----------+-------+ | 3 | C | 2 | +-----+----------+-------+ | 4 | G | 1 | +-----+----------+-------+ | 5 | H | 1 | +-----+----------+-------+ | ... | ... | ... | +-----+----------+-------+ I want to get all the records in the customer table that their orders consist of "Apple". I wrote these codes: all_apple_orders = Customer.objects.filter(order='Apple') I got an error message: Field expected a number but got 'Apple'. How should change the code? -
Tempus Datepicker Small Widget Background
I've installed Tempus Dominus Datepicker. But i have problem with the background being too narrow I've search the internets and found that this is supposed to help .bootstrap-datetimepicker-widget.dropdown-menu { width: auto !important; } But i don't understand where to put it (i've only been coding for two weaks). Models class Order(models.Model): timerep = models.FloatField(blank=True, null=True,) Forms class RepairForm(forms.ModelForm): repdate = forms.DateField(widget=DatePicker()) Template {% load bootstrap3 %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title></title> {% bootstrap_css %} {% bootstrap_javascript %} {% load static %} {# Include FontAwesome; required for icon display #} <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css"> {# Include Bootstrap 4 and jQuery #} <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> {# Django Tempus Dominus assets are included in `{{ form.media }}` #} {{ form.media }} </head> <body> <form action="{% url 'mtn:edit_order' order.id %}" method='post'> {% csrf_token %} {{ form.as_p }} <button name="submit" role="button" class="btn btn-primary btn-sm">Save Changes</button> </form> How exactly can i change this argument? Or is there another way to fix it? -
Django OneToMany relation on existing database
I'm working on a legacy database constructing an API, and I need to create some respect some hierarchy that is already in place. The API is meant to be read only, so I'm trying to avoid creating any new table in this cenario. There's a table called regionsubregion that has the idregion and idsubregion I need for creating the relation between Region and SubRegion . I was doing simple ForeingKeys like so: class Region(BaseModel): id_region = models.IntegerField(primary_key=True, db_column="idregion") name = models.CharField(verbose_name="Nome", db_column="description", max_length=80) uf = models.CharField( verbose_name="Unidade Federal", db_column="ufe_sg", max_length=2 ) class SubRegion(BaseModel): id_subregion = models.IntegerField(primary_key=True,db_column='idsubregion') region = models.ForeignKey( "Region", on_delete=models.DO_NOTHING, related_name="subregions" ) name = models.CharField(verbose_name="Nome", db_column="description", max_length=80) The Tables in question are region and subregion. But subregion table has no data related to the id of its parent region, this information is contained in the table regionsubregion, like so: idregion idsubregion 8 3 8 10 8 26 9 23 9 28 9 41 9 8 10 18 Before there was a Many to Many relation between those two, but now it is only 1-to-N (One Region has many Subregions, One subregion is bound to one region only). Since the relation information is in an entirely different table and I'm … -
Upload video on website and keep it secured ? (Django)
For the school project I've been working on, the client asked for video uploading, but due to privacy, they wanted to secure the video to be shown only for signed users. I made the page to be secured, but uploading video was a bit of problem. I was thinking about youtube prvacy enhanced mode, but because various users will be uploading, this wasn't a good way to do. So, I was wondering, Can server / host or webpage handle the size of the videos uploaded by users ? Would html5 video tag be ok for this? Would there be any other good option in this case ? -
Why I am getting pylint error in Django blog? How to solve this issue? Installed pylint. Using VSC Mac
I am a beginner in Django, I am trying to build a basic app by referring a tutorial, after completed the code, getting lots of error related to pylint. Please help me to resolve this issue. Thank you.These are the error -
Why the "?page=" doesn't work after I added the pagination to my django website?
I followed the django documentation and I added the pagination and everything looks fine. Here is how it looks how the pagination looks like. And here is my urls.py file: urlpatterns = [ path('', views.home, name='home'), path('new_search', views.new_search, name='new_search'), ] And here is what I got when I click to the next page or any link in the pagination: IntegrityError at /new_search NOT NULL constraint failed: global_store_app_search.search Request Method: GET Request URL: http://127.0.0.1:8000/new_search?page=2 Django Version: 2.1.2 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: global_store_app_search.search Exception Location: /home/ubuntu/.local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 296 Python Executable: /usr/bin/python3 Python Version: 3.6.9 Python Path: ['/home/ubuntu/Desktop/TunisiaGlobalStoreDjango/global_store_project', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/ubuntu/.local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Thu, 2 Apr 2020 18:08:59 +0000 -
How to upload multiple image in django 3?
i want to upload multiple image using django 3. Here My, **Model:** class Image(models.Model): file = models.ImageField(upload_to='images/') **form:** class UploadForm(forms.Form): images = MultiImageField(min_num=1, max_num=3, max_file_size=1024*1024*5) **Views:** class UploadView(FormView): template_name = 'html/form.html' form_class = UploadForm success_url = '/done/' def form_valid(self, form): for each in form.cleaned_data['images']: Image.objects.create(file=each) return super(UploadView, self).form_valid(form) **urls.py:** path('upload', views.UploadView.as_view(), name="upload"), **Finally form.html:** <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Send" /> </form> But i get error: AttributeError at /upload 'list' object has no attribute 'name' -
Django Role Based Authentication based on Permission on URL instead of Permission on model class
I have studied abut Django Authorization. My observation is basically Django Authentication module works fine for Authorization based on role-based Authentication based on Permission on a Model instance. But In Spring framework I found here same role-based Authentication based on Permission on URL or actually relative URL or URL pattern here like .antMatchers("/user/**").hasRoles("USER", "ADMIN") in following code snippet. Here is a code snippet of Spring Framework: @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/static","/register").permitAll() .antMatchers("/user/**").hasRoles("USER", "ADMIN") // can pass multiple roles .antMatchers("/admin/**").access("hasRole('ADMIN') and hasIpAddress('123.123.123.123')") // pass SPEL using access method .anyRequest().authenticated() .and() .formLogin() .loginUrl("/login") .permitAll(); }``` Is there any way or library in Django Similar way of Spring for Authorization based on Permission on URL? Thanks. -
Django Local Font
I can't connect fonts stored in the static/fonts folder. The path itself django as far as I understand sees, but the font is not loaded on the site static/css/main.css: .container { -webkit-box-sizing: border-box; box-sizing: border-box; font-family: url("../fonts/font-light.ttf"); } -
How to add 'Jinja' extension in Pycharm?
I am trying to install jinja extension in pycharm but somehow I am not able to find it in the pycharm marketplace. Can anyone please help me add 'Jinja' extension in pycharm? Thanks -
Django AssertionError: `update()` did not return an object instance
I want to update my model's deleted field. It's a boolean field. I searched on google and stackoverflow but couldn't find an issue with the same error, strange.. Here is my code: probably my serializer is not working, but I can't find where.. Thanks for your help Django keeps saying: AssertionError: `update()` did not return an object instance. this is my test class: def test_delete_device(self): self.client.force_login(self.admin_user) url = reverse( "admin-device-change-status", kwargs={"device_pk": self.undeleted_device.id} ) response = self.client.patch(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data["deleted"], True) view: class AdminDeletedDeviceView(GenericAPIView): pagination_class = StandardPagination def get_permissions(self): return IsAuthenticated(), IsAdminUser() def get_serializer_class(self): return AdminDeviceChangeStatusSerializer @swagger_auto_schema( responses={ 200: openapi.Response( _("Successfully undeleted the device"), AdminSiteSerializer, ) } ) def patch(self, request, device_pk): """ Undelete device """ device = get_object_or_404(Device, pk=device_pk) serializer_class = self.get_serializer_class() serializer = serializer_class(device, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() if device.deleted == False: device.deleted = True else: device.deleted = False device.save() return Response(serializer.data, status=status.HTTP_200_OK) serializer: class AdminDeviceChangeStatusSerializer(serializers.Serializer): # This method is a method that is needed to override an abstract method in the super class. def create(self, validated_data): # pragma: no cover pass # This method is a method needed to override an abstract method in the super class. def update(self, instance, validated_data): # pragma: no cover pass deleted = … -
Psycopg2 causing ImportError with reason: image not found
I have been running Django and PostgresSQLand have been getting this error when running the migrations: ImportError: dlopen(/Users/tristanwhite/PycharmProjects/Pixel_Pals/venv/lib/python3.7/site-packages/psycopg2/_psycopg.cpython-37m-darwin.so, 2): Library not loaded: @rpath/libssl.1.1.dylib Referenced from: /Users/tristanwhite/PycharmProjects/Pixel_Pals/venv/lib/python3.7/site-packages/psycopg2/_psycopg.cpython-37m-darwin.so Reason: image not found This is using pycharm on a macOS Mojave machine -
override django - oscar payment
I want to save the payment data into admin section of BankCard in Django oscar . I overrided the paypal code like below ,but I get an error , saying : ValueError at /checkout/preview/ The Bankcard could not be created because the data didn't validate. Request Method: POST The Bankcard could not be created because the data didn't validate. How can I override the validation? from oscar.apps.checkout.views import PaymentDetailsView as CorePaymentDetailsView #from .models import PaymentCard as Bankcard from django.shortcuts import redirect from django.shortcuts import render from oscar.apps.payment.forms import BankcardForm from oscar.apps.checkout import views from oscar.apps.payment import forms, models from django.contrib import messages from django.http import HttpResponseRedirect from django.urls import reverse class PaymentDetailsView(CorePaymentDetailsView): template_name = 'paymen_details.html' def get_context_data(self, **kwargs): """ Add data for Paypal Express flow. """ # Override method so the bankcard and billing address forms can be # added to the context. template_name = 'checkout/payment_details.html' ctx = super(PaymentDetailsView, self).get_context_data(**kwargs) ctx['bankcard_form'] = kwargs.get( 'bankcard_form', forms.BankcardForm()) """ ctx['billing_address_form'] = kwargs.get( 'billing_address_form', forms.BillingAddressForm()) """ return ctx def post(self, request, *args, **kwargs): # Override so we can validate the bankcard/billingaddress submission. # If it is valid, we render the preview screen with the forms hidden # within it. When the preview is submitted, … -
Django - request to API in the same project
I have 2 apps in my project. One of them contains the API. The second app sends a request. class PlayLongView(TemplateView): template_name = 'play/homepage.html' def get_price_info(self): url = reverse('myAPI:play_data') return requests.get(url).json() def get_context_data(self, **kwargs): context = super().get_context_data() data = self.get_price_info() context['price'] = data[0]['price'] return context It gives me a mistake: Invalid URL '/myAPI/play_data': No schema supplied. Perhaps you meant http:///myAPI/play_data? Of course I can replace: url = reverse('myAPI:play_data') with a: url = 'http://localhost:8000/myAPI/play_data' and then it works correctly, but my code is "local". How should I write it so that the code also works after host on the server? -
How to access image file that is stored in local machine by clicking on link in a web application using Django?
I am new to django and running into an issue. I am using Django to generate/display test results from python-appium framework. Here I am trying to display a screenshot(saved by the python-appium framework) from my local machine when clicking on a link in dango web application. This is how my HTML page looks This is my code in the template/html file in django. <td><a href="file:///{{ScreenshotLocation}}">Click to view Screenshot</a></td> The variable ScreenshotLocation variable holds the file location(/Users/abc/PycharmProjects/Project1/Screenshots/FileName_timestamp.png The file name is generated dynamically by Python based on timestamp. When I click on the link, nothing happens. The screenshot is not displayed. How can I display the screenshot when clicking on the "Click to view screenshot" link using django? -
How to use pandas fast to_sql method correctly?
Pandas 0.24.0 have a fast implementation to load data into a PostgreSQL database in their website. I copied the method into my django application and use it like so: def insertData(): # download some data into a dataframe df... engine = create_engine('postgresql://user:password@host:port/name') df.to_sql(name='HistData', con=engine, if_exists="append", method=psql_insert_copy) This is how the django model looks like: class HistData(models.Model): """A model representing a stock's data on a specific date""" # Fields stock = models.ForeignKey('Stock', on_delete=models.CASCADE, related_name='histData', null=False) date = models.DateField(verbose_name='Date Correspondence', name='date', null=False) openVal = models.FloatField(verbose_name='Open Value', name='open', null=True) closeVal = models.FloatField(verbose_name='Close Value', name='close', null=True) adjCloseVal = models.FloatField(verbose_name='Adjacent Close Value', name='adjClose', null=True) highVal = models.FloatField(verbose_name='Highest Value', name='high', null=True) lowVal = models.FloatField(verbose_name='Lowest Value', name='low', null=True) volume = models.FloatField(verbose_name='Volume', name='volume', null=True) When I run the application and try to activate the method insertData() I get one of the following errors: either Table "histdata" already exists or relation "histdata" does not exist, however I made sure that the table exists. I have looked through other methods of doing this, mainly from here, and yet I can't seem to make it work. Does anyone know what I'm doing wrong? -
0001_initial migrations Wont Create
So I'm new to django and recently tried to create some migrations for a project. I created the project, created the application name, and set the application name in the Installed apps section in settings. Whenever I run 'python manage.py makemigrations ' it gives me an output of: 'No changes detected in app' Then when i run 'python manage.py migrate' it gives me: Operations to perform: Apply all migrations: (none) Running migrations: No migrations to apply. There is a migrations folder within the application module, it just has an empty 'init.py' file inside. Any suggestions? -
How to SELECT from multiple tables in Django ORM?
I have two tables, oneup_backend_design and Django's default auth_user. First table have following columns (simplified): human_readable_id, manager, worker. Worker column contains a username from auth_user. So I want to get human_readable_id plus first_name and last_name of worker associated with username in one query. In raw SQL it would look like this: SELECT d.human_readable_id, u.first_name, u.last_name FROM oneup_backend_design as d, auth_user as u WHERE d.worker = u.username; I've tried hard reading the docs and Django ORM cookbook, but did not found anything. It's such a simple query, I should be missing something. How one can make it with single database hit?