Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to receive a zip file from a HTTP response
Context Summarizing, I have an app that sends some file or JSON to a Django server, the server then process the file and create a new zip file. This zip file have to return to the app. I'm trying to do this with a POST request only, returning the file as a response. I was able to download the file as a response with Postman and I can also see the response I want inside one of the HttpErrorResponse attributes. I also found an answer that was able to do the same, but in Java. Some informations App: made with Ionic v4 | Server: Django 2.24 Front side attempts Main request method: const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Accept': 'application/json', }), requestType: 'application/octet-stream' }; this.http.post("http://127.0.0.1:8000/converter2/", file, httpOptions) .pipe( finalize(() => { loader.dismiss(); }) ) .subscribe(data => { console.log(data['body']); }, error => { console.log(error); console.log(error.error.text) }); Attempts: With the method above I receive this error: Error number 1 -> SyntaxError: Unexpected token P in JSON at position 0 at JSON.parse I'm receiving this error because the http response, by default, is trying to parse the response. I read the documentation of HttpClient, but don't say much about receiving … -
foreign key mismatch - "app_uploadedfiles" referencing "app_uploadedfile"
This question doesn't answer to my problem. Here are my classes: class Person(BaseModel): user = models.OneToOneField(User, related_name='person', on_delete=models.CASCADE) class UploadedFiles(BaseModel): person = models.ForeignKey(Person, null=True, blank=True, default=None, related_name='uploaded_files', on_delete=models.CASCADE) common_directory = models.CharField(max_length=200, default=None, null=True, blank=True) tarball_file = models.ForeignKey(UploadedFile, null=True, blank=True, related_name='tarball_file', default=None, on_delete=models.CASCADE) class UploadedFile(BaseModel): description = models.CharField(max_length=200, default=None, null=True, blank=True,) original_file = models.CharField(max_length=200, default=None, null=True, blank=True,) uploaded_file = models.FileField(default=None, null=True, blank=True,) When, in my code I do this: UploadedFiles.objects.create(person=self.request.user.person) I get this error: sqlite3.OperationalError: foreign key mismatch - "app_uploadedfiles" referencing "app_uploadedfile" Any idea how to solve this? -
Is it possible to override LoginView in function based views, not as a class?
I understand that in order to override from django.contrib.auth.views.LoginView one has to use a subclass Class(LoginView) in views.py. However, in my views.py I only have views declared with def my_view(request) In old versions of Django I could just do from django.contrib.auth.views import login, logout def login_user(request): result = login(request=request, template_name='Market/pages/login.html') return result What's the modern Django equivalent of this? The documentation has this example, that forces me rewrite the whole username/password logic into my view: from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. ... else: # Return an 'invalid login' error message. ... How can I use a view function (not class!) and still have the automatic managing of the submitted request? -
Django - DoesNotExist at /accounts/signup/ - Membership matching query does not exist
I followed a tutorial on how to deploy django2 on pythonanywhere and than I just added the components from my own app. Everything worked fine in development, but after deployment I cant sign in and all media elements are gone. Traceback: Django Version: 2.2.4 Python Version: 3.6.6 Installed Applications: ['todo', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'qsessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'allauth', 'allauth.account', 'allauth.socialaccount', 'courses', 'memberships', 'star_ratings', 'avatar', 'home', 'online_users', 'django.contrib.sites'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'qsessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'online_users.middleware.OnlineNowMiddleware'] File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/views/generic/base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/allauth/account/views.py" in dispatch 214. return super(SignupView, self).dispatch(request, *args, **kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/allauth/account/views.py" in dispatch 80. **kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/allauth/account/views.py" in dispatch 192. **kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch 97. return handler(request, *args, **kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/allauth/account/views.py" in post 103. response = self.form_valid(form) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/allauth/account/views.py" in form_valid 230. self.user = form.save(self.request) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/allauth/account/forms.py" in save 404. adapter.save_user(request, user, self) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/allauth/account/adapter.py" in save_user 243. user.save() File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/contrib/auth/base_user.py" in save 66. super().save(*args, **kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/db/models/base.py" in … -
Django User Registration View -- Best Practice
I need user registration to only be open to users that I approve and I want to minimize the amount of info that users have to input. My current solution is to create a uuid for each user in the django admin (via a unique model that contains other relevant information). Once I have done that I send the user a 'registration link' in the form of: www.oursite.com/accounts/register?c={companyID}&ac={accessCode} Then I use my view to capture those url query parameters and use them to verify create a new user: company = None access_code = None def register(request): # www.lunica.com/accounts/register?c={companyID}&ac={accessCode} global company global access_code initial = {} if request.GET: initial = request.GET.copy() company = initial['c'] access_code = initial['ac'] if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] password = request.POST['password'] password2 = request.POST['password2'] if password == password2: if get_user_model().objects.filter(email=email).exists(): messages.error(request, 'Email is already in use') return redirect('register') else: print(company) if Customer.objects.filter(customer_id=company).exists(): company_access_code = Customer.objects.filter( customer_id=company).values_list( 'access_code', flat=True)[0] if uuid.UUID(str(company_access_code)) == uuid.UUID( str(access_code)): try: company_obj = Customer.objects.get(customer_id=company) except Customer.DoesNotExist: company_obj = None if company_obj != None: user = get_user_model().objects.create_user( email=email, password=password, name=name, customer=company_obj ) auth.login(request, user) messages.success(request, 'You are now logged in') return redirect('index') else: messages.error(request, 'Admin Error (3): Please contact admin.') … -
OperationalError at /admin/news/article/ no such column: news_article.reporter_id
Models.py from django.db import models from django.utils import timezone class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=255, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name class Reporter(models.Model): full_name = models.CharField(max_length=70, db_index=True) def __str__(self): return self.full_name class Article(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) category = models.ForeignKey(Category, related_name='article', on_delete=models.CASCADE) reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) headline = models.CharField(max_length=200) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='article/%Y/%m/%d', blank=True) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft') class Meta: ordering = ('-publish',) def __str__(self): return self.headline I am getting this error while running this code. django.db.utils.IntegrityError: The row in table 'news_article' with primary key '1' has an invalid foreign key: news_article.reporter_id contains a value 'reporter_id' that does not have a corresponding value in auth_user.id. admin.py from django.contrib import admin from .models import Category, Article, Reporter # Register your models here. @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ['name', 'slug'] prepopulated_fields = {'slug': ('name',)} @admin.register(Reporter) class ReporterAdmin(admin.ModelAdmin): list_display = ['full_name'] @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): list_display = ['headline', 'slug', 'reporter', 'created', 'updated'] list_filter = ['headline', 'created', 'updated'] prepopulated_fields = {'slug': ('headline',)} -
How are the directories of a Django Project tree referred to?
Assume you have a directory where you keep all your Django projects: $HOME/Programming/Django_Projects If you in this directory call django-admin startproject blog you'll end up with the following director tree: $HOME/Programming/Django_Projects/blog $HOME/Programming/Django_Projects/blog/blog What's the first blog and whats blog/blog? -
How to customize template in django-oscar?
i want to customize django-oscar template according to my requirement , when i modified the checkout page, i had been encoutred with this error : TemplateSyntaxError at /checkout/thank-you/ Invalid block tag on line 132: 'oscar_thumbnail', expected 'endwith'. Did you forget to register or load this tag? this my settings.py : TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), OSCAR_MAIN_TEMPLATE_DIR ] , # 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.i18n', 'django.contrib.messages.context_processors.messages', 'oscar.apps.search.context_processors.search_form', 'oscar.apps.promotions.context_processors.promotions', 'oscar.apps.checkout.context_processors.checkout', 'oscar.apps.customer.notifications.context_processors.notifications', 'oscar.core.context_processors.metadata', ], 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ], }, }, ] how i can register the templatetag into my custom template in django-oscar? -
Serialize nested models as a keyed JSON object in Django
I have a Django model that has many=True nesting, and I'd like to serializer the nested objects (in Django Rest Framework) as an object instead of a list (which is the default in DRF). Adding many=True serializes things as a list. class PostSerializer(serializers.ModelSerializer): votes = VoteSerializer(many=True) Instead of rendering the votes as a list of objects: [... posts: [{id: 123, user: A}, {id: 456, user: B}, ....] I'd like to render votes as a list of objects keyed by id: [... posts: {123: {user: A}, 456: {user: B}}, ...] -
django models and migrations are not affecting project
I have been stuck on trying to alter a column of one my models. I am able to makemigrations and migrate successfully, and the migration file accurately describes the changes. The problem is that when i try to run my webapp, I get errors from a model schema from before. For example I have a column key. It used to be an integer with null = False. Now i have made a migration changing this key column to a TextField with null = True. The migration file shows the change and models accurately depicts this as well. Now I am getting errors saying that null value in column "key" violates not-null constraint My project is connected to a postgresql backend and this particular model doesn't have a postgres table connected to it. What I have tried: I have tried to delete all migration files in my project and try to start from scratch, but it seems as though it is still using an old schema and have no idea why that is. This is what shows in my migration commands: $ python3.6 manage.py makemigrations kpi Migrations for 'kpi': kpi/migrations/0001_initial.py - Create model Bug - Create model Epic - Create model … -
how to save video and use it like I do with an image
I'm using django and I'm just wondering how to use video. <video class="video-fluid" style="max-width:100%; height: auto;" autoplay loop muted> <source src="https://mdbootstrap.com/img/video/Tropical.mp4" type="video/mp4" /> </video> how do I save video in my directory? where do I save it? in the media folder? and use static to call it like I do with images? -
Django: Form ModelMultipleChoiceField with annotated queryset
I´m trying to make a multiple choice field in a form. Instead of using the full queryset I want to annotate some values. The annotation productos_incluir = ProductosBase.objects\ .filter((Q(region__region__icontains="Argentina") | Q(region__region__icontains="Todas")) & Q(estatus_contenido__id__gt=2))\ .values("marca__marca", "producto", "packaging").annotate(variantes=Sum("producto"))\ .order_by("marca__marca", "producto", "packaging") The form field productos = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=productos_incluir, required=False) The view <div>{{ filter_form.productos }}</div> The result I get the list displayed in the view but I get the "Label" next to the checkbox like this: {'marca__marca': 'Cramer', 'producto': 'Cutter - Shark', 'packaging': 'Bolsa individual', 'variantes': 0.0} My desire What I want is to be able to show the labels without the field info. I guess it has to do with the queryset type change when annotating, but I can´t find how to show this. Cramer | Cutter - Shark Bolsa | individual Thanks in advance! -
redirect to API login page and get back token
I am amateur in web programming and I don't know if my question is stupish: I'm developing an app that uses an API (Trello API) to work and I don't know how to redirect user to Trello login page and and get back token to run my app using his/her account Trello Authorization manual: https://developers.trello.com/page/authorization -
Upload image whit Selenium and Python on Ubuntu 18.04
I have a problem... This is my code: upimage = ActionChains(webdriver).move_to_element( webdriver.find_element_by_class_name("button")) print ('open') sleep(5) upimage.send_keys("/home/user/Image/2.jpg") print ('selected') sleep(5) it open popup for choose file and print "open" after if print "selected" but not select and load any image!!! Whats' wrong? EDIT 1: I try with: upimage.send_keys("/home/user/Image/2.jpg").perform() no effect! -
MultiValueDictKeyError: 'content'
i'm going to make the todo list using django...i did some code...but it throws an multiplevaluekeyerror i tried c = request.POST.get('content', False) but it gives always as False value views.py from django.shortcuts import render from django.http import HttpResponseRedirect from .models import TodoItem # Create your views here. def home(request): return render(request, 'home.html') def work(request): all_todo_items = TodoItem.objects.all() return render(request, 'work.html', {'all_items': all_todo_items}) def addTodo(request): c = request.POST['content'] new_item = TodoItem(content = c) new_item.save() return HttpResponseRedirect('/work/') def deleteTodo(request, todo_id): item_to_delete = TodoItem.objects.get(id=todo_id) item_to_delete.delete() return HttpResponseRedirect('/work/') work.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'css/work.css' %}"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous"> <link rel="icon" href="{% static 'images/list.png' %}" type="image/png"> <title>Tasks</title> </head> <body> <div class="container justify-content-center wrap1"> <div class="text-center heading"> <p><u>write your everyday task here!!!<u></p> </div> </div> <ul style="list-style: none; color: #1b0573; font-weight: bold;" class="text-center"> {% for todo_item in all_items %} <li> <div class="row"> <div class="col-sm-6"> {{ todo_item.content }} </div> <div class="col-sm-2"> {{ todo_item.date_created }} </div> <div class="col-sm-1"> <form action="/deleteTodo/{{ todo_item.id }}" method="post" style="display: inline;"> {% csrf_token %} <div class="form-group"> <button class="btn btn-outline-danger"><i class="fas fa-trash"></i></button> </div> </form> </div> </li> {% endfor %} </ul> <div class="container"> … -
Data not being saved by form in Django
I have this form in Django: class MyForm(forms.ModelForm): key = forms.CharField() secret = forms.CharField() class Meta: model = MyModel fields = ("key", "secret") def save(self, commit=True): send = super(MyForm self).save(commit=False) if commit: send.save() return send And its model: class MyModel(models.Model): key = models.CharField(max_length=200) secret = models.CharField(max_length=200) def save(self): # ALL the signature super(MyModel, self).save() This is the view: def MyView(request): if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): send = form.save(commit=False) send.save() messages.success(request, f"Success") else: form = MyForm() return render(request, "main/template.html", context={"form":form}) URL: path("MyView/", views.MyView, name="MyView"), The problem i keep having, is that the data submitted to the form is not being saved on my Database. When i use the form everything works, i don't get any errors, i get a Success from Django, but nothing happens on my DB. The only errors i'm getting are the following: [2019-08-02 18:22:38,279] log: WARNING - Not Found: /template/... And on Chrome: GET http://127.0.0.1:8000/apis/... 404 (Not Found) -
Automatically filled form in class-based view
I want to automatically fill some form in class-based view and save in database. post function in my view def post(self, request, *args, **kwargs): form_2 = self.form_class_2(self.request.POST) if form_2.is_valid(): keyword = form_2.cleaned_data['keyword'] books = self.search(keyword) if books: for book in books: title = self.add_title(book) form = self.form_class(initial={"title": title, }) if form.is_valid(): form.save() else: return HttpResponseRedirect(reverse_lazy('add_books')) return HttpResponseRedirect(reverse_lazy('import_books')) else: return HttpResponseRedirect(reverse_lazy('index_books')) return reverse_lazy('import_books') Basically I have 2 forms. form 2 is used to input value which is used as argument in my search function. then this search function return .json, then i took some value from this .json and assign to "title" then this title is my input data for form. And everything works fine until part with validation. My form isn't valid but when I print my form before validation part I see that my initial data is in form as expected. -
django can't run exiftool himself
I'm using exiftool in django project but it's seem can't run it . i dont know how i can found why because not any error hapen when i call process is using exiftool . but i think its about permission of users . when i run exiftool -j <image> in terminal all going well and i can see correct result but when i use below code to use exiftool in project ,the result shown me django can't run exiftool : cmd_get_meta = 'exiftool -j "{filename}"'.format(filename=absolute_file_path) process = subprocess.Popen(cmd_get_meta, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) raw_result = process.communicate() meta = json.loads(str(raw_result[0], 'utf-8'))[0] the error is : File "/usr/lib/python3.5/json/decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None so obvious that exiftool -j "{filename}" is not running by django. for more information i should tell this problem appear after i updated exiftool and i'm sure code is correct. django are running by uWSGi and here is user that running exiftool and uwsgi by : $ ps aux | grep uwsgi backend 1243 0.0 0.0 14224 988 pts/9 S+ 14:52 0:00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn uwsgi www-data 20469 0.0 0.7 222664 63984 ? S 2018 32:55 /usr/bin/uwsgi --ini /usr/share/uwsgi/conf/default.ini --ini /etc/uwsgi/apps-enabled/hamclassy.ini … -
Django admin site is changed to normal html
Unfortunately my admin site got changed into a normal html site. I don't how it is happened. Did anyone came-across this problem and overcome of it. Actual result: Expected Result: -
How to display Changed Data in Django With AJAX
Actually am trying to make an cart for my website Now What i am trying to do is using Ajax i want to add and remove the item from my cart Here what i have done so far urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.cart_home, name = 'cart_home'), path('add/<int:product_id>', views.cart_add, name = 'cart_add'), path('delete/<int:product_id>', views.cart_delete, name = 'cart_delete'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And Here is my delete item from cart function in views.py def cart_delete(request, product_id): cart_id = request.session.get('cart_id') cart = Cart.objects.filter(id = cart_id ).first() ###REMOVING PRODUCT FROM CART########## cart.Product.remove(product_id) ################################### # GETTING TOTAL PRICE cart = Cart.objects.filter(id = cart_id).first() if cart is None: pass else: total = 0 for x in cart.Product.all(): total += x.price cart.total = total cart.save() print(total) return HttpResponse('Item Removed') and here is my Cart Model models.py class Cart(models.Model): User = models.ForeignKey(User, blank = True, null = True, on_delete = models.DO_NOTHING) Product = models.ManyToManyField(Product, blank = True,null = True) total = models.IntegerField(blank = True, null=True) sub_total = models.IntegerField(blank = True, null = True) created_at = models.DateField(auto_now=True) and now what i have done so far //Deleting Cart $(document).on('click','.cart_delete',function(e){ e.preventDefault() url = $(this).attr('href'); var p = $(this) $.ajax({ url: url, beforeSend: function(data){ $(".alert").html("<div class='alert alert-success' >Removing</div>") }, success: … -
How can you create an excel from a serialized model in DJANGO REST FRAMEWOK to be consumed (downloaded)
Good afternoon I have a query how I could generate an excel of a serialized model in DJANGO REST FRAMEWORK to be downloaded from a frontend (Angular). This excel I want to have the possibility that it has a filter, for example I want it to only bring me the records that have the P79COL01 equipment column in the property or property, in addition to other filters. My Model Interfaces class Interfaces(models.Model): id_interface=models.PositiveIntegerField(primary_key=True) id_EquipoOrigen=models.ForeignKey(Equipos,on_delete=models.DO_NOTHING,related_name='equipo_origen') id_PuertoOrigen=models.ForeignKey(Puertos,on_delete=models.DO_NOTHING,related_name='puerto_origen',null=True,blank=True) estatus=models.BooleanField(default=False) etiqueta_prtg=models.CharField(max_length=80,null=True,blank=True) grupo=models.PositiveSmallIntegerField(default=0,blank=True) if_index=models.PositiveIntegerField(default=0,blank=True) bw=models.PositiveSmallIntegerField(default=0,blank=True) bw_al=models.PositiveSmallIntegerField(default=0,blank=True) id_prtg=models.PositiveSmallIntegerField(default=0,blank=True) ospf=models.BooleanField(default=False) description=models.CharField(max_length=200,null=True,blank=True) id_EquipoDestino=models.ForeignKey(Equipos,on_delete=models.DO_NOTHING,related_name='equipo_destino') id_PuertoDestino=models.ForeignKey(Puertos,on_delete=models.DO_NOTHING,related_name='puerto_destino') ultima_actualizacion=models.DateTimeField(auto_now=True) class Meta: db_table='Interfaces' My Serializer Model Interfaces class InterfaceSerializer(serializers.ModelSerializer): # Las siguientes lineas me permiten agregan campos de otros modelos al modelo en cuestion que estoty serializando a traves de llaves foraneas. #Se le agrega la propiedad de read_only=True para que el campo no sea editable. EquipoOrigen = serializers.CharField(source='id_EquipoOrigen.nombre',read_only=True) PuertoOrigen = serializers.CharField(source='id_PuertoOrigen.nombre',read_only=True) LocalidadOrigen=serializers.CharField(source='id_EquipoOrigen.localidad',read_only=True) CategoriaOrigen=serializers.CharField(source='id_EquipoOrigen.categoria',read_only=True) EquipoDestino = serializers.CharField(source='id_EquipoDestino.nombre',read_only=True) PuertoDestino = serializers.CharField(source='id_PuertoDestino.nombre',read_only=True) LocalidadDestino=serializers.CharField(source='id_EquipoDestino.localidad',read_only=True) CategoriaDestino=serializers.CharField(source='id_EquipoDestino.categoria',read_only=True) Vendedor=serializers.CharField(source='id_EquipoOrigen.vendedor',read_only=True) class Meta: model=Interfaces fields=('id_interface','id_EquipoOrigen','EquipoOrigen','id_PuertoOrigen','PuertoOrigen','LocalidadOrigen','CategoriaOrigen','Vendedor','estatus','etiqueta_prtg','grupo','if_index','bw','bw_al','id_prtg','ospf','description','id_EquipoDestino','EquipoDestino','id_PuertoDestino','PuertoDestino','LocalidadDestino','CategoriaDestino','ultima_actualizacion',) My ModelViewSet Interfaces class InterfacesViewSet(viewsets.ModelViewSet): queryset=Interfaces.objects.all() serializer_class=InterfaceSerializer pagination_class=PostPageNumberPagination filter_class=InterfacesFilter class PostPageNumberPagination(PageNumberPagination): page_size=10 page_size_query_param = 'page_size' max_page_size = 1000 #Funcion Para El Filtro del Modelo Interfaces. class InterfacesFilter(filters.FilterSet): # Lineas de Codigo para filtrar campos relacionados, es decir campo que estan en el serializador del modelo Interfaces … -
Switching Git branches while running in Docker container causes permission error
I'm running Docker 19 on Windows 10 for development. A container volume binds directly to a Git repo folder and serves the Django app in that folder. I use Mingw-w64 to run Git (aka Git Bash). Occasionally, I'll do the following (or something similar to the following): Request a page served by the Docker container. (To replicate an error, for example.) Switch to a different branch. Request a page served by the Docker container from the new branch. Switch to a different branch. On the last branch switch, Git will freeze for a bit and then say permission denied on a particular file. The file is a difference between the two branches, so Git is trying to change it. Process Explorer tells me the files are used by the system process so the only way to get it to let go is by restarting. My gut is telling me the Django web process (manage.py runserver) is likely locking the file until the request connection is fully closed and is probably lingering as an established connection. Is my gut right? If it is... Why is the lock held by the system process and not Docker? Is there anything to do to … -
HTTPConnectionPool(host=\'0.0.0.0\', port=7000): Max retries exceeded with url (Caused by NewConnectionError
I'm using python to make 2 APIs communicate between them, i made tests and both APIs work fine on their own, the problem arises when i try to send a request to API A (made with flask) so A can pass the data to API B(made with django) and then return the result to A again. When i try to test this endpoint, the response is: HTTPConnectionPool(host='0.0.0.0', port=7000): Max retries exceeded with url: /verify?0 (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fa0b939df50>: Failed to establish a new connection: [Errno 111] Connection refused')) The test file and the manual test fail in this way, if i make a request to API B with the url that API A is making it returns a ok message. I'm thing i missing something about the config in API B, but where? -
Django Please enter the correct username and password for a staff account
I have created the superuser before the deployment of app on Heroku server my domain is gizga.herokuapp.com when u enter gizga.herokuapp.com/admin a Django Admin dashboard comes and then u have to enter the username and password but it shows the following error "Django Please enter the correct username and password for a staff account Note that both fields" even I have created the superuser -
How do I force Django's DateTimeField to always use microseconds
This answer helped me quite a bit, but I am trying to go for something different, and wondering if there is an easy way to do it. I have some data that always needs to have microsecond precision. Currently, I'm just storing it as a BigIntegerField and converting it when needed. However, I would like to store it as a DateTimeField or something similar so I don't have to litter the code with converters. I know Django will preserve this information on our production database, but our tests run using the SQLite DB. It's one of those edge cases, where it shouldn't matter, but I want to try to future-proof the application a bit. Does anyone know if Django has a fallback method or if its fallback is just to throw away the extra information when using databases that don't support that level of precision?