Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need help woth django stripe
I am creating a payment method using stripe. Following tutorial, I was able to send test donation successfully. When I switched to live mode and made a payment. The log showed the payment was succeeded, with status 200 OK. However, on the client side, django return an InvalidRequestError, No such token... (see full message below). Here is the error message: InvalidRequestError at /membership/donate/500/ Request req_XjpOs2GYFxyP9K: No such token: tok_1FVm12LAhXPisFUbODE2xZhe; a similar object exists in live mode, but a test mode key was used to make this request. According to the response body in stripe log, the missing token does exist: { "id": "tok_1FVm12LAhXPisFUbODE2xZhe", "object": "token", "card": { "id": "card_1FVm12LAhXPisFUberAeLysv", "object": "card", "address_city": null, ... "metadata": { }, "name": "myemail@yahoo.com", "tokenization_method": null }, "client_ip": "71.246.224.231", "created": 1571607164, "email": "myemail@yahoo.com", "livemode": true, "type": "card", "used": false } To complete the picture, here is the imported settings parameters: STRIPE_LIVE_MODE True STRIPE_LIVE_PUBLIC_KEY '********************' STRIPE_LIVE_SECRET_KEY '********************' STRIPE_PUBLISHABLE_KEY '********************' STRIPE_SECRET_KEY '********************' STRIPE_TEST_PUBLIC_KEY '********************' STRIPE_TEST_SECRET_KEY '********************' The settings parameters show STRIPE_LIVE_MODE = True, and both public and secret keys are set to the live one with correct spelling. However, the value of my_api_key parameter in api_requester.py was test secret key, and not live secret key as it … -
Why are most of my project's Django files missing from the PyTest Coverage report?
I'm running pytest-cov and pytest-django using tox. I have a very simple tox.ini file with limited omit files. The problem is when I run pytest using tox -e unit, I get a limited Coverage report: ---------- coverage: platform darwin, python 3.7.4-final-0 ----------- Name Stmts Miss Cover Missing ---------------------------------------------------------------------------- components/__init__.py 0 0 100% components/client/__init__.py 0 0 100% components/client/admin.py 27 0 100% components/client/factories.py 57 0 100% components/client/models.py 62 0 100% components/controller/__init__.py 0 0 100% components/controller/admin.py 62 6 90% 96-97, 109-110, 122-123 components/controller/management/__init__.py 0 0 100% components/controller/models.py 107 6 94% 19, 31, 54, 92, 105, 132 components/personal/__init__.py 0 0 100% components/personal/admin.py 24 0 100% components/personal/factories.py 39 0 100% components/personal/models.py 81 16 80% 23, 36, 49, 62, 72, 75-76, 92-104 server/__init__.py 3 0 100% server/celery.py 10 1 90% 30 server/config/__init__.py 1 0 100% server/settings.py 52 0 100% server/test.py 56 33 41% 16-19, 43, 48-49, 63-88, 94-105, 112-115 ---------------------------------------------------------------------------- TOTAL 589 62 89% All of my Django apps under components have many files that should be covered in the report, including apps, serializers, signals, urls, and views (the standard Django structure). Anyone have any idea what I'm missing? Everything I've got in the tox.ini seems to follow pretty much exactly what I've read in the … -
List stay empty
I m trying to use datables js in my code but my page stays empty (no title and no table I tried several modification in code but still stay a blank page with no error message html page: {% extends "baseCRM.html" %} {% load bootstrap4 %} <link rel="stylesheet" type="text/css" href="/static/DataTables/datatables.css"> <script type="text/javascript" charset="utf8" src="/static/DataTables/datatables.js"></script> {% block content %} <table cellpadding="0" cellspacing="0" border="0" id="example"> <thead> <tr><th>Client List</th></tr> </thead> <tbody></tbody> </table> <script type="text/javascript" language="javascript" class="init"> $(document).ready(function() { $('#example').dataTable( { "processing": true, "ajax": { "processing": true, "url": "{% url 'clientListJson' %}", "dataSrc": "" }, "columns": [ { "data": "fields.name" }, { "data": "pk" } ] } ); } ); </script> {% endblock %} views.py: def client_list_json(request): object_list = Client.objects.all().order_by("name") json = serializers.serialize('json', object_list) return HttpResponse(json, content_type='application/json') model.py class Client(models.Model): name = models.CharField(max_length=255,) description = models.CharField(max_length=255,blank=True) address1 = models.CharField("Address line 1",max_length=1024,) address2 = models.CharField("Address line 2",max_length=1024,) zip_code = models.CharField("ZIP / Postal code",max_length=12,) city = models.CharField("City",max_length=1024,) country = models.CharField("Country",max_length=3,choices=ISO_3166_CODES,) point_person = models.ForeignKey(User, limit_choices_to={'is_staff': True}, on_delete=models.CASCADE) # in charge of the client (admin) firm = models.ManyToManyField(Firm, related_name='Firm_Client',) I should have a liste of client with name, description, firm and point_person thanks for help -
Data is not store in cart array when click add to cart button in React and Django
I'm following the react and Django tutorial, and I keep running into an issue when click add to cart button. Both Data array and data are not store show when i test in console In action/cart.js export const fetchCart = () => { return dispatch => { dispatch(cartStart()); authAxios .get(orderSummaryURL) .then(res => { dispatch(cartSuccess(res.data)); }) .catch(err => { dispatch(cartFail(err)); }); }; }; In Layout.js const mapStateToProps = state => { return { authenticated: state.auth.token !== null, cart: state.cart.shoppingCart, loading: state.cart.loading }; }; const mapDispatchToProps = dispatch => { return { logout: () => dispatch(logout()), fetchCart: () => dispatch(fetchCart()) }; }; export default withRouter( connect( mapStateToProps, mapDispatchToProps )(CustomLayout) ); In ProductList.js, handleAddToCart handleAddToCart = slug => { this.setState({ loading: true }); authAxios .post(addToCartURL, { slug }) .then(res => { console.log(res.data); this.setState({ loading: false }); }) .catch(err => { this.setState({ error: err, loading: false }); }); }; -
Need help resolving django stripe::InvalidRequestError, No such token
I am creating a payment using stripe on my website. Following tutorial, I was able to send test donation successfully. When I switched to live mode and made a payment. It went through with status 200 OK according to the log. However, django return with InvalidRequestError, No such token ... I check the log and find the token actually present. Here is my code: def donate(request,donateamt=None): # new donateamt_display = '' if donateamt: donateamt_display = f'{donateamt / 100:.2f}' if request.method == 'POST': charge = stripe.Charge.create( amount=donateamt, currency='usd', description='Donation', source=request.POST['stripeToken'] ) send_mail('Thank you for your donation', 'message', 'myemail@mywebsite.org', ['myemail@yahoo.com'], fail_silently=False ) context = {'donateamt_display':donateamt_display,'namespace':'membership',} return render(request, 'membership/donate.html',context) Here is the error message: Request req_XjpOs2GYFxyP9K: No such token: tok_1FVm12LAhXPisFUbODE2xZhe; a similar object exists in live mode, but a test mode key was used to make this request. And here is the response body: { "id": "tok_1FVm12LAhXPisFUbODE2xZhe", "object": "token", "card": { "id": "card_1FVm12LAhXPisFUberAeLysv", "object": "card", "address_city": null, "address_country": null, "address_line1": null, "address_line1_check": null, "address_line2": null, "address_state": null, "address_zip": null, "address_zip_check": null, "brand": "Visa", "country": "US", "cvc_check": "pass", "dynamic_last4": null, "exp_month": 12, "exp_year": 2023, "funding": "credit", "last4": "9124", "metadata": { }, "name": "myemail@yahoo.com", "tokenization_method": null }, "client_ip": "71.246.224.231", "created": 1571607164, "email": "myemail@yahoo.com", "livemode": true, … -
manage.py runserver invalid syntax
I am trying to run the command python manage.py runserverbut keep getting errors. I have tried python manage.py runserver,manage.py runserver and python3 manage.py runserver. Microsoft Windows [Version 10.0.17134.165] (c) 2018 Microsoft Corporation. All rights reserved. C:\Users\HP>cd C:\Users\HP C:\Users\HP>cd C:Users\HP\django_project The system cannot find the path specified. C:\Users\HP>cd C:\Users\HP\django_project C:\Users\HP\django_project>python manage.py runserver File "manage.py", line 3 python3 manage.py runserver ^ SyntaxError: invalid syntax C:\Users\HP\django_project>manage.py runserver File "C:\Users\HP\django_project\manage.py", line 3 python3 manage.py runserver ^ SyntaxError: invalid syntax C:\Users\HP\django_project>python3 manage.py runserver 'python3' is not recognized as an internal or external command, operable program or batch file. C:\Users\HP\django_project>python manage.py runserver File "manage.py", line 3 python3 manage.py runserver ^ SyntaxError: invalid syntax C:\Users\HP\django_project>dir /s >listmyfolder.txt Volume in drive C is Windows Volume Serial Number is D84A-5EE6 Directory of C:\Users\HP\django_project 10/20/2019 10:15 PM <DIR> . 10/20/2019 10:15 PM <DIR> .. 10/19/2019 05:50 PM <DIR> django_project 10/20/2019 10:15 PM 113 listmyfolder.txt 10/20/2019 08:23 PM 53 manage.py 2 File(s) 166 bytes Here is the contents of django_project - Directory of C:\Users\HP\django_project\django_project 10/19/2019 05:50 PM <DIR> . 10/19/2019 05:50 PM <DIR> .. 10/19/2019 05:50 PM 3,232 settings.py 10/19/2019 05:50 PM 777 urls.py 10/19/2019 05:50 PM 421 wsgi.py 10/19/2019 05:50 PM 0 __init__.py 4 File(s) 4,430 bytes Total Files Listed: … -
Can I run a Django Management Command in parallel over split pieces of DB?
I have a Django management command "update_prices.py" which basically takes 5-6 days to run over my whole database and update all prices. The command has quite a few calls to apis and then it updates and saves each product with new prices, which is happening way too slow. My question is, if is possible to run the same command on parallel (maybe multiprocessing/threading???) over different X sections of products of my database. So that if it takes 5 days for let's say 10.000 products, I could run 5 processes of the same command on 5 different slices of my DB and then finish in 1 day. Is this an option and if so, how should I do it? -
Carousel at django some problems
Carousel does not work. Can anyone help. Django just started learning models.py When I click on the button the next item the picture does not change. help me pls/ models.py class News(models.Model): news_title = models.CharField('название статьи', max_length=200) news_short_text = models.CharField('короткий текст статьи', max_length=400) news_text = models.TextField('текст статьи') news_pub_date = models.DateField('дата публикации') video = models.FileField(upload_to='media/', null=True, blank=True) def __str__(self): return self.news_title def was_published_recently(self): return self.news_pub_date >= (timezone.now() - datetime.timedelta(days=7)) class Image(models.Model): news = models.ForeignKey(News, on_delete=models.CASCADE, null=True, blank=True, related_name="news_post") image = models.ImageField(null=True, blank=True, upload_to="media/", verbose_name='Изображение') views.py def news(request): latest_news = News.objects.order_by('-news_pub_date')[:] paginator = Paginator(latest_news, 6) page = request.GET.get('page') latest_news = paginator.get_page(page) return render(request, 'news/news.html', {'latest_news': latest_news}) def detail(request, news_id): try: a = News.objects.get(id=news_id) except: raise Http404("error") latest_news_list = a.news_post.order_by('-id').all() return render(request, 'news/detail.html', {'news': a, 'latest_news_list': latest_news_list}) html <div id="myCarousel" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#myCarousel" data-slide-to="0" class="active"></li> <li data-target="#myCarousel" data-slide-to="1"></li> <li data-target="#myCarousel" data-slide-to="2"></li> </ol> <div class="carousel-inner" role="listbox"> {% for news in latest_news_list %} <div class="item {% if forloop.first %} active{% endif %}"> <img class="first-slide" src="{{news.image.url}}" alt="First slide"> <div class="container"> <div class="carousel-caption"> </div> </div> </div> {% endfor %} </div> <a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#myCarousel" role="button" data-slide="next"> <span … -
How to create a website where users can upload files, run them through a python script and download files back?
Sorry if this is a beginner question, but I wrote a python script that performs some data transformation on files for accounting and returns the file to the user. This is all done locally. I would like to create a website where users can pay a fee and upload their (bad) file, the website runs transformations on the file according to my script, and then return a good file for the user to download. I am confused on where to start however, and what web development tools I would need to learn to get this up and running? (the whole upload/download + payment methods are my issues). Is it also possible to link a finished script to the website process or would I have to re-write it? If you have any recommendations or suggestions, I would appreciate it. Thank you! -
How to load isolated template in to another template?
I have a form that it has Bootstrap 4 CSS classes. I want add jquery image upload code in my form but this codes have Bootstrap 3 CSS classes. I put my jquery block to image_block.html with {% load 'image_block.html %} tag. But I load image_block.html to my form.html file BS3 classes squash my BS4 classes and page is destroyed! image_block.html: {% load upload_tags %} <head> <!-- Bootstrap styles --> <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"> <!-- Generic page styles --> <link rel="stylesheet" href="/static/jquery-upload/css/style.css"> <!-- blueimp Gallery styles --> <link rel="stylesheet" href="/static/jquery-upload/css/blueimp-gallery.min.css"> <!-- CSS to style the file input field as button and adjust the Bootstrap progress bars --> <link rel="stylesheet" href="/static/jquery-upload/css/jquery.fileupload-ui.css"> <!-- CSS adjustments for browsers with JavaScript disabled --> <noscript><link rel="stylesheet" href="/staticjquery-upload//css/jquery.fileupload-ui-noscript.css"></noscript> </head> {% block upload %} <div class="container"> <!-- The file upload form used as target for the file upload widget --> <form id="fileupload" method="post" action="." enctype="multipart/form-data">{% csrf_token %} <!-- Redirect browsers with JavaScript disabled to the origin page --> <!--<noscript><input type="hidden" name="redirect" value="http://blueimp.github.io/jQuery-File-Upload/"></noscript>--> <!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload --> <div class="row fileupload-buttonbar"> <div class="col-lg-7"> <!-- The fileinput-button span is used to style the file input field as button --> <span class="btn btn-success … -
Django - Database design in orders ecommerce
I have a scenario what will be best design for this . I have a Articles table (like pizza , drink etc) class Articles(models.Model): restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE , blank=True, null=True) articlename = models.CharField(max_length=50, null=False, blank=False) price = models.DecimalField(max_digits=10, decimal_places=2) category = models.ForeignKey(Categories, on_delete=models.CASCADE) ingredient = models.ManyToManyField(Ingredient) #done articleoptionnames = models.ForeignKey(ArticlesOptionsName , on_delete=models.CASCADE) 2nd table is Article options (Like topping (1 time, 2times or 3 times), extra sauce , etc) class ArticlesOptions(models.Model): articleoptionrestaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE , blank=True, null=True) optionname = models.ForeignKey(ArticlesOptionsName, on_delete=models.CASCADE, related_name="optionnames") min = models.IntegerField() max = models.IntegerField() choice_price = models.DecimalField(max_digits=10, decimal_places=2) choice = models.CharField(max_length=255) def __str__(self): return str(self.optionname) And 3rd Order table class orders(models.Model): restaurant=models.ForeignKey(Restaurant, on_delete=models.CASCADE , blank=True, null=True) articles=models.ForeignKey(Articles, on_delete=models.CASCADE , blank=True, null=True) articleoptions=models.ManyToManyField(ArticlesOptions) totalamount=models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return str(self.articles) Customer will be able to purchase many articles at a time and then every article have multipul article options (for example 4 types of topping and 4 type of sauce user can select many type of topping and many type of sauce ). SO how to make order table in best way ? -
How to make a formset dynamic with a 'add-another' buttton in django?
$('#add_more').click(function() { var form_idx = $('#id_form-TOTAL_FORMS').val(); $('#form_set').append($('#empty_form').html().replace(/__prefix__/g,form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); -
template filter tag in django - filtering {{activate_url}}
I am working with django and react and developing a multi tenant application where each subdomain in django is a different company. Using rest framework. At user registration(company wise user) a confirmation email is send to each user to activate their account. The email send to users are in the format of http://company_code.localhost.com:8000/rest-auth/account-confirm-email/key subdomain wise. After some search i came to know this goes from allauth, send_confirmation_message.text file and in the form of {{activate_url}} for activating the account from react what i did was changed the default 'send_confirmation_message.txt' file of allauth as : 'http://localhost:8000/verify-email?key={{key}}' now i automatically filter my key from url on react and post to backend, and activate the account, the manual part still is getting company code from the url which django send in the email. Again i have read about template filter tag but can not use. So how can i use filter on {{activate_url}} which is http://company_code.localhost.com:8000/rest-auth/account-confirm-email/key to get my company_code and send to react in the form of url. Getting company_code is important as users are company wise and react should post to a specific company. Or My approach is wrong and should try something other ? Thanks -
Jquery Not Updating Management Formset
Very new to Django in general. View, template is working great, but for some reason, jquery.formset.js is not updating TOTAL_FORMS. Thus, while I can add entries and they are rendered in the HTML, only one is submitted. Oddly enough, adding several forms and then removing one correctly sets the value of TOTAL_FORMS properly. Probably time for a javascript course... Here is Jquery script I am referring to. Views.py def submit(request): order = Order() order_form = OrderForm() SelectionFormSet = get_ordereditem_formset(SelectionForm,extra=1,can_delete=True) if request.method == 'POST': order_form = OrderForm(request.POST, instance=order) formset = SelectionFormSet(request.POST, request.FILES,instance=order,prefix='horseselection_set') if order_form.is_valid() and formset.is_valid(): order_form.save() formset.save() return HttpResponseRedirect(order.get_absolute_url()) else: order_form = OrderForm(instance=order) formset = SelectionFormSet(instance=order,prefix='horseselection_set') return render(request,'orderform/order_form.html',{'form': order_form,'formset': formset}) order_form.html {% extends "base.html" %} {% block title %}{% endblock %} {% block content %} <h2>Profile</h2> <hr> <div class="col-md-4"> <form action="" method="post">{% csrf_token %} {{ form.as_p }} <table class="table"> {{ formset.management_form }} {% for form in formset.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr class="{% cycle row1 row2 %} formset_row"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for … -
Django CreateView not working with TinyMCE 5
I'm trying to use TinyMCE 5 with Django CreateView and can't get it to save to the database with the submit button; the form doesn't get submitted, i.e form_valid doesn't get called. The HTML template I'm using works with both CreateView and UpdateView successfully without TinyMCE and the model gets saved to the database. One of the fields in my model is a TextArea so wanted to try TinyMCE. I downloaded the SDK and have it stored locally. I then placed the following in the tags as per the documentation: <script src="{% static 'tinymce/js/tinymce/tinymce.min.js' %}"></script> <script type="text/javascript"> tinymce.init({ selector: '#id_description', }); </script> With this in place, I can see and use the TinyMCE editor when both Creating a new model and updating an existing one, but I can no longer save new model data to the database. Funny thing is though, I can still update and save edited data. Since I can update existing data, but not new data, I think this is probably a bug. Can anyone confirm please. Thanks -
Site doesn't show admin panel when i write http://localhost:8001/admin/
Site doesn't show admin panel. What should I do? Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8001/admin/ Raised by: news.views.PageViews With what it could be connected? I don't know what to do. class PageViews(ListView): template_name = 'page.html' paginate_by = 8 context_object_name = 'posts' ordering = ['-datetime'] model = Page paginate_orphans = 1 def dispatch(self, request, *args, **kwargs): slug = kwargs.get('slug') try: self.category = Category.objects.get(slug=slug) except Category.DoesNotExist: raise Http404 return super().dispatch(request, *args, **kwargs) def get_queryset(self): return Page.objects.filter(category=self.category) -
Modifying the models.Integerfield() appearance
Apologies if such question has been already asked before but I am not really sure how the feature I need is actually called. Is it possible to create models.Integerfield() that would look something like this: https://ibb.co/9VhBL5L where I would be able to define any word to show up beside the Integerfield() instead of "$". For instance, I have a basic mathematics task where kids need to calculate a number of animals in a forest. So the field would be blank and on the side of the field it would say "animals". So far, I can create only an empty field in Django: answer_1 = models.IntegerField( min=0, label='How many animals do you see?') Thanks. -
Django: Url translation is wrong
I have the following translation: {% url 'admin:organizers:settings:index' request.organizer.slug as business_settings_url %} {% blocktrans trimmed %} Looking for <a href="{{ business_settings_url }}">business settings</a>? {% endblocktrans %} However, I always get the wrong url: http://127.0.0.1:8000/admin/everett-vega-and-davis/survey-test/settings/%E2%80%9C/admin/everett-vega-and-davis/settings/%E2%80%9D It should be http://127.0.0.1:8000/admin/everett-vega-and-davis/survey-test/settings/ Do you see what I am doing wrong here? -
Django Models: Default for Choice Foreign Key
I have a Type model class as follows: class Type(models.Model): ENVIRONMENT = 'A' HUMANENV = 'B' HUMAN = 'C' ANIMAL = 'D' UNKNOWN = 'H' TYPE_CHOICES = [ (ENVIRONMENT, 'Environment'), (HUMANENV, "Human-related Environment"), (HUMAN, 'Human'), (ANIMAL, 'Animal'), (UNKNOWN, 'Unknown'), ] code = models.CharField(max_length=1, choices=TYPE_CHOICES, unique=True) class Meta: ordering = ['code'] def __str__(self): return self.get_code_display() And another Sample model where one of the fields is a foreign key to the Type model as follows: class Sample(models.Model): sample_id = models.CharField(max_length=20, unique=True) type = models.ForeignKey("Type", on_delete=models.CASCADE, blank=True, default=get_default_type()) class Meta: ordering = ["sample_id"] def __str__(self): return self.sample_id where get_default_type is a function that returns the pk for the default Type model instance: def get_default_type(): return Type.objects.get(code="H").id The problem is when I run Sample.objects.create(sample_id="some_id"), it is giving me the error IntegrityError: null value in column "type_id" violates not-null constraint DETAIL: Failing row contains (28113, some_id, null). As you can see in the second line of the error message, the type_id is null instead of the pk as returned by the get_default_type function. I have tried setting null=True for the foreign key and when I do that I am able to create the Sample model instance, but with a None type instead of the Unknown … -
Copy contents from a model to another model
I need to copy the full contents from a table to another everytime that the user add an object. I have this two models: from django.contrib.gis.db import models from django.contrib.gis.geos import Point from mapbox_location_field.models import LocationField class AddPointManager(models.Model): description = models.TextField( 'Short description', max_length=500, help_text="Max 500 characters.", ) location = LocationField() def __int__(self): return self.pk def get_absolute_url(self): return reverse("point", kwargs={"pk":self.pk}) class Meta: ordering = ['-pk'] class AddPoint(models.Model): description = models.TextField( 'Short description', max_length=500, help_text="Max 500 characters.", ) geom = models.PointField() def __int__(self): return self.pk def get_absolute_url(self): return reverse("point", kwargs={"pk":self.pk}) def save(self, *args, **kwargs): manager = AddPointManager.objects.all() lat = self.manager.location[0] lon = self.manager.location[1] self.geom = Point(x=lon, y=lat, srid=4326) self.description = AddPointManager.description super(AddPoint, self).save(*args, **kwargs) @property def coordinates(self): return str(self.geom.x) + ', ' + str(self.geom.y) class Meta: ordering = ['-pk'] I think that my save method isn't correct because when I add a point by admin panel I can see itself in AddPointManager but not into AddPoint. The table of AddPoint remains empty. admin.py from django.contrib.gis import admin from mapbox_location_field.admin import MapAdmin from .models import AddPointManager class AddPointManagerAdmin(MapAdmin): class Meta: model = AddPointManager admin.site.register(AddPointManager, AddPointManagerAdmin) -
How to emulate native CREATE response
I am trying to emulate the type of JSON response I get from a ModelSerializer when doing a GET. I have this ViewSet: def create(self, request, *args, **kwargs): recipe_ingredient = RecipeIngredient.objects.create( base_ingredient=Ingredient.objects.get(pk=request.data['base_ingredient']), recipe=Recipe.objects.get(pk=request.data['recipe']) ) data = serializers.serialize('json', [recipe_ingredient, ]) struct = json.loads(data) data = json.dumps(struct[0]) return Response(data) This returns a JSON the physical recipe_ingredient instance instead of just the data like it would with my RecipeIngredientSerializer when I make a GET request. Once I have created an object through .create(), how can I return a JSON that would have all the same serialization as my RecipeIngredientSerialzer returns when I do a GET? -
Django update view only seems to work with regex urls
I am getting my hands dirty with Django and have a simple use case in which i have to create a function based view for updating a Model. Below is my function based view function: def update_post(request, id=None): obj = get_object_or_404(PostModel, id=id) form = PostModelForm(request.POST or None, instance=obj) if form.is_valid(): obj = form.save(commit=False) print(f"The object that i am going to save is {form.cleaned_data}") obj.save() messages.success(request, f"Updated object with id {id}") return HttpResponseRedirect(f"/blog/read/{id}") context = { "form": form } return render(request, "blog/update-post.html", context) Below is my update-post.html: <html> <form method="POST" action="."> {% csrf_token %} {{form.as_p}} <input type="submit" value="Change"> </form> </html> And this is my urls.py file : from django.urls import path, include from django.conf.urls import url from .views import list_posts, read_post, create_post, update_post app_name = "blog" urlpatterns = [ path('posts/', list_posts, name="list"), path('read/<int:id>', read_post, name="read"), path("create/", create_post, name="create"), #url(r'^(?P<id>\d+)/edit/$', update_post, name="update") path("update/<int:id>", update_post, name="update"), ] The update view only seems to work when i use the above regex url pattern for editing the post . Otherwise i get the below error message: Can someone please tell me where i am going wrong with this. -
Toastr JS appears in source code but is invisible
I am trying to use Toastr JS, initially i could not figure out why it just wont appear but it actually does(figured out by changing Timeout to 10min and looking at the source code) but it is invisible and i have no idea why. It Appears below everything instead of top right. My Template code {% block javascript %} {% if messages %} {% for message in messages %} {% if message.tags == 'success'%} <script> toastr.success("{{ message }}")</script> {% elif message.tags == 'info' %} <script> toastr.info("{{ message }}")</script> {% elif message.tags == 'warning' %} <script> toastr.warning('{{ message }}")</script> {% elif message.tags == 'error' %} <script> toastr.options = { closeButton: false, debug: false, newestOnTop: false, progressBar: true, positionClass: "toast-top-right", preventDuplicates: false, onclick: null, showDuration: "9000", hideDuration: "1000", timeOut: "0", extendedTimeOut: "1000", showEasing: "swing", hideEasing: "linear", showMethod: "fadeIn", hideMethod: "fadeOut" } toastr.error("{{ message }}") </script> {% endif %} {% endfor %} {% endif %} {% endblock %} -
Getting 500 Internal Server Error After Creating a Letsencrypt https certificate
Ok so I have a django project hosted on Linode served via apache webserver. After creating a certificate from Letsencrypt I get this error whenever I visit my site. Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at webmaster@localhost to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. Apache/2.4.34 (Ubuntu) Server at www.mysite.com Port 443 I did not get this error on http before. It might something from their side or wrong configuring on my apache side. Has anyone had experience with this issue? Thank you -
Django unused import statement: virtualenv issue
I have looked all over and nobody seems to be having the same issue as me. I am new to Django and have followed many tutorials but nothing is working. Before I found out that it is best practice to setup a virtualenv for your django projects I had installed it normally (globally) on my pc (ubuntu) and everything worked fine. I wanted to follow best practice though and started fresh and setup a project in a virtualenv. The landing page works and everything, but when I go to and editor I get errors wherever imports using django are. Example: Project->polls app->views.py from django.shortcuts import render Error given: Unused import statement I am completely lost at this point. I really would love to start using Django but I really want to follow best practice with virtualenv. Any help is appreciated!