Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django pass data from one model form to another model form
I am creating e-commerce type website project. I want to pass the data from one model to another model form. In this case when I click on order button details from menu_details model should extracted and passed to order_details form. Fields of both models i.e. menu_details and order_details are same except order_details has one extra field called customer_name field. I executed the below code. No error is showing but order_details is still empty. Views.py def order_food(request, id): content = menu_details.objects.get(id=id) o_content = menu_details.objects.all() form = order_form( {'restaurant_name': content.restaurant_name, 'customer_name': request.user, 'dish_name': content.dish_name, 'dish_type': content.dish_type, 'price': content.price, 'description': content.description, 'image': content.image}) if form.is_valid(): form.save() return render(request, "menu/order_view.html", {'content': o_content}) -
django: Force cache-refresh after update
After updating a model instance, I redirect back to this instance "detail page". Part of the model is an image generated from the models content. In this redirect I want to force the browser to reload the image from the server. I tried it with headers but that doesn't work: response = HttpResponseRedirect('/target/path/') response['Cache-Control'] = 'no-cache' response['Pragma'] = 'no-cache' return response Because I assume the redirect loses the headers. How can I force the page to reload the image but only after user returns from update page? -
Joining Models in Python DRF Serializer
So I am relatively new to Django, and DRF. I recently started a project to learn more about the platform. I also found best practice guide line which I am following at the moment. Here is the Django Style Guide The guild line says that every App should completely decouple itself and use UUID instead of foreign key, And every business rule should go into services.py (Which I like btw.) Here comes the problem. I am not sure how I can construct two models together to produce a nested JSON Output. Ex: I have Post() model and Comments() model. and Comment model uses uuid of Post model as a referential id. Now in my API.py, I am not sure how I can join these two together in the Serializer.py Model class Post(models.Model): user_id = models.UUIDField(default=uuid.uuid4) title = models.CharField(max_length=100) description = models.CharField(max_length=100) pictures = models.CharField(max_length=100) lat = models.CharField(max_length=16) long = models.CharField(max_length=16) vote = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now_add=True) class Comment(models.Model): post_id = models.UUIDField(default=uuid.uuid4) parent_id = models.ForeignKey("self", on_delete=models.CASCADE) text = models.CharField(max_length=1000) up_vote = models.IntegerField() down_vote = models.IntegerField() user_id = models.UUIDField(default=uuid.uuid4) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now_add=True) API class ReportGetApi(APIView): class OutputSerializer(serializers.ModelSerializer): comments = OutputCommentSerializer(many=True, read_only=True) class Meta: model = Post … -
How to pass parent object primary key value to another template using {% include%} in Django?
I have a TreeView template and an itemList template. I want these two templates to be displayed on the same page, so I tried to include the itemList template into the Treeview template using {% include %}. When I click on the leaf node in the Treeview, the itemList should show the corresponding Content. So far I have made these two templates work independently, but now I am stuck on how to integrating them together, here is my urls.py url(r'^marketgroups',views.show_marketgroups,name='marketgroups'), path('marketgroup/<int:pk>',views.itemListView.as_view(),name='invtypes_list'), and views.py def show_marketgroups(request): return render(request,"sde/marketgroups.html",{'marketgroups':Marketgroups.objects.all()}) class itemListView(generic.ListView): model = Invtypes template_name = 'sde/invtypes_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) pk = self.kwargs['pk'] context['invtypes'] = Invtypes.objects.filter(marketgroupid=pk).order_by('typeid') return context and here is marketgroups.html <div class="row" > <div class=""> {% load mptt_tags %} <ul id="mktUL"> {% recursetree marketgroups %} <li> {% if node.is_leaf_node %} <li><span class=""><a href="{{ node.get_absolute_url }}">{{ node.nameid }} {{ node.marketgroupid }}</a></span></li> {% else %} <li><span class="mktcaret">{{ node.nameid }}</span> <ul class="nested"> <li>{{ children }}</li> </ul> </li> {% endif %} </li> {% endrecursetree %} </ul> </div> <div class=""> <p>itemList supposed to be load here</p> {% include "sde/invtypes_list.html" with node.pk %} </div> </div> I haven't figured out how to tell the {% include %} to load different pk values, maybe use … -
Fetching and display the data in a Django Template Using MYSQL RAW SQL QUERY
Here is my Django Template Used to Display The data in table Format... enter code here <table class="content" border="2px"> <thead> <tr> <th>S-No</th> <th>Name</th> <th>Email</th> <th>Productname</th> <th>Quantity</th> <th>Price</th> <th>Ordertime</th> <th>Orderstatus</th> <th>Actions</th> </tr></thead> <tbody> {% for row in records %} <tr align="center"> <td>{{row..pid}}</td> <td>{{ row.username }}</td> <td>{{ row.email }}</td> <td>{{ row.productname }}</td> <td>{{ row.quantity }}</td> <td>{{ row.price }}</td> <td>{{ row.ordertime }}</td> <td>{{ row.orderstatus }}</td> <td><input type="submit" value="Accept"> <input type="button" value="Reject"></td> </tr> {% endfor %} </tbody> </table> And This is my Views.py Page for the fetching up of the data def viewpro(request): con = mysql.connector.connect(user='root', password='', host='localhost', database='company1') cur = con.cursor() cur.execute("SELECT * FROM user_order") records=cur.fetchall() print(records) con.commit() cur.close() con.close() #context = {'viewpro' : user_order.objects.all()} return render(request, "viewpro.html", {'records':records}) But Here The problem is it display the no.of table rows same like DB(It have 4 records and table shows 4 rows But no data in the fields).....Pls Help me to get rid of that....Only using raw queries.... -
Exclude issue in Cerberus 1.3.2
I'm new to Cerberus recently upgraded the Cerberus version to 1.3.2 from 1.1. But getting validation errors. Please find the validation schema. my_schema = { 'email': { 'type': 'string', 'maxlength': 1000, 'regex': EMAIL_PATTERN, 'required': True }, 'guest': { 'type': 'boolean', 'required': False, 'excludes': ['password', 'issue_password_reset'] }, 'password': { 'type': 'string', 'minlength': 9, 'required': True, 'excludes': 'issue_password_reset' }, 'prefix': { 'type': 'string', 'nullable': True, 'required': False, 'maxlength': 10 }, 'first_name': { 'type': 'string', 'nullable': True, 'required': False, 'maxlength': 50 }, 'last_name': { 'type': 'string', 'nullable': True, 'required': False, 'maxlength': 50 }, 'phone_number': { 'type': 'string', 'required': False, 'nullable': True, 'regex': PHONE_NUMBER_PATTERN }, 'birthday': { 'type': 'string', 'required': True, 'excludes': 'is_legal_drinking_age' }, 'is_legal_drinking_age': { 'type': 'boolean', 'required': True, 'excludes': 'birthday' }, 'issue_password_reset': { 'type': 'boolean', 'required': True, 'excludes': 'password' }, } data = { "email": "guest123@email.com", "guest": True, "birthday": "1975-05-05", "prefix": "Ms.", "first_name": "Allison", "last_name": "Smith", "phone_number": "(212) 555-2002" } valid = Validator(default_schema) resp = valid.validate(data) print(valid.errors) print(resp) For Cerberus version 1.3.2, getting error For Cerberus version 1.1, validation is working properly. Hoping to find some help. -
Django localflavor field overwrite breaks form
I have the following form, which generates a Value error upon submition. ValueError at /en/orders/create/ The view orders.views.order_create didn't return an HttpResponse object. It returned None instead. my form: from django import forms from .models import Order from localflavor.us.forms import USZipCodeField class OrderCreateForm(forms.ModelForm): postal_code = USZipCodeField() class Meta: model = Order fields = ['first_name', 'last_name', 'email', 'address', 'postal_code', 'city'] my model: class Order(models.Model): first_name = models.CharField(_('first name'), max_length=50) last_name = models.CharField(_('last name'), max_length=50) email = models.EmailField(_('e-mail')) address = models.CharField(_('address'), max_length=250) postal_code = models.CharField(_('postal code'), max_length=20) city = models.CharField(_('city'), max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class Meta: ordering = ('-created', ) def __str__(self): return f'Order {self.id}' my view: def order_create(request): if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order.save() request.session['order_id'] = order.id # redirect for payment return return redirect(reverse('payment:process')) else: form = OrderCreateForm() return render(request, 'orders/order/create.html', {'cart': cart, 'form': form}) The process works fine, and redirects to a payment form, without this line in the form : postal_code = USZipCodeField() I cant seem to understand what causes the error -
How can I render a button based on condition in html templates | Django
I am trying to render the button based on a condition. Here I am checking if the combo is in cart, then I will render out the remove button, for that combo only. But I am not able to do that. Here in ComboCartItem class combo field is a ForeignKey of class Combo and in Cart class combo_item field is a ManyToManyField of class ComboCartItem So in general if we want to display a list of all the combos that are present in the cart we can do that by {% for item in cart.combo_item.all %}{{item.combo}}{% endfor %} But it doesn't work while going for a condition check. Please help. {% if combo in cart.combo_item.all %} <button type="submit" class="btn btn-success">Remove?</button> {% endif %} This doesn't work. Please help! l.html <form method="POST" action="{% url 'carts:combo_add_to_cart' %}" class="form"> {% csrf_token %} <input type="hidden" name="combo_id" value="{{ combo.id }}"> <button type="submit" class="btn btn-success">Add to Cart</button> {% if combo in cart.combo_item.all %} <button type="submit" class="btn btn-success">Remove?</button> {% endif %} </form> combo - models.py class Combo(models.Model): title = models.CharField(max_length=120) cart - models.py class ComboCartItem(models.Model): combo = models.ForeignKey(Combo, blank=True, null=True, on_delete=models.CASCADE) class Cart(models.Model): combo_item = models.ManyToManyField(ComboCartItem, blank=True, null=True) -
How do I start building API for an application?
I am trying to build a currency exchange API using a third-party currency conversion API, which will allow users to sign up, sign in, and able to create, read, update user balance/wallet, and able to convert currency. Can anyone guide how to start? I am planning to use Django and Django REST Framework and will test using POSTMAN? -
How to make delete method in django extra action?
I was able to use extra actions to make an endpoint when I want to POST an ImageTag (ManyToMany Field) to my Image. I was also able to use lookup_field to make CharField instead of pk for accessing each Image. This is my sample endpoint when adding ImageTag: POST localhost:8000/my_app/images/IMG_123/image_tags/ I can POST something like this to the endpoint: {"image_tags": ["Urban", "Vegetation"]} This my source code: #models.py class ImageTag(models.Model): name = models.CharField() description = models.CharField() class Image(models.Model): image_id = models.CharField(unique=True) image_tags = models.ManyToManyField(ImageTag, blank=True) ... #serializers.py class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = '__all__' class ImageTagSerializer(serializers.ModelSerializer): image_tags = serializers.StringRelatedField(many=True) class Meta: model = Image fields = ('image_tags',) def to_internal_value(self, data): return data #views.py class CaptureExtraAction(viewsets.ModelViewSet): @action(detail=True, methods=['get', 'post', 'delete']) def image_tags(self, request, image_id=None): image = self.get_object() data = request.data.copy() image_tags = request.data.get('image_tags') if image_tags: data['image_tags'] = [] for tag in image_tags: obj_, created = ImageTag.objects.get_or_create( defaults={'name': tag}, name__iexact=tag ) image.image_tags.add(obj_) data['image_tags'] = image.image_tags.all() serializer = ImageTagSerializer(image, data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class ImageTagViewSet(ImageExtraAction, viewsets.ModelViewSet): queryset = Image.objects.all() serializer_class = ImageSerializer lookup_field = 'image_id' ... #urls.py router.register(r'images', ImageTagViewSet, basename='image') My next task is allowing DELETE method to remove an ImageTag from the object. For … -
Why Django Rest API id not in order?
So, I have django rest api with model like class Data(models.Model): node_id = models.ForeignKey("Node", on_delete=models.CASCADE) timestamp = models.DateTimeField() vibration = models.IntegerField() moisture = models.IntegerField() gps_latitude = models.CharField(max_length=250) gps_longitude = models.CharField(max_length=250) gyro_x = models.FloatField() gyro_y = models.FloatField() gyro_z = models.FloatField() accelero_x = models.FloatField() accelero_y = models.FloatField() accelero_z = models.FloatField() displacement = models.IntegerField() The serializer is like this: class DataSerializer(serializers.ModelSerializer): class Meta: model = Data fields = '__all__' And the views is like this : class DataViewSet(viewsets.ModelViewSet): queryset = Data.objects.all() serializer_class = DataSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['node_id'] You can access my api on : https://gmlews.com/api/data/ The problem is my id on the web page won't come in order. I receive all the data from raspberry pi. Where the problem come from? the code from raspberry or my django rest code? After id 253, it come id 255,257,259. It should be id 254 and so on in order. How can I handle this id to be in order? -
Django Categories and sub-categories based on Country
I am building a Django 2.2.x ecommerce,there is a model for Country, and model for Category, the Category model has a self foreign key and Country foreign key. Categories may differ from one country to another. However, my goal is this: The Parent (Root) categories can have a country but sub-categories should follow the country of their Parent category only. I hope I am clear enough. The models: class Country(models.Model): name = models.CharField(max_length=64, unique=True) slug = models.SlugField(default=None, max_length=2, unique=True) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=64) country = models.ForeignKey(Country, on_delete:models.PROTECT) parentId = models.ForeignKey('self', on_delete:models.PROTECT) slug = models.SlugField(default=None) def __str__(self): return self.name -
PyLint shows "Unable to import" error with app's module file in Django project
I have an app named "diary" in my Django project: school_diary/ diary/ <standart files inside app> views.py forms.py Inside my views.py I make this import: from . import forms PyLint marks it as error. Here's what I have inside my settings.json: { ..., "python.linting.enabled": true, "on.linting.pylintEnabled": true, "python.linting.lintOnSave": true, "python.linting.maxNumberOfProblems": 200, "python.linting.pylintPath": "/home/alantheknight/Python/Environments/secenv/bin/pylint", "python.pythonPath": "/home/alantheknight/Python/Environments/secenv/bin/python3.7", ... Also, I read about generating .pylintrc, so I ran this command: $ pylint --generate-rcfile > ~/.pylintrc Where have I made a mistake? -
Django rest framework: Rendering a field as read only in json renderer
I'm using React to dynamically display a table from JSON serialised by DRF. Only some of the columns are meant to be editable by the user, the rest are read-only. I'd like the serializer to specify which of the fields are read-only rather than explicitly setting it in the React app. Let's say I have a serializer like so: class Test_Serializer(serializers.ModelSerializer): class Meta: model = Change_Ticket fields = ['change_id','date','title','description'] read_only_fields = ['change_id'] extra_kwargs = {'change_id':{'read_only':True}} I'd like the output to be something similar to: [ { "change_id": { "CHG000001": {"read_only":True} } "date": "2020-05-21", "title": "Change Title goes here", "description": "Change Description" } ] Unfortunately, neither read_only_fields nor extra_kwargs work as they seems to have no effect on the rendered JSON. The style keyword seems to be applicable only when rendering to html rather than JSON. Just wondering if there is a simple way to achieve this or would I have to manually code for this behaviour using the to_representation method? -
Using ReportLab To Create A PDF Then Save It To A User Model
For a few days Ive been trying to get this working and, while I think im getting close, I still havent got it working yet. I have a function which uses ReportLab to generate a SimpleDocTemplate pdf and I want to return it to the calling view so I can save it to the uesrs Profile model. This is my code so far: model.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pdf = models.FileField(upload_to='pdfs/user_pdfs') the error message: 'HttpResponse' object has no attribute 'read' view def final_question(request): if request.method == 'POST': # this is the final form they complete form = FinalQuestionForm(request.POST, request.FILES, instance=request.user.finalquestion) if form.is_valid(): form.save() # generate pdf containing all answers to enrolment questions users_pdf = utils.generate_user_pdf(request) # here i get the users model # hard coded user_id for testing users_profile = Profile.objects.get(user_id=1) # then i get the field I want to save to pdf = users_profile.profile_pdf # then i save the generated pdf to the field pdf.save('user_1_pdf', users_pdf) my pdf generation function def generate_user_pdf(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename = "test.pdf"' doc = SimpleDocTemplate(response) elements = [] data= [ ['---TEST DATA---'], ['test data'], ] [.. cont ..] doc.build(elements) return response Thank you. -
ImageField is not working properly in form but works in admin Django
i cannot figure out why my ImageField is not working . I have included in my view request.Files and enctype="multipart/form-data" in my form. I have also ImageFiled with my new_article form i with my user forms and it works perfect. ImageField is not working with my comment form. so my comment text works just image can not upload with text . views.py posts = The_Article.objects.filter(article_choice=value) page = request.GET.get('page', 1) paginator = Paginator(posts,5) try: page = paginator.page(page) except PageNotAnInteger: page = paginator.page(1) except EmptyPage: page = paginator.page(paginator.num_pages) return render(request,'articles/articless.html',{'page':page}) def one_article(request,slug): posts = The_Article.objects.get(slug=slug) post = Comment.objects.filter(post=posts,replay=None).order_by('-id') page = request.GET.get('page', 1) paginator = Paginator(post,8) try: page = paginator.page(page) except PageNotAnInteger: page = paginator.page(1) except EmptyPage: page = paginator.page(paginator.num_pages) comment_count = post.all() if request.method == 'POST': new_comm = forms.New_Comment(request.POST,request.FILES) if new_comm.is_valid(): # remember new_comm is form of Comment object replay_id = (request.POST.get('comment_id')) parent = None if replay_id: parent = Comment.objects.get(id=replay_id) comm_save = new_comm.save(commit=False) comm_save.post = posts #this will be executed before/// post = Comment.objects.filter(post=posts,replay=None).order_by('-id') comm_save.replay = parent comm_save.user = request.user comm_save.save() else: new_comm = forms.New_Comment() context = {'posts':posts, 'post':post, 'page':page, 'new_comm':new_comm, 'comment_count':comment_count} if request.is_ajax(): html = render_to_string('articles/comment.html',context,request=request) ,context,,request=request) return JsonResponse({'form':html}) return render(request,'articles/one_article_page.html',{'posts':posts, 'post':post, 'new_comm':new_comm, 'page':page, 'comment_count':comment_count}) settings.py MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = … -
Django command python manage.py runserver is not working
The command python manage.py runserver is not giving any response. When i press enter after typing command then the only thing which i get is: HP@LAPTOP-3446CCM0 MINGW64 ~/downloads/src7/src7/mysite $ python manage.py runserver Watching for file changes with StatReloader Nothing after this appears on the screen. But when i press CTRL+C then something like this appears on the screen: $ python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. May 29, 2020 - 15:38:05 Django version 3.0.6, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. How to overcome through this -
Topic.entry_set Issue [Django]
I tried the fix from here but it still won't work. ReverseManyToOneDescriptor object has no attribute order_by django 2.1 What am I missing? entering http://localhost:8000/topics/1/ gives me Environment: Request Method: GET Request URL: http://127.0.0.1:8000/topics/1/ Django Version: 3.0.6 Python Version: 3.7.2 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'learning_logs') Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "E:\Personal projects\python\learning_log\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "E:\Personal projects\python\learning_log\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "E:\Personal projects\python\learning_log\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\Personal projects\python\learning_log\learning_logs\views.py", line 20, in topic entries = topic.entry_set.order_by('-date_added') # lowercase "t" Exception Type: AttributeError at /topics/1/ Exception Value: 'Topic' object has no attribute 'entry_set' This is my views.py from django.shortcuts import render from .models import Topic def index(request): """The home page for learning log""" return render(request, 'learning_logs/index.html') def topics(request): """Show all topics.""" topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) def topic(request, topic_id): """Show a single topic and all its entries""" topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') # lowercase "t" context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) Where is the issue? how can I use entry_set? … -
Understandig how to count using filters and combining models in django views
Yesterday I asked this question, because I need to count some data from my models. And the answer from @Willem Van Onsem was perfect. But now I want to count another fields, and I really don't understand how this filtering works. I have two models, Gateways and DevData, class Gateway(models.Model): gat_id = models.CharField(max_length=16, primary_key=True, unique=True) gat_name = models.CharField(max_length=20, unique=True) def __str__(self): return self.gat_name class DevData(models.Model): data_uuid = models.UUIDField(primary_key=True, default=uuid.uuid1, editable=False) gateway_id = models.IntegerField(null=True, blank=True) gateway_name = models.CharField(max_length=20, null=True, blank=True) data_timestamp = models.DateTimeField() data = models.FloatField() dev_eui = models.ForeignKey(Device, on_delete=models.CASCADE) #hay que saber porque añade _id def __str__(self): return self.dev_eui And I want to know how many data I received yesterday from each gateway. That is what I tried, yesterday = datetime.date(2020, 5, 28) gateway = Gateway.objects.filter( devdata__data_timestamp__date=yesterday ).annotate( total_data=Count('devdata') ) But this is a big fail. Can somebody help me? Thank you very much. -
What is the proper way to retrieve all class definitions that contain a specific mixin?
I'm working on a django application, and I want to create a mixin containing certain behaviors that aren't important for the question. However, I need to be able to retrieve a list of all the class definitions that inherit from this mixin. These classes can be in different apps within the django project. Possible answers I've found so far are: How to find all the subclasses of a class given its name? How to auto register a class when it's defined I'm mostly wondering what the best method would be to accomplish this goal. -
How to pass the specific object my form is editing into django?
If I have multiple objects of the same database model displayed on my page, and I want to have an edit button for each of them that allows you to edit the data of said object, how could I pass the data of which one I'm editing to my view so I could edit the fields of that specific database entry. Right now I have only one form <form method="POST" action="." id="projectForm"> {% csrf_token %} <legend class="border-bottom mb-4 formheader">Edit Assumption</legend> {{ form }} <div class="form-group" style="display: flex; justify-content: center; align-items: center;"> <button type="submit" class="createbutton" name="editassumptionformbutton">Save</button> </div> </form> I can make the onclick trigger the display of the form like this: <a onclick="toggleVisibilityEdit()">Edit</a> (which is a javascript function that displays the form) But I have no idea how to tell the view which of the objects I'm currently editing, how could I do that? -
Authentication credentials were not provided in Django
headers = { "content-type": "application/json", "Authorization": "JWT " + token, } post_data = json.dumps({"content": "Some Random Content"}) posted_response = requests.post(ENDPOINT, data=post_data, headers=headers) print(posted_response.text) Getting this error {"detail":"Authentication credentials were not provided."} Permissions and Authentications REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSE': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } -
Get live data of nse stocks of all symbols in python/Django
I m working on a stock prediction project. This is how I want: To show all the stocks available in Nifty50, Nifty100 or so and then the user will select the stock to predict the high and low price of a stock on next day only. I m using Django. What I have done till now: I m able to display a list of stock. def index(request): api_key = 'myAPI_Key' url50 = 'https://archives.nseindia.com/content/indices/ind_nifty50list.csv' url100 = 'https://archives.nseindia.com/content/indices/ind_nifty100list.csv' url200 = 'https://archives.nseindia.com/content/indices/ind_nifty200list.csv' sfifty = requests.get(url50).content shundred = requests.get(url100).content stwohundred = requests.get(url200).content nifty50 = pd.read_csv(io.StringIO(sfifty.decode('utf-8'))) nifty100 = pd.read_csv(io.StringIO(shundred.decode('utf-8'))) nifty200 = pd.read_csv(io.StringIO(stwohundred.decode('utf-8'))) nifty50 = nifty50['Symbol'] nifty100 = nifty100['Symbol'] nifty200 = nifty200['Symbol'] context = { 'fifty': nifty50, 'hundred': nifty100, 'twohundred': nifty200 } return render(request, 'StockPrediction/index.html', context) What I want: I want to get the live data of all stocks open, high,LTP,Change, Volume.by mean of live data is that it will change as per stock values will change. Please Help! -
how to solve no such column: todo_todo.title
I'm making a basic todo app in Django3. how to solve no such column: todo_todo.title error?? I can't solve this problem. here is my todo models and views. this is my todo/models.py from django.db import models from django.utils import timezone class Todo(models.Model): title=models.CharField(max_length=200) details=models.TextField() date=models.DateTimeField(default=timezone.now) def __str__(self): return self.title this is my views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import TodoForm from .models import Todo ############################################### def index(request): item_list = Todo.objects.order_by("-date") if request.method == "POST": form = TodoForm(request.POST) if form.is_valid(): form.save() return redirect('todo') form = TodoForm() page = { "forms" : form, "list" : item_list, "title" : "TODO LIST", } return render(request, 'todo/index.html', page) ### function to remove item, it recive todo item id from url ## def remove(request, item_id): item = Todo.objects.get(id=item_id) item.delete() messages.info(request, "item removed !!!") return redirect('todo') -
In Django Relation Manager has something changed between v1.10 and v3.0?
I am upgrading some code from Django 1.10 to Django 3.0 and have encountered a baffling problem relating to ManyToMany fields. Three models (among many others!) are defined as follows: migrations.CreateModel( name='FilteredDataSet', fields=[ ('dataset_ptr', models.OneToOneField(auto_created=True, parent_link=True, primary_key=True, serialize=False, to='dataset.DataSet', on_delete=django.db.models.deletion.CASCADE)), ('dataset', models.ForeignKey(related_name='source_data_set', help_text='The dataset this filter is applied to', to='dataset.DataSet', on_delete=django.db.models.deletion.CASCADE)), ::: ], bases=('dataset.dataset',), ), migrations.CreateModel( name='MaterialisedDataSet', fields=[ ('dataset_ptr', models.OneToOneField(auto_created=True, parent_link=True, primary_key=True, serialize=False, to='dataset.DataSet', on_delete=django.db.models.deletion.CASCADE)), ('dataset', models.ForeignKey(related_name='materalised_source_data_set', help_text='The dataset this filter is applied to', to='dataset.DataSet', on_delete=django.db.models.deletion.CASCADE), ::: ], bases=('dataset.dataset',), ), migrations.CreateModel( name='SurveyRunDataSet', fields=[ ('dataset_ptr', models.OneToOneField(auto_created=True, parent_link=True, primary_key=True, serialize=False, to='dataset.DataSet', on_delete=django.db.models.deletion.CASCADE)), ('survey_run', models.ForeignKey(help_text='Survey run for the Cassandra responses', to='survey.SurveyRun', null=True, on_delete=django.db.models.deletion.CASCADE)), ::: ], bases=('dataset.dataset',), ), But the app errors at the line indicated below: class AggregateDataSet(DataSet): """ A collection of DataSets with conformant schema items. It is assumed that component DataSets have RowKey sets with a null intersection. datasets = models.ManyToManyField(SurveyRunDataSet, help_text="Set of datasets for this aggregate") ::: def update_datasources(self): ::: self.datasets.clear() <--- Fine at Django 1.10, FAILS at Django 3.0 I have studied the Django Relation Manager documentation until I am blue in the face, but I can see nothing wrong with this code. Any ideas? Has some incompatible change been made, and if so how can I adapt the …