Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
restore postgreSQL database on Django project
I'm working on an application that runs on Ubuntu 18.04, it consists of Django App and PostgreSQL server, each on runs in a separate Docker container. I created a backup for my database, so I can keep it and runs it on a test server for test cases. Now I'm moving my backup database to another test server, but the problem is when I run: docker-compose -f production.yml up both containers of Django & PostgreSQL run fine, the problem is which should I do first to make everything working on the test server, like everything working on the production server? should I restore backup database first then run: python manage.py migrate or should I migrate then restore backup database, actually I ran both, and each time after successfully end both I got this error: ProgrammingError at /accounts/login/ so what should I do to restore backup database? Anther question: I tried to ignore the backup database and just run: python manage.py migrate and create a database from scratch but I got the same error as before!!! I'm there is something common I'm wrong with, so help me with any information on the theory of backup database, please. -
string indices must be integers while passing ObjectId through URL in Django
I am building a website in django and using mongodb as a database. I want to pass the objectID of mongodb document through url. I am applying the custom filter on it, but I am keep getting this error "string indices must be integers" on 'object|mongo_id' what am I doing wrong? Here is my code: user.html {% load get_id %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <title>Document</title> </head> <body> <nav class="navbar navbar-inverse"> <div style="padding-left: 1200px;" class="container-fluid"> <button class="btn btn-danger navbar-btn"><a href="{% url 'login_view' %}">Log Out</a></button> </div> </nav> <br> <div style="padding-left: 1100px;"> <button type="button" class="btn btn-success"> <a href="{% url 'new_job' object|mongo_id %}">Post Job</a> </button> </div> </body> </html> get_id.py from django import template register=template.Library() @register.filter(name="mongo_id") def mongo_id(value): return str(value['_id']) -
Taggit in list_filter doesn't refresh if any of the tags is deleted in Django
I'm using Taggit for tagging a post in my Django app. I've added list_diplay and list_filter for the Admin model view and both are working. The problem is that if I go and delete a tag as an Admin, the list_filter won't refresh and stop showing that tag. If I add another tag, the list will refresh and work. Admin.py class UploadedAdmin(admin.ModelAdmin): list_display = ('name', 'time_uploaded', 'file', 'tag_list') list_filter = ['time_uploaded', 'tags'] def get_queryset(self, request): return super().get_queryset(request).prefetch_related('tags') def tag_list(self, obj): return u", ".join(o.name for o in obj.tags.all()) # Register your models here. admin.site.register(Uploaded, UploadedAdmin) -
Passing slug into ListView URL
I wanted to pass slug into ListView. But it was not as simple as passing it to DetailView. That's because, ListView doesn't have built-in slug support. I found answer of my question and I want to share with you, guys. -
TypeError when Django authenticate function tries to bind to custom authenticate function
I am attempting to implement an authentication method where: the user submits their email I generate a token for that user that is stored in the database, or I retrieve the token if it already exists I generate a link to log in and email it to the user, with the token as an HTTP parameter The token is extracted from the link and used to search for an active user The user info is passed to the template Note that this isn't for any mission-critical production software - I'm reading the Obey The Testing Goat O'Reilly book and this is the authentication method the author has us implement. So when the user clicks the link in their email, this is the view function that handles it: from django.contrib.auth import authenticate, login def login(request): uid = request.GET.get('uid') user = authenticate(uid=uid) if user is not None: login(request, user) return redirect('/') In that view function, we call the authenticate function that is provided by django.contrib.auth. Here is that function: def authenticate(request=None, **credentials): """ If the given credentials are valid, return a User object. """ for backend, backend_path in _get_backends(return_tuples=True): backend_signature = inspect.signature(backend.authenticate) try: backend_signature.bind(request, **credentials) except TypeError: # This backend doesn't accept … -
Unable to resolve Reverse for 'create_order' with no arguments not found
The issue is already been discussed here... Reverse for 'create_order' with no arguments not found i get an error. django.urls.exceptions.NoReverseMatch but there is nothing mentioned on how to solve the issue. can somebody help? This is code iam getting an error .. dashboard.html <div class="col-md-7"> <h5>LAST 5 ORDERS</h5> <hr> <div class="card card-body"> <a class="btn btn-primary btn-sm btn-block" href="{% url 'create_order' customer.id %}">Create Order</a> <table class="table table-sm"> <tr> <th>Product</th> <th>Date Orderd</th> <th>Status</th> <th>Update</th> <th>Remove</th> </tr> {% for order in orders %} <tr> <td>{{order.product}}</td> <td>{{order.date_created}}</td> <td>{{order.status}}</td> <td><a class="btn btn-sm btn-info" href="{% url 'update_order' order.id %}">Update</a></td> <td><a class="btn btn-sm btn-danger" href="{% url 'delete_order' order.id %}">Delete</a></td> </tr> {% endfor %} </table> </div> // When i remove the link href ( i,.e create order ) then the URL works fine Corresponding views def createOrder(request, pk): #def createOrder(request): OrderFormSet = inlineformset_factory(Customer, Order, fields=('product', 'status'), extra = 10 ) customer = Customer.objects.get(id=pk) formset = OrderFormSet(queryset=Order.objects.none(),instance=customer) if request.method == 'POST': #form = OrderForm(request.POST) formset = OrderFormSet(request.POST,instance=customer) if formset.is_valid(): formset.save() return redirect('/') context = {'formset':formset} return render(request, 'accounts/order_form.html', context) there some one told the create order button is commented, but nothing. This the part of the exception iam getting Tracee Error Internal Server Error: / Traceback (most recent call … -
A Coroutine is returning a coroutine after await
I'm writing tests for a fastAPI on django with an ASGI server (adapted this tutorial). My fastAPI side of the test keeps returning errors and I'm trying in vain to fix it. My need is about creating a user to test the API. @sync_to_async async def _create_user(self, username, email): try: return User.objects.create(username=username, email=email) except Exception as e: await print(e) return None async def setUp(self): task = asyncio.create_task(self._create_user(username="user", email="email@email.com")) self.user = await task Running this test, it turn out that self.user is a coroutine and it's impossible to access the attributes I expect. How to solve this ? -
problem on loading tensorflow models in django website backend in pythonanywhere hsoting
I trained few tensorflow models and saved them using h5 extension.I am trying to load them in django backend in a view.All versions that i use are latest for django,tf and python. models['1'] = load_model("static/car_model.h5",compile=False) models['2'] = load_model("static/model1.h5",compile=False) models['3'] = load_model("static/model2.h5",compile=False) models['4'] = load_model("static/model3.h5",compile=False) models['5'] = load_model("static/model4.h5",compile=False) This code worked for me in testing.BUt when i try to host it in pythonanywhere First i got errors on path as model not found.Later I tried to change path to os.get_dir("static")+modelname.h5 After running it there is a error message saying could not load backend "Error code: 502-backend" I am confused what to change and where is actual problem.please help thanks. -
pdfkit : header containing watermark not repeating
In my Django project, I need to add watermark on all the pages of the pdf document being generated. I initially tried with regular css but ended up getting multiple watermarks per page. To work around it, i created a template only for header and mapped it against a url. my header.html <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <style> #watermark { position: fixed; z-index: 99; opacity: 0.5; top: 300px; } </style> </head> <body> <div id="watermark"> <img src="/media/images/policy_cancel.png" style=" width: 650px; height: 414px;"> </div> </body> </html> in my urls.py re_path(r'^header/$', views.header), I'm passing this as options in pdfkit as follows : _options = { 'cookie': [ ('csrftoken', options.get('csrftoken','none')), ('sessionid', options.get('session_key','none')), ], 'footer-center': 'Page [page] of [topage]', 'footer-right': DOC_VERSION.get(doctype,''), 'footer-font-size': '9', 'header-html': 'http://127.0.0.1:8000/b/header/', } ISSUE : when pdf is generated, the header is getting printed only on the first page and the footer related configurations have been lost. -
How can i get the name of the Foreign Key on Django List View with qyery returns None
I want to display on the page the name of categoria When there is at least one series, I can get the name. Otherwise, it just returns none! I am trying to create a new context variable to pass the categoria name. But I fell I am doing something wrong... and complicated also... Can someone help me to pass the categoria name into template even if there is no series returned? Thanks... Error Displayed DoesNotExist at /categoria/15 Categoria matching query does not exist. Request Method: GET Request URL: http://localhost:8000/categoria/15 Django Version: 3.1 Exception Type: DoesNotExist Exception Value: Categoria matching query does not exist. view.py class CatergoriasSeriesView(ListView): model = Serie template_name = 'categorias_series_of.html' paginate_by = 10 def get_queryset(self): return Serie.objects.filter(categoria=self.kwargs['categoria']) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['cat'] = self.kwargs['categoria'] context['cat_name'] = Categoria.objects.get(categoria=self.kwargs['categoria']) return context models.py class Categoria(models.Model): categoria = models.CharField( max_length=200, verbose_name="Nome da categoria", help_text="colocar aqui o texto de ajuda") class Meta: verbose_name_plural = "Categorias" verbose_name = "categoria" def get_absolute_url(self): return reverse('series_da_categoria', kwargs={'pk': self.pk}) class Serie(models.Model): serie = models.CharField( max_length=200, verbose_name="Série", help_text="colocar aqui o texto de ajuda") categoria = models.ForeignKey( Categoria, default=1, on_delete=models.SET_DEFAULT) HTML template {% if object_list %} {% for serie in object_list %} <div> {% if forloop.first %} <h1 … -
How to reload Django context from JavaScript w/out redirect?
I am developing a dictionary application and a simple bookmark page where bookmarked definitions are displayed. I am using JavaScript to add/remove a definition to/from bookmarks through a button. The button works. However, when I am on the bookmarks page and I press it to remove a definition from my bookmarks, the definition stays there until I reload the page. I would like the definition to disappear as soon as I hit the button through JavaScript. I tried to remove the parentNode of my button (the div for definition) but it looks horrible, and that's not what I am looking for. I am now trying to send an AJAX request to my Django bookmarks view to re-load the context, but so far I haven't been able to do it. Can anybody help? Here is my Javascript code (the ? is where I am stuck): function toggleBookmark(event) { // Get definition id. let id = event.target.id.split("-")[1]; // Send AJAX request to bookmark view. $.get("/bookmarks/bookmark/" + id, function (data) { if (data.added) { alert('Definition added to your bookmarks.') event.target.innerHTML = 'Remove definition from your Bookmark'; } else if (data.removed) { alert('Definition removed from your bookmarks.') event.target.innerHTML = 'Add definition to your Bookmarks'; … -
sql query don't work in django: "not enough arguments for format string error in django"
I write a SQL query in MySQL and It runs correctly but when I use this query in Django, it runes with error. I delete space of "Title" in the database. When user enter something in the search field, I also delete space in the user text, and then start to search in the database whether the user text contains in title or not. Error: SQL query: Model: # Business (کسب و کار) Model class Business(models.Model): title = models.CharField(verbose_name = 'عنوان', max_length = 255) slug = models.SlugField(verbose_name = 'شناسه', unique = True) FK_CEO = models.ForeignKey(User, verbose_name = 'admin', related_name = 'business_admin_user', on_delete = models.SET_NULL, null = True) description = models.TextField(verbose_name = 'توضیحات', blank = True) createdate = models.DateTimeField(verbose_name = 'تاریخ ثبت', auto_now_add = True) state = models.CharField(verbose_name = 'استان', max_length = 50, blank = True) city = models.CharField(verbose_name = 'شهر', max_length = 50, blank = True) address = models.TextField(verbose_name = 'آدرس', blank = True) FK_Point = models.ManyToManyField('Point', verbose_name = 'امتیازات', related_name = 'business_point', blank = True) FK_Comment = models.ManyToManyField('Comment', verbose_name = 'نظرات', related_name = 'business_comment', blank = True) phone = models.CharField(verbose_name = 'شماره تماس', max_length = 11, blank = True) support_number = models.CharField(verbose_name = 'شماره تماس پشتیبانی', max_length = 11, … -
ValueError: Field 'id' expected a number but got 'choice'
please help when I execute python manage.py migrate I get this error Traceback: (FM) C:\projects\AM\FM\mysite>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, polls, sessions Running migrations: Applying polls.0009_auto_20200914_1002...Traceback (most recent call last): File "C:\projects\AM\FM\lib\site-packages\django\db\models\fields_init_.py", line 1774, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'choice' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\projects\AM\FM\lib\site-packages\django\core\management_init_.py", line 401, in execute_from_command_line utility.execute() File "C:\projects\AM\FM\lib\site-packages\django\core\management_init_.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\projects\AM\FM\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\projects\AM\FM\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\projects\AM\FM\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\projects\AM\FM\lib\site-packages\django\core\management\commands\migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "C:\projects\AM\FM\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\projects\AM\FM\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\projects\AM\FM\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\projects\AM\FM\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\projects\AM\FM\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards schema_editor.add_field( File "C:\projects\AM\FM\lib\site-packages\django\db\backends\sqlite3\schema.py", line 328, in add_field self.remake_table(model, create_field=field) File "C:\projects\AM\FM\lib\site-packages\django\db\backends\sqlite3\schema.py", line 189, in remake_table self.effective_default(create_field) … -
Creating Login/Logout View Django REST API
My Question is: How to create a Login and Logout View, were the user is able to Login/Logout? I am using DjangoRestFramework-SimpleJWT, The user is able to obtain a JSONWebToken. Thanks. -
Is it possible to pass a list into includes variables with Django?
I'm trying to create a reusable sub template to use on my pages that's something like this: <div> <h1>{{ heading }}</h1> <p>{{ copy }}</p> <ul> {% for list_item in list %} <li>{{ list_item }}</li> {% endfor %} </ul> </div> But, I'm wondering if it's possible to pass a list into the include? Maybe something like this? {% includes 'template.html' with list="['list_item1', 'list_item2']" %} -
Change Django self describing api
I built an api using django which has a user. class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=100) address = models.CharField(max_length=100) phone = models.CharField(validators=[validate_phone_number], max_length=20) I am using ModelViewSet to automatically generate the crud methods. However, I add two new routes which are login and signup: class ClientViewSet(viewsets.ModelViewSet): queryset = models.Kindergarten.objects.all() serializer_class = serializers.KindergartenSerializer @action(detail=False, methods=['POST'], name='signup') def signup(self, request): return self.create(request) @action(detail=False, methods=['POST'], name='login') def login(self, request): serializer = serializers.UserSerializer(data=request.data) username = request.data['email'] raw_password = request.data['password'] user = authenticate(username=username, password=raw_password) login(request, user) return Response(serializer.data) Then I route like this : router = routers.DefaultRouter() router.register(r'client', views.ClientViewSet) My problem is when I open my documentation I get to fill field that I do not need : How can I better customize the self description view ? Thanks ! -
While defining method for autosaving in CreateView for ManyToMany field Error shows
I have three Models, in third models Foreign Key and ManyToMany fields are linked, which are: Personal_info Models.py class Personal_info(models.Model): gen_choices = ( ("पुरुष", "पुरूष"), ("महिला", "महिला"), ("तेस्रो", "तेस्रो"), ) pinfo_id = models.AutoField(primary_key=True) userid = models.OneToOneField(User, on_delete=models.CASCADE) nfullname = models.CharField(validators=[max_len_check], max_length=128) efullname = models.CharField(validators=[max_len_check], max_length=128) dob_ad = models.DateField() dob_bs = models.DateField() gender = models.CharField(max_length=6, choices=gen_choices) citizen_no = models.CharField(max_length=56) cissue_dist = models.ForeignKey(District, on_delete=models.CASCADE) cissue_date = models.DateField() language = models.CharField(max_length=56) p_district = models.CharField(max_length=56) p_vdc = models.CharField(max_length=56) p_ward = models.CharField(max_length=2) p_city = models.CharField(max_length=56) t_district = models.CharField(max_length=56) t_vdc = models.CharField(max_length=59) t_ward = models.CharField(max_length=2) t_city = models.CharField(max_length=56) telephone = models.BigIntegerField(null=True, blank=True) mobile = models.BigIntegerField() mother_name = models.CharField(validators=[max_len_check], max_length=128) mother_cit = models.CharField(max_length=10, null=True) father_name = models.CharField(validators=[max_len_check], max_length=128) father_cit = models.CharField(max_length=10, null=True) gfather_name = models.CharField(validators=[max_len_check], max_length=128) gfather_cit = models.CharField(max_length=10, null=True) spose_name = models.CharField(validators=[max_len_check], max_length=128, null=True) spose_cit = models.CharField(max_length=10, null=True, blank=True) image = models.FileField(upload_to="photos/", null=True, blank=True) cit_image = models.FileField(upload_to="citizens/") inclu_image = models.FileField(upload_to="inclusions/", null=True) active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager def __str__(self): return str(self.efullname) Educational Models.py class Education(models.Model): edu_id = models.AutoField(primary_key=True) userid = models.ForeignKey(User, on_delete=models.CASCADE) institute = models.CharField(max_length=255, validators=[max_len_check]) board = models.CharField(max_length=128, validators=[max_len_check1]) pexam = models.CharField(max_length=16, choices=exam_choices) faculty = models.CharField(max_length=16, choices=fac_choices) division = models.CharField(max_length=16, validators=[max_len_check2]) tmarks = models.IntegerField() percent = models.FloatField(null=True, blank=True) mainsub … -
Crispy Forms: Align dynamically
I add some forms to my page dynamically - I always start with a name field and add multiple others depending on a database entry in the data field: class ProductModelForm(ModelForm): class Meta: model = Product fields = ("name", "data") def __init__(self, user, *args, **kwargs): super(ProductModelForm, self).__init__(*args, **kwargs) user_layouts = models.Layout.objects.filter(user__id=user.id) all_fields = {} self.helper = FormHelper() self.helper.form_method = 'POST' HTML_SAVE = HTML(f"""<button type="submit" name="submit" value="save">save</button>""") NAME_FIELD = Column(Field('name'), css_class='form-row') self.helper.layout = Layout(NAME_FIELD) DATA = Field("data", type="hidden") for i in range(0,n): tmpField = Column(Field( ...), css_class=...) self.helper.layout.append(tmpField) self.helper.layout.append(HTML_SAVE) Now my problem is, that because of using column I get a new line for every entry - but I actually would like the forms to be aligned more space preserving. But I never know which kind of form I add - could be a MultipleChoiceField, a BooleanField or a simple CharField. Is there a way so cripsy will align the forms for me in the page? I could stop using Column but which other field benefits me most? -
django form validation: field error not displayed
I am lost with form validation and the way to display error messages I have a "customized" form display in my template (displayed field by field) I need validation between 2 fields so I should use clean method If the checkbox is ticked, text input can't be empty I would like to bind a error message to my text field but error message is not displayed... forms.py class CreateForm(forms.Form): def __init__(self, request, *args, **kwargs): super(CreateForm, self).__init__(*args, **kwargs) self.fields["bra_00A_act"] = forms.BooleanField(label = "", required = False) self.fields["bra_00A_lib"] = forms.CharField(label = "", required = False) def clean(self): cleaned_data = super(CreateForm, self).clean() if cleaned_data["bra_00A_act"] and cleaned_data["bra_00A_lib"] == "": raise forms.ValidationError('error') return cleaned_data template html <form id="randomization_settings_form" method="POST" class="post-form"> {% csrf_token %} <input id="new_parameters" type="hidden" name="parameters" value=""> {{ form.non_field_errors }} <table id="table_parametrage" class="table table-hover"> <thead> <tr> <th>Bras A</th> <th>-----</th> </tr> <tr> <td colspan="2"> <div class="fieldWrapper"> {{ form.bra_00A_act.errors }} {{ form.bra_00A_act }} {{ form.bra_00A_lib.errors }} {{ form.bra_00A_lib }} </div> </td> </tr> </thead> </table> ... </form> -
Passing model field as a slug to URL
models.py: class Article(models.Model): title = models.CharField('Title', max_length=99) slug = AutoSlugField(max_length=99, populate_from='title', unique=True) view_counter = models.IntegerField(default=0) topic = models.ManyToManyField('Topic', related_name='articles') country = models.ManyToManyField('Country', related_name='country', blank=True) class Country(models.Model): slug = models.CharField(max_length=50) name = models.CharField(max_length=50) urls.py: urlpatterns = [ path('', ArticlesListView, name='articles-list'), path('api/', ArticlesApiView, name='articles-api'), path('<slug:country>/', ArticlesListView2.as_view(), name='articles-list1'), path('nope/<slug:slug>/', ArticleDetailView.as_view(), name='article-detail'), ] views.py: class ArticlesListView2(ListView): model = Topic template_name = 'articles/articles-list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["topics"] = Topic.objects.values() context["countries"] = Country.objects.values() return context I want to pass manytomany model field to url. When I run this code, I get the page, but with a problem. If I write a value that doesn't exist into URL, it doesn't throw error. It shows it as it exist. How can I pass it? Giving slugfield to manytomany field gives error as well. -
django vote system failing
I am Confused. I am trying to set a vote system for a post in a blog. But Django always sums on the vote posive side, /blog/models.py class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') 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=10, choices=STATUS_CHOICES, default='draft') post_pos = models.IntegerField(default=0) post_neg = models.IntegerField(default=0) objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) /blog/urls.py urlpatterns = [ path('', views.PostListView.as_view(), name='post_list'), path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'), path('<int:post_id>/share/',views.post_share, name='post_share'), path('<int:post_id>/',views.positive_post, name='positive_post'), path('<int:post_id>/',views.negative_post, name='negative_post'), ] blog/views.py def positive_post(request,post_id): obj = Post.objects.get(pk=post_id) obj.post_pos += 1 obj.save() print ('positive') return redirect(obj.get_absolute_url()) def negative_post(request,post_id): obj = Post.objects.get(pk=post_id) obj.post_neg += 1 obj.save() print ('negative') return redirect(obj.get_absolute_url()) template: <p> <a href="{% url 'blog:positive_post' post.id %}"> VOTE UP {{ post.post_pos}} </p> <p> <a href="{% url 'blog:negative_post' post.id %}"> VOTE DOWN {{ post.post_neg}} </p> no matter if I click vote up or vote down always sums in obj.post_pos ???????? thanks to those print('positive), and print('negative') of views.py I know it is always … -
XML-RPC API with Django
I'm trying to create an API with Django using xml-rpc protocol. I actually created some basic examples on Python but when implementing them on Django I started to get lots of issues. I'm following this code, I think it's pretty old but I couldn't find any better tutorial My urls.py: urlpatterns = [ path('xml_rpc', views.rpc_handler), ] This is my django views.py: from xmlrpc.server import SimpleXMLRPCDispatcher from django.http import HttpResponse # Create a Dispatcher; this handles the calls and translates info to function maps #dispatcher = SimpleXMLRPCDispatcher() # Python 2.4 dispatcher = SimpleXMLRPCDispatcher() # Python 2.5 @csrf_exempt def rpc_handler(request): if len(request.POST): response = HttpResponse(mimetype="application/xml") response.write(dispatcher._marshaled_dispatch(request.raw_post_data)) else: response = HttpResponse() response.write("<b>This is an XML-RPC Service.</b><br>") response.write("You need to invoke it using an XML-RPC Client!<br>") response.write("The following methods are available:<ul>") methods = dispatcher.system_listMethods() for method in methods: sig = dispatcher.system_methodSignature(method) help = dispatcher.system_methodHelp(method) response.write("<li><b>%s</b>: [%s] %s" % (method, sig, help)) response.write("</ul>") response.write('<a href="http://www.djangoproject.com/"> <img src="http://media.djangoproject.com/img/badges/djangomade124x25_grey.gif" border="0" alt="Made with Django." title="Made with Django."></a>') response['Content-length'] = str(len(response.content)) return response def multiply(a, b): return a*b dispatcher.register_function(multiply, 'multiply') This code actually 'works', I mean, I can access the view if I run the server and I can send the Api request from Python with this code: import … -
Django: Pillow seems to install but is not showing in pip freeze
I'm having problems installing Pillow in a venv on AWS Linux. Pillow seems to install correctly but pip freeze doesn't list it and Django runserver fails claiming that PIL is missing. The following console output shows the problem: [root@ip-172-31-25-228 ichiba]# source venv/bin/activate (venv) [root@ip-172-31-25-228 ichiba]# pip freeze asgiref==3.2.10 Django==3.1.1 django-bootstrap-form==3.4 django-crispy-forms==1.9.2 django-filter==2.3.0 django-rest-framework==0.1.0 djangorestframework==3.11.1 pytz==2020.1 sqlparse==0.3.1 (venv) [root@ip-172-31-25-228 ichiba]# pip install Pillow Collecting Pillow Using cached Pillow-7.2.0-cp36-cp36m-manylinux1_x86_64.whl (2.2 MB) Installing collected packages: Pillow Successfully installed Pillow-7.2.0 (venv) [root@ip-172-31-25-228 ichiba]# pip freeze asgiref==3.2.10 Django==3.1.1 django-bootstrap-form==3.4 django-crispy-forms==1.9.2 django-filter==2.3.0 django-rest-framework==0.1.0 djangorestframework==3.11.1 pytz==2020.1 sqlparse==0.3.1 (venv) [root@ip-172-31-25-228 ichiba]# What am I doing wrong? Thanks and regards...Paul -
How to read a file form a Django model FileField
I have the following model in Django: class Batch(CustomModel): product = models.ForeignKey(Product, verbose_name=_("Producto"), on_delete=models.PROTECT, related_name='batchs') start_date = models.DateField(_("Fecha de Inicio"), auto_now=False, auto_now_add=False) due_date = models.DateField(_("Fecha de Vencimiento"), auto_now=False, auto_now_add=False) states = models.ManyToManyField(State, verbose_name=_("Estados")) source_file = models.FileField(_("Archivo de origen"), upload_to=None, max_length=100) class Meta: verbose_name = _("Lote") verbose_name_plural = _("Lotes") def __str__(self): return "[{}]{}/{}/{}".format(self.id, self.product.id, self.start_date, self.due_date) def save(self, *args, **kwargs): super().save(*args, **kwargs) tokens_string = self.source_file.open() tokens = tokens_string.split('\n') print(tokens) As you can see, in method save() I try to print the content of the file being uploaded to field ' source_file`. This is the file being uploaded: file.txt 867670000460 867670000693 867670001445 867670001519 867670001597 When I do print(tokens), I get a single long string: b'867670000460\r\n867670000693\r\n867670001445\r\n867670001519\r\n867670001597\r\n867670002554' I tried to split the string using tokens_string.split('\n'), but I get this error: File "/Users/hugovillalobos/Documents/Code/cinetogoproject/backend/cinetogo/inventory/models.py", line 37, in save tokens = tokens_string.split('\n') TypeError: a bytes-like object is required, not 'str' How can I get each line of the file separated? -
How to rebuild index in elasticsearch for low-memory instance
I'm trying to run python3 manage.py search_index --rebuild -f on my EC2 small instance (+500,000 documents) but the process gets killed as soon as it starts. I tried changing chunk_size, query_pagination, and parallel_indexing but I always get the same error "Killed" or sometimes I get "Memory Error". My question is how can I run this command in small chunks so it doesn't cause this error?