Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: Cannot read property 'title' of undefined | django react js
I can't figure out why it's showing TypeError in Card. Though it's working fine in backend. Error: TypeError: Cannot read property 'title' of undefined view.js ... export default class ArticleDetail extends React.Component { state = { articles: {} } componentDidMount() { const articleID = this.props.match.params.articleID; axios.get(`http://127.0.0.1:8000/api/${articleID}`).then( res => { this.setState({ article: res.data }); } ) } render (){ return ( <Card title={this.state.article.title}> <p> {this.state.article.content} </p> </Card> ) } } models.py class Article(models.Model): title = models.CharField(max_length=20) content = models.TextField() -
How to set value on forms.ChoiceField in django view?
This is my form : class ch_form(forms.Form): ch_field = forms.ChoiceField( required=True , label= 'ch_field : ' , ) and this is my view : def testView(request): form = ch_form( initial={ 'ch_field':[ (1, 'test1'), (2, 'test2'), (3, 'test3'), ] } ) But its not work. So my question is how can I set value for forms.ChoiceField in view function during the runtime. sorry for my bad English. -
django makemessages error "Non-ASCII string at"
When I run the command python manage.py makemessages -l tr I get the following error "xgettext: Non-ASCII string at ./venv/Lib/site-packages/fpdf/fonts.py:22.". I go to the file with errors and look at the relevant line, this line _ ("xx") is not a line that starts like this so why does it give such an error here? took a screenshot of the moment i got the error and the corresponding fonts.py file fonst.py image view -
How to draw rectangle into HTML page using Python
I am using Django with Python to create an HTML page as shown in the image with rectangles image -
TypeError: join() argument must be str or bytes, not 'PosixPath'
So, I'm receiving the following error: TypeError: join() argument must be str or bytes, not 'PosixPath' It happens while checking my Django installation on Ubuntu 16.04. The full error would be: STATIC_ROOT = os.path.join(BASE_DIR, 'static') File "/usr/lib/python3.5/posixpath.py", line 89, in join genericpath._check_arg_types('join', a, *p) File "/usr/lib/python3.5/genericpath.py", line 143, in _check_arg_types (funcname, s.__class__.__name__)) from None TypeError: join() argument must be str or bytes, not 'PosixPath' This is from the settings.py file. In the file I have: from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent ... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') On my development environment it is working and running through it, yet here I receive the error. The version of Python on production is 3.5.1-3. Normally the packages should be installed the same as well (pip freeze/install -r). Anyone have an idea to push me in the correct direction? Thanks in advance, -
Django child fields return null on parent GET request
I'm having an issue getting the proper data through a GET request. The parent Order has several OrderItem children. When doing a POST request to create the parent with a child at the same time, the response shows the created parent object but with all fields set to null for the child. I don't understand why it does this as in Django admin page I can verify that the child has saved the data properly upon the parent's creation. When showing the list of parents or the details of one parent, it seems the child's data are not returned properly. However in the serializers I have the corresponding fields. What am I missing or doing wrong? Thanks for your responses! I'm getting this on the endpoint /api/orders/24: { "bar_id": 2, "order_items": { "order_id": null, "ref_id": null } } And this on the endpoint /api/order_items/21: { "order_id": 24, "ref_id": 3 } So I should be getting on the endpoint /api/orders/24: { "bar_id": 2, "order_items": { "order_id": 24, "ref_id": 3 } } Here is my parent OrderModel: from django.db import models from .model_bar import * class Order(models.Model): bar_id = models.ForeignKey(Bar, null=True, on_delete=models.CASCADE, related_name='orders') Here is my child OrderItemModel: from django.db import models … -
Django serializers filter foreignkey
view: class MPNView(viewsets.ModelViewSet): queryset = MPN.objects.all() serializer_class = MPNSerializer serializers: class ProductsSerializer(serializers.ModelSerializer): class Meta: model = Products fields = "__all__" class MPNSerializer(serializers.ModelSerializer): products = ProductsSerializer(many=True) class Meta: model = MPN fields = "__all__" model: class MPN(Model): number = models.CharField(max_length=50) created_at = models.DateTimeField(auto_now_add=True) class Product(Model): mpn = models.ForeignKey(to=MPN, on_delete=models.CASCADE, related_name="products", null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) Results i am getting: [ { "id": 1221, "products": [], "number": "B07BMTYSMR", "created_at": "2020-09-29T03:05:01.560801Z" }, { "id": 1222, "products": [ { "id": 2352, "created_at": "2020-09-30T12:49:09.347655Z", }, { "id": 2352, "created_at": "2020-09-30T12:49:09.347655Z", } ] } ] Results i am expecting: [ { "id": 1222, "products": [ { "id": 2352, "created_at": "2020-09-30T12:49:09.347655Z", }, { "id": 2352, "created_at": "2020-09-30T12:49:09.347655Z", } ] } ] Here is my code . Shared view, model and serializers Here i am trying to get result with ForeignKey related fields But, I wants to add one filter so it will ignore data where products is [] (empty array) Please have a look how can i achive that -
django rest framework vs django rest framework 2
hello can someone explain to me the difference between django-rest-framework and django-rest-framework 2 because on internet both have different sites https://www.django-rest-framework.org/ and http://www.tomchristie.com/ bot both have same GitHub repo. and I am also very much confused between laravel and django way of returning json response in laravel we can return query result and it will automatically convert in JSON but in django we create serializers but by creating nested serializers can we able to return any type of response related to those tables? it will be appreciated if someone can provide me with some reference to learn nested serilizing thanks in advance... -
How to allow users to pay with paypal each other in Django
I was following This and ended up with users can pay me and get their product, however, I want users to pay each other. Both users should enter their email address linked with their PayPal, now how can I make the transaction transfer money to other user email address instead of me? My html <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <scriptsrc="https://www.paypal.com/sdk/js?client-id=MY_SANDBOX_CLIENT_ID"></script> <h1>you are about to pay {{ trade.price }}</h1> <div id="paypal-button-container"></div> <script> paypal.Buttons({ createOrder: function (data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: '{{trade.price}}' } }] }); }, onApprove: function (data, actions) { return actions.order.capture().then(function (details) { $.ajax({ url: "{% url 'payment:pay_trade' trade.id %}", data: { csrfmiddlewaretoken: "{{ csrf_token }}" }, method: 'POST', success: function (response) { alert('Successfully paid') }, error: function (response) { alert('something went wrong') } }) }); } }).render('#paypal-button-container'); </script> The function: def pay_trade(request, trade_id): trade = get_object_or_404(Trade, pk=trade_id) if request.method == 'GET': return render(request, 'payment/pay_trade.html', {'trade': trade}) else: # Give something to the buyer # No idea how to check if the transaction was made but i hope so ;-; return JsonResponse({}) Also, it would be great if someone can help me to check if the payment is done before making the function, thanks! -
Override the maximum number of characters in the admin form
There is a model with a maximum length of 32 characters in the field. The model is used in the form in the administrator interface. The value to be entered in the field must allow an unlimited number of elements separated by commas. This field is then parsed and passed to the bulk_create method. The problem is that the model level length limits do not allow entering more than 32 characters into the form. How to avoid this constraint? models.py class MyModels(models.Models): .... items = models.CharField(verbose_name=_(u'Item ID'), max_length=32) forms.py class ItemForm(ModelForm): class Meta: model = MyModel fields = ['items'] -
Reverse for 'date_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['date/(?P<pk>[0-9]+)$']
I have two models and a third model for a many-to-many relationship the form should take a date from the first model that is the date model and the user will choose images from the second model and connect them but when I'm making the form I'm getting this error Reverse for 'date_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['date/(?P[0-9]+)$'] my models.py class MyDate(models.Model): english_date = models.DateField(auto_now=False) hebrew_date = models.CharField(max_length=20,unique=True) sof_zman_1 = models.TimeField(auto_now=False,blank=True,null=True) sof_zman_2 = models.TimeField(auto_now=False,blank=True,null=True) sof_zman_tefila = models.TimeField(auto_now=False,blank=True,null=True) def get_absolute_url(self ): return reverse('date_detail',kwargs={'pk':self.pk}) def __str__(self): return self.hebrew_date # images class Images(models.Model): image = models.ImageField(unique=False,upload_to='images/') def get_absolute_url(self): return reverse("image_detail",kwargs={'pk':self.pk}) #connect days and images together class DayImage(models.Model): date = models.ForeignKey('luach.MyDate',related_name='day',on_delete=models.CASCADE) image = models.ManyToManyField('luach.images',related_name='images') def __str__(self): return self.pk my views.py def create_day_image_view(request,pk): date = get_object_or_404(MyDate,pk=pk) if request.method == 'POST': form = DayImageForm(request.POST) if form.is_valid(): dayimage = form.save(commit=False) dayimage.date = date dayimage.save() return redirect('date_detail',pk=mydate.pk) else: form = DayImageForm() return render(request, 'luach/dayimage_form.html',{'form': form}) my urls.py urlpatterns = [ path('admin/', admin.site.urls), path('date/<int:pk>',views.MyDateDetailView.as_view(),name='date_detail'), path('date/<int:pk>/add_image/',views.create_day_image_view,name='add_image') ] and my dayimage_form.html {% block content %} <div class='container'> <div class="jumbotron"> <form method="POST"> {% csrf_token %} {{form.as_p}} <button type='submit' class='btn btn-success'>save</button> </form> <a class="btn btn-danger" href="{% url 'date_detail' pk=mydate.pk %}">cancel</a> </div> </div> {% endblock %} -
Error: Invalid value for '-A' / '--app': module 'proj' has no attribute 'celery'
I am trying to run celery using supervisord using command supervisorctl start sv_celery. I'm getting the below error. Error: Invalid value for '-A' / '--app': module 'proj' has no attribute 'celery' My proj directory has the celery.py and tasks.py files My Celery.py: from celery import Celery import os if(os.environ.get("DJANGO_ENV") == "production"): os.environ.setdefault("DJANGO_SETTINGS_MODULE", \ "projectname.settings_prod") else: os.environ.setdefault("DJANGO_SETTINGS_MODULE", \ "projectname.settings") import django django.setup() app = Celery('proj', broker='pyamqp://', backend='redis://localhost', include=['proj.tasks']) # Optional configuration, see the application user guide. app.conf.update( result_expires=3600, ) if __name__ == '__main__': app.start() My Tasks.py from .celery import app @app.task def add(x, y): return x + y My Supervisord/conf.d/celery.conf ; the name of your supervisord program [program:sv_celery] ; Set full path to celery program if using virtualenv command=/root/venv/bin/celery -A proj worker --loglevel=INFO ; The directory to your Django project directory=/root/projectname/projectname ; If supervisord is run as the root user, switch users to this UNIX user account ; before doing any processing. user=root ; Supervisor will start as many instances of this program as named by numprocs numprocs=1 ; Put process stdout output in this file stdout_logfile=/var/log/celery/celery_worker.log ; Put process stderr output in this file stderr_logfile=/var/log/celery/celery_worker.log ; If true, this program will start automatically when supervisord is started autostart=true ; May … -
Sort Django Rest API Endpoint Response by Date
Let's say I have a response from a endpoint. I am using Django Rest Framework. Let's say this is what is returning from endpoint. [ { Name: "q4", Date: "2020-09-30T18:00:52+03:00", Url: "/test/test", }, { Name: "q2", Date: "2020-10-01T13:32:21+03:00", Url: "/test", }, { Name: "q1", Date: "2020-09-30T17:42:06+03:00", Url: "/xyz", }, { Name: "q3", Date: "2020-09-30T13:04:23+03:00", Url: "...", }, { Name: "q5", Date: "2020-10-01T13:04:45+03:00", Url: "...", }, ] How am I going to change ordering of response by respecting to date and time like this? [ { Name: "q3", Date: "2020-09-30T13:04:23+03:00", Url: "...", }, { Name: "q1", Date: "2020-09-30T17:42:06+03:00", Url: "/xyz", }, { Name: "q4", Date: "2020-09-30T18:00:52+03:00", Url: "/test/test", }, { Name: "q5", Date: "2020-10-01T13:04:45+03:00", Url: "...", }, { Name: "q2", Date: "2020-10-01T13:32:21+03:00", Url: "/test", } ] -
How to make a djangomodel form appear in two different colums with fields divided into two coulmn?
I have this form rendered in my webapp. I dont want this in single column, instead in two columns with fields divided. How can I do that?? This is my form in template. <form method="POST"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success" formaction="{% url 'addcustomer' %}">Submit</button> <button class="btn btn-primary" formaction="{% url 'customerlist' %}">Cancel</button> </form> -
How to update User Profile in Django?
I am trying to update user profile, and I am using signals for this, but when i create a user from my Django default admin panel then it's creating a record automatically in profile table with Null values. I am using OneToOneField relation between User and Profile models, Please let me know how i can update the profile section after create a user. It's functionality is something like this, when i create a user then I will assign the user a Group, if the user is logged in on my website then he/she can see the functionality of that group and profile update functionality is available in that Group. Here is my Profile modal... class Profile(models.Model): age=models.CharField(max_length=225) customer=models.OneToOneField(User, related_name='related_user',on_delete=models.CASCADE) @receiver(post_save, sender=user) def create_profile(sender, instance, created, **kwargs) if created: Profile.objects.create(user=instance) group = Group.objects.get(name='profile') instance.groups.add(group) Now it's happening when I create a user it's automatically creating record in profile table, but I want the record update when I assign the profile group to that user (If i assign profile group to the user then profile record should be update), after that i will update all the fields in user profile. -
Dynamically building complex queries in Django using Q-Objects
I have a database query for some items (containers). There is a related table that could define some restrictions (Only those in a top-level org, only those in a dept (customer) in an org, or just those in a team (course) in a dept) Here's my (not working) code to get the list of objects: def get_containers(customer_id: None, course_id: None): q_list = (Q(is_private=False), Q(is_active=True)) if customer_id: try: customers = Customer.objects customer = customers.get(id=customer_id) except KeyError: return None # Second level restriction: may have a customer-id customer_q = ( Q(restrictions__customer__isnull=True) | Q(restrictions__customer=customer.id) ) # Third level restriction: may be restricted to a course-code course_q = Q(restrictions__course_code__isnull=True) if course_id: course_q |= Q(restrictions__course_code=course_id) # Top level restriction: restricted to org restrictions_q = ( Q(restrictions__organisation=customer.org.id) & customer_q & course_q ) q_list = (Q(q_list) | Q(restrictions_q)) print(f"q_list: {q_list}") return Container.objects.filter(q_list) I've been using https://docs.djangoproject.com/en/3.0/topics/db/queries/#complex-lookups-with-q (& the referenced https://github.com/django/django/blob/master/tests/or_lookups/tests.py), and the previously asked django dynamically filtering with q objects as references during this. I've tried a bunch of variations to get the OR at the end of the if customer_id: block to work - and they all give me errors: q_list = q_list | restrictions_q\nTypeError: unsupported operand type(s) for |: 'tuple' and 'Q' q_list = Q(q_list … -
Django: Use a different related_name than "%(class)s" on abstract base classes to account for irregular plurals
I have the following models: from django.db import models from foo.bar.models import Location class AbstractShop(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE, related_name="%(class)s") class Meta(self): abstract = True class Bakery(AbstractShop): some_field = models.BooleanField("Some field", default=True) class Meta: verbose_name = "Bakery" verbose_name_plural = "Bakeries" class Supermarket(AbstractShop): some_other_field = models.CharField("Some other field", max_length=20) class Meta: verbose_name = "Supermarket" verbose_name_plural = "Supermarkets" Now, Supermarket as well as Bakery inherit the location-ForeignKey from AbstractShop. If I want to query the reverse relation to Bakery on the Location model, I would have to use bakerys as related_name - which I don't want as it's grammatically wrong and unintuitive. So my questions are: Is there any way to use the verbose_name_plural as related_name? Is there any way at all to use any other related_name than "%(class)s" or "%(app_label)s or do I just have to implement the ForeignKey on the child classes? If so, that would be somewhat annoying. Imagine you have a lot of shared ForeignKeys: You can move the ones with regular plurals in English to the abstract base class while those with irregular plurals have to be implemented on the child class. This is a totally arbitrary condition which might not be obvious to non-native English speakers, … -
How many parallel request can flask/django handle at a time?
I have built an api with python deployed with gunicorn/nginx/docker. I would like to know how many parallel request can a single api handle at a single point of a time. -
RuntimeError at /admin/auth/user/add/ generator raised StopIteration
I am new in django and i am facing RuntimeError at /admin/auth/user/add/ generator raised StopIteration while adding new user in database -
Allow user to make new roles in django?
I am new to Django.I was learning how to create multiple user type with same common login form in Django.I was following this blog https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html.On this blog it says that No matter what strategy you pick, or what is your business model, always use one, and only one Django model to handle the authentication. And in this blog example, before building the project the set of users were known and according to that the model was built.For that he took a choice field and stored the user_type.When the user wants to login he/she need to select any option from the dropdown and login.But I want my user(admin) to create the user_type.In such case how do I dynamically add the created user_type and add to that choice_field. Code snippet from that blog: class Role(models.Model): STUDENT = 1 TEACHER = 2 SECRETARY = 3 SUPERVISOR = 4 ADMIN = 5 ROLE_CHOICES = ( (STUDENT, 'student'), (TEACHER, 'teacher'), (SECRETARY, 'secretary'), (SUPERVISOR, 'supervisor'), (ADMIN, 'admin'), ) id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, primary_key=True) def __str__(self): return self.get_id_display() class User(AbstractUser): roles = models.ManyToManyField(Role) -
django 3 Forbidden (403) CSRF verification failed. Request aborted. how can you bypass or send a token via axios vuejs
I have an error that I can't go further because he swears at the token, I don't want to use django-rest-framework and django-cors-headers. front works in vuejs 3. front <i class="fa fa-question-circle fa-2x text-warning" aria-hidden="true" @click="checkFly(item.booking_token)"></i> checkFly: function(booking_token) { var vue = this; console.log(booking_token); axios .post(API + "check-fly/", { params: { csrfmiddlewaretoken: $("#csrfmiddlewaretoken").val(), booking_token: booking_token, }, }) .then(function(response) { vue.check = response.data; console.log(vue.check); }); }, back def checkfly(request): data = [] url = "v=2&booking_token=" + \ request.GET.get( 'booking_token') + "&bnum=3&pnum=2&affily=picky_{market}&currency=USD&adults=1&children=0&infants=1" print(url) return JsonResponse(json.dumps(url), safe=False) -
Django receiving POST URL
I'm using Jira webhooks to communicate with my Django app. In Jira, I set POST URL to: /api/webhooks/jira?issue_id=EXAMPLE_ISSUE_ID&secret=EXAMPLE_SECRET&user_id=EXAMPLE_USER_ID&user_key=EXAMPLE_KEY My app urls.py from django.urls import path from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path("api/webhooks/jira", views.webhook, name='webhook') ] How can I get information about issue_id, secret, user_id, and user_key (Those values aren't included in json that I recveive via post) and what is the proper way to set path in my urls.py? -
How to to math operation in Django templates?
I am writing a web app in Django where a user can vote a post, from 1 to 5 (using stars), when I want to display the stars I have to decide how many of them have to be yellow and how many not. I save the feedback in this model: class Feedback(models.Model): text = models.TextField() stars = models.IntegerField(choices=[(i, i) for i in range(1, 6)], blank=False) article = models.ForeignKey(Article, on_delete=models.CASCADE) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) the problem is in the template, because I would like to do something like this, but i don't know how and if it is a good choice: {% for _ in art.stars %} <span class="fa fa-star checked"></span> {% endfor %} {% for _ in (5-art.stars) %} <span class="fa fa-star"></span> {% endfor %} -
hide secret key on django/pycharm mac
I'm making a simple CRUD app in django with the use of Pycharm. I want to upload the project to Github and thus need to protect some of my settings.py file. Would the best way to be use a .env file and add it to .gitignore or does that method not work on mac? -
What are the best online programs suitable for kids? [closed]
Coding, Programming, App Development, Digital Literacy, C program , Little Hackers and many more engaging programs.