Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have a question about displaying the data and html element with condition in django
I have a <div> tag which has bootstrap card class inside. Inside that card I have some data. Right now I use default_if_none:"&nbsp;" to not display the data when the data is none but the card class still render out to the template. The question is How can I not display both the data and the div tag with card class when the data is none? In simple words, When there is no data it won't render div tag. <div class="card" style="background-color: rgb(243, 243, 243);"> <div class="card-top"> <pre class="mt-3" style="font-size: 16px; left: 0; margin-left: -130px;"> <code class="prettyprint"> {{ post.content|default:"&nbsp;" }} </code> </pre> </div> </div> -
Obtain multiple model associated in a single query according some conditions in Django
I have a Car model which has multiple associations with other models through foreignkeys and manytomany fields, in this case a Car have one Owner and has Many Obligations. Model relationship class Car(TimeStampedModel, models.Model): owner = models.ForeignKey( to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name=_("Owner") ) class Obligation(TimeStampedModel, models.Model): """Representation of the obligations that a car should have up to date.""" car = models.ForeignKey(to=Car, on_delete=models.CASCADE) expiration_date = models.DateField( verbose_name=_("Expiration Date"), default=date.today, ) Expected result I expect to obtain those cars with expired obligations and from these cars to have their owner and those expired obligations. What I've tried 1. Obtain those cars with obligation expired For this task I create a custom Car Manager that retrieve those cars with expired obligations: class CarManager(models.Manager): """Define a manager for Car model.""" def with_obligations_expired(self) -> "QuerySet[Car]": """Returns a Car given where there is at least one Obligation that is expired.""" return ( self.get_queryset() .filter(obligation__expiration_date__lte=date.today(), get_today()]) .distinct() ) 2. Obtain owners of that cars with obligations expired I run the custom manager method with_obligations_expired() to obtain the cars with obligation expired. Through the result I can access the owners and the obligations of that vehicle. cars_with_expired_obligations = Car.objects.with_obligations_expired() owners = [car.owner for car in cars_with_expired_obligations] obligations = # ...something … -
Does Django save zipped directories as files or what could be going on here?
I'm working with OpenEdX, it has a plugin system, called XBlocks, that in this case allows importing content created by third party "studio apps." This content can be uploaded as a zip file. it is then processed by the following code: @XBlock.handler def studio_submit(self, request, _suffix): self.display_name = request.params["display_name"] self.width = request.params["width"] self.height = request.params["height"] self.has_score = request.params["has_score"] self.weight = request.params["weight"] self.icon_class = "problem" if self.has_score == "True" else "video" response = {"result": "success", "errors": []} if not hasattr(request.params["file"], "file"): # File not uploaded return self.json_response(response) package_file = request.params["file"].file self.update_package_meta(package_file) # First, save scorm file in the storage for mobile clients if default_storage.exists(self.package_path): logger.info('Removing previously uploaded "%s"', self.package_path) default_storage.delete(self.package_path) default_storage.save(self.package_path, File(package_file)) logger.info('Scorm "%s" file stored at "%s"', package_file, self.package_path) # Then, extract zip file if default_storage.exists(self.extract_folder_base_path): logger.info( 'Removing previously unzipped "%s"', self.extract_folder_base_path ) recursive_delete(self.extract_folder_base_path) with zipfile.ZipFile(package_file, "r") as scorm_zipfile: for zipinfo in scorm_zipfile.infolist(): default_storage.save( os.path.join(self.extract_folder_path, zipinfo.filename), scorm_zipfile.open(zipinfo.filename), ) try: self.update_package_fields() except ScormError as e: response["errors"].append(e.args[0]) return self.json_response(response) where the code default_storage.save( os.path.join(self.extract_folder_path, zipinfo.filename), scorm_zipfile.open(zipinfo.filename), ) is the origin of the following (Django) error trace: cms_1 | File "/openedx/venv/lib/python3.5/site-packages/openedxscorm/scormxblock.py", line 193, in studio_submit cms_1 | scorm_zipfile.open(zipinfo.filename), cms_1 | File "/openedx/venv/lib/python3.5/site-packages/django/core/files/storage.py", line 52, in save cms_1 | return self._save(name, content) cms_1 | … -
django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured
Python is version 3.7.6, Django is version 3.0.8, I am trying to deploy from aws, but adding container_commands gives an error container_commands and DATABASES code - container_commands: 01_migrate: command: "django-admin.py migrate" leader_only: true 02_compilemessages: command: "django-admin.py compilemessages" option_settings: aws:elasticbeanstalk:container:python: WSGIPath: config.wsgi:application aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: config.settings - DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "HOST": os.environ.get("RDS_HOST"), "NAME": os.environ.get("RDS_NAME"), "USER": os.environ.get("RDS_USER"), "PASSWORD": os.environ.get("RDS_PASSWORD"), "PORT": "5432", } } The problem seems to be caused by django-admin.py migrate Enter django-admin.py migrate command django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I get this message, I don't know how to fix it, I need help,thankyou -
Django doesn't load images from media
I've set things for the setting and the URLs as follow but it doesn't load the images from media directory: settings.py: STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, '/media/') urls.py: urlpatterns = [ path('create/', views.image_create, name='create'), path('detail/<int:id>/<slug:slug>/', views.image_detail, name='detail'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have another app named accounts and if I add the base URL of account to the first of this media URLs it works! but I know they are separated from each other. if you need other parts of code please tell me. -
Post hardcoded data using django and angularjs appservice?
I have this hardcoded json data in models.py I have called that from API in views.py. I have got that url link in views. The thing is I have to display that data in html using angular js app service function? views.py def gdata(request): if request.method == 'POST': jsondata = json.loads(request.body.decode('utf-8')) headers = {"content-type": "application/json", "Authorization": 'Token 71117971142'} resp = requests.get("http://127.0.0.1:8000/attdata", params="", data="", headers=headers, verify=False) responses = resp.content.decode("utf-8") return HttpResponse(responses) app service angularjs code app.service( function($http) { this.fn_ss_gdata = function(datap) { var response = $http.post( "/gdata/", datap); return response; } }); I have called the data from that url using app service method in angular js. But I am unable to display the data using html. The url above is a fake one.So help me to display the data from app service using html -
What is the equivalent of dash callback in plotly js
I had to build a dashboard , so dash seemed pretty easy. But i faced lot of issues integrating with flask or django. So I had to rebuild the dashboard with django framework with plotly.js , while using plotly dash @app.callback() was very fast and quick in updating the graphs. To mock the similar behaviour I tried using ajax in django and plotly.js. Even though the job gets done using ajax, i see there is a lag in performance, it takes 3-4 secs to render the updated graph. Is there a better or efficient way to achieve similar performance of dash callbacks in django/ajax ? Just because every time i have to read the csv file during ajax call , hinders my performance ? sample backend code for ajaxcall def itemsAjax(request): if request.is_ajax(): itemsList = request.POST.get('items') #itemsList = ast.literal_eval(itemsList) #itemsList = [n.strip() for n in itemsList] itemsList=itemsList.split(',') daterange = request.POST.get('daterange').split('-') franchise = request.POST.get('franchise') startDate = dt.strptime(daterange[0].strip(),'%m/%d/%Y') endDate = dt.strptime(daterange[1].strip(),'%m/%d/%Y') df = at.readData() flag = ut.determineFlag(startDate,endDate) df = at.filter_df_daterange(df,startDate,endDate) itemTrend_df = at.getDataForItemsTrend(df,startDate,endDate,flag) itemTrend_plt = [{'type':'scatter', 'x' : itemTrend_df[itemTrend_df['S2PName']==item]['S2BillDate'].tolist(), 'y' : itemTrend_df[itemTrend_df['S2PName']==item]['totSale'].tolist(), #'text' : itemTrend_df[itemTrend_df['S2PName']==item]['Hover'], 'mode' : 'markers+lines', 'name' : item }for item in itemsList] return JsonResponse({'itemTrend_plt':itemTrend_plt}) else: return HttpResponse(' Not authorised!') -
Hello to everyone! How can I add favorite products to user instance in Django Rest Framework?
Friends, now I am working with Django Rest Framework. I have User model, Product model and Favourite Product model. How can I add favorite products to user instance in Django Rest Framework? I added but I am not sure. did I it right? models.py class UserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): """Creates and saves new user""" if not email: raise ValueError('Введите электронную почту') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """Creates and saves a new super user""" user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): """Custom user model that supports using email instead of username""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) surname = models.CharField(max_length=255, default='Фамилия') is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) favorite_product = models.ForeignKey( 'FavoriteProduct', related_name='favorite_products_for_user', on_delete=models.SET_NULL, null=True ) objects = UserManager() USERNAME_FIELD = 'email' I added Favorite Product to User model but I can not see users data like picture 1. Picture 1. models.py class FavoriteProduct(models.Model): """Favorite product object""" created = models.DateTimeField(auto_now_add=True, null=True) product = models.ForeignKey( 'Product', related_name='favorite_products', on_delete=models.CASCADE, null=True ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) serializers.py in user package Here, should I add list method, to see user information in Django web page … -
Is there any easy way to update HTML files for a VPS django server?
Somebody coded a Django website for me and hosted a VPS server using linode . Now the website is fully functioned . Then he gave me the source folders and server password. My computer is window and I can't connect the server with cmd console . I just want to update some HTML files . Is there any easy way to updates HTML codes for a VPS server ? ( connecting its ftp server and updating HTML files? ) -
Django formset displays no field
I'm trying to create a multiple select form for order, where a user can select multiple items in the cart and enter the quantity of each item. But my form is only displaying delete and checkboxes not the cart model fields. models.py class Cart(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) amount = models.IntegerField(default=1) def __str__(self): return str(self.product) class Product(models.Model): stockId = models.AutoField(primary_key=True) product_name = models.CharField(max_length=100) product_type = models.CharField(max_length=100) stock = models.IntegerField(default='0', blank=True, null=True) def __str__(self): return self.product_name class Order(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=30) date_created = models.DateTimeField('date_created', default=timezone.now(), blank=False) cart = models.ManyToManyField('Cart') status_choices = (('Processing', 'Processing'), ('Shipped', 'Shipped'), ('Delivered', 'Delivered'), status = models.CharField(max_length = 100, choices = status_choices) views.py def create_order(request): OrderFormSet = inlineformset_factory(Cart, Order, fields=('product',)) formset = OrderFormSet(request.POST or None, request.FILES or None) if request.method == 'POST': if form.is_valid(): order.user = request.user; order.save() form = OrderForm(user=request.user) return redirect('/orderlist') context = {'formset':formset} html_form = render_to_string('order_form.html', context, request=request, ) return JsonResponse({'html_form': html_form}) HTML file <form method="post" action="{% url 'accounts:create-order' %}" class="create-form"> {% csrf_token %} {{formset|crispy}} </form> -
Django3 - Issue usign model from another app possibly routing issue
I have a record label website im building and I want to populate a navbar dropdown list with artists from the Artst object Artist.objects.all(). I have it working in one app "music" but only when I append "/artistlist/" onto the end. Any other URL doesnt populate the list. I have tried adding a copy of the view and url regex to my main urls file and set teh regex to trigger with two forward slashes "http://127.0.0.1:8000//" and that worked, but I want the list to always be there as its a navbar item. I could use some help as I'm clearly doing something stupid, or overlooked something basic. On all other urls it triggers the else I added "We currently dont have any artists yet..". Hope it makes sense to someone. Any help is greatly appreciated. base.html <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <div class="dropdown-item" href="#"> {% if all_artists %} <ul> {% for artist in all_artists %} <li class="dropdown-item"> <a href="{% url 'music:artist' artist.id %}"> <img src="{{ artist.artist_logo.url }}" style="width: 100px"><br> {{ artist.artist_name }}<br> {{ artist.artist_url }}<br> </a> </li> {% endfor %} </ul> {% else %} <h3>We currently dont have any artists yet..</h3> {% endif %} </div> </div> main urls.py from django.contrib import … -
Can't Click Element In Selenium Because 'Object Obscures It'
This selenium functional test was working a week ago. Since then I have made a lot of changes to this page and now the test is failing with selenium.common.exceptions.ElementClickInterceptedException: Message: Element <input id="id_test_date" class="checkboxinput custom-control-input" name="test_date" type="checkbox"> is not clickable at point (8,470) because another element <label class="custom-control-label"> obscures it I have tried waiting for the element to load, but it doesn't help. This is the html <div class="form-group"> <div id="div_id_test_date" class="custom-control custom-checkbox"> <input type="checkbox" name="test_date" class="checkboxinput custom-control-input" id="id_test_date"> <label for="id_test_date" class="custom-control-label"> Do you know what month you will take the test? </label> </div> </div> I don't know of the ::before:: is causing the issue, if it is I don't know why as it didn't used to be an issue and I don't know how to fix it. I think this is unrelated, but I get the following error msg in console Uncaught TypeError: option required is not recognized! at Boolean.<anonymous> (bootstrap-datetimepicker.min.js:1) I have searched a lot and can't find a solution, many people seem to fix this issue by waiting for the element to load. Any help would be greatly appreciated. Thank you. -
How do I create ajax functions for the whole site?
I am creating a notification center, naturally it must be visible throughout the site; So the question is how do I do it. Create a name.js file inside the static folder but it seems that something is missing since apart from the delay in the app itself it is not visible outside it. view.py @csrf_exempt def NewsSubjects(request): if request.is_ajax() == True: queryset = Downloads.objects.all().order_by('register_date').values()[:5] print("cantidad\t",queryset.count()) data=list(queryset) return JsonResponse(data, safe=False) urls.py path('alerts/', views.NewsSubjects, name='alerts'), /static/js/notifications.js $.ajax({ // initialize an AJAX request url: "alerts", // al estar en static no se usa el name del URL ('control:alert') sino el PATH (alerts/) type: "GET", datatype:'json', success: function(data) { console.log('cambio') var opciones = document.getElementById("nuevasDisciplinas"); var countAlert = document.getElementById("countAlert"); var listaDisciplinas = '' for (var i = 0; i < data.length; i++) { // console.log(data[i]); var nombDis = data[i].category_name var fechaCreacion = data[i].register_date // var d = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(fechaCreacion) // var m = new Intl.DateTimeFormat('en', { month: 'short' }).format(fechaCreacion) // var a = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(fechaCreacion) var icon = '<divclass="mr-3"><divclass="icon-circle bg-primary"><iclass="fas fa-file-alt text-white"></i></div></div>' var body ='<div><divclass="small text-gray-500">'+fechaCreacion+'</div><spanclass="font-weight-bold">'+nombDis+'</span></div>' listaDisciplinas += icon+body } opciones.innerHTML = listaDisciplinas; countAlert.innerHTML = data.length; }, error: function() { console.log("The information could not be obtained"); } … -
Reusing a template in Django by passing different arguments in custom template tags
I trying to create 2 separate views to show parts required and parts produced for an activity/job. The model uses a boolean 'increment' field for filtering True (parts produced) and False (parts required) and to increment/decrement parts from the inventory. I'd like to reuse the same template in Django by passing the increment=True/False through the custom template tags for each button in the activity view. However I keep getting an error django.urls.exceptions.NoReverseMatch: Reverse for 'addrequired' with keyword arguments '{'id': '1', 'increment': False}' not found. 1 pattern(s) tried: ['activities/activity/(?P<id>[^/]+)/addrequired$'] urls.py from django.urls import path from .views import * urlpatterns = [ ... path('activity/<str:id>/addrequired', add_required_part_to_activity, name='addrequired'), infoActivity.html <div class="col-sm"> <br> <table class="table table-hover"> <thead> <tr> <th>Parts Required</th> </tr> </thead> <tbody> {% for required in activitypartsrequired %} <tr data-href="{% url 'info_part' required.part.id %}"> <td>{{ required.part.partnumber }}</td> <td>{{ required.part.description }}</td> <td>{{ required.quantity }}</td> </tr> {% endfor %} </tbody> </table> <a href="{% url 'addrequired' id=id increment=False %}" class="btn btn-secondary btn-sm btn-pad" role="button">Add Required Part</a> <table class="table table-hover"> <thead> <tr> <th>Parts Produced</th> </tr> </thead> <tbody> {% for produced in activitypartsproduced %} <tr data-href="{% url 'info_part' required.part.id %}"> <td>{{ produced.part.partnumber }}</td> <td>{{ produced.part.description }}</td> <td>{{ produced.quantity }}</td> </tr> <a href="{% url 'addrequired' id=id increment=True %}" class="btn btn-secondary … -
Implement variable waited for loop in Python
Consider I want to implement the following logic: def fetch_only_once(ids: List[Thing]): # lookup every id every 10s # lookup(ids[0]) # wait 10s # lookup(ids[1]) # wait 10s # ... # example implementation using id for (i, id) in enumerate(ids): threading.Timer(10 * i, lookup, arg=id) Note that these lookup are individual requests to a random server. The biggest issue here is that the number of threads is in the order of number of elements. Based on my limited knolwedge of python, I don't think the language scales very well with multiple threads, with especially an arbitrary large number of threads. I am unsure what the right solution looks like here, but here's an idea: def f(): thread = create_thread() for (i, id) in enumerate(ids): wait(timer=10) # non blocking thread.async_dispatch(job) async_dispatch simply dispatches a job on the thread queue every 10s. Some lookups may not finish in time so the queue can stall. I am not sure if there is a construct in python that deals with something like this, but any ideas will be helpful. -
Gitlab CI bash: gunicorn: command not found
I am trying to deploy Django project on AWS Linux(RHEL/Centos). I use Gunicorn to run my Django project via python3 virtualenv and use Gitlab to do ci/cd. But it fail when i use gunicorn command. Here is response from gitlab-runner. WARNING: You are using pip version 20.1.1; however, version 20.2 is available. You should consider upgrading via the '/usr/bin/python3 -m pip install --upgrade pip' command. No changes detected bash: gunicorn: command not found ERROR: Job failed: exit code 1 This is code in .gitlab-ci.yml aws_deploy: stage: deploy before_script: # Generate ssh key - mkdir ~/.ssh - echo -e "$SSH_PRIVATE_KEY" > ~/.ssh/id_rsa - chmod 600 ~/.ssh/id_rsa - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config' - apt-get update - apt-get install python3-pip -y - pip3 install gunicorn - gunicorn --version script: - echo "deploy" - bash .gitlab-deploy-prod.sh only: - devop And this is .gitlab-deploy-prod.sh #!/bin/bash # Get server list set -f string=$DEPLOY_SERVER array=(${string//,/}) # Iterate servers for deploy and pull last commit for i in "${!array[@]}"; do echo "Deploy project on server ${array[i]}" ssh ec2-user@${array[i]} "cd backend && git pull && sudo cp -r /home/ec2-user/backend /var/ && cd /var/ && ./build_project.sh && cd /var/venv/bin/ && source ./activate … -
Changing from Slug to Id to post an item
I am trying to change from Slug to Id related to an item in order to fix a bug related to quantity in my project. So I have switched everything from slug to id but i keep getting Page not found (404) No Item matches the given query. I have updated the Models functions, View, URLs and template related to the order summary, I am not sure if there something else I need to update Here are my models which I started with: class Item(models.Model): title = models.CharField(max_length=100) def get_add_to_cart_url(self): return reverse("core:add-to-cart", kwargs={ 'id': self.id }) def get_remove_from_cart_url(self): return reverse("core:remove-from-cart", kwargs={ 'id': self.id }) Here are my urls: app_name = 'core' urlpatterns = [ path('', HomeView.as_view(), name='home'), path('product/<slug>/', ItemDetailView.as_view(), name='product'), path('add-to-cart/<id>/', add_to_cart, name='add-to-cart'), path('remove-item-from-cart/<id>/', remove_single_item_from_cart, name='remove-single-item-from-cart'), path('remove-from-cart/<id>/', remove_from_cart, name='remove-from-cart'), Here are the views: @login_required def add_to_cart(request, id): item = get_object_or_404(Item, id=id) order_item_qs = OrderItem.objects.filter( item=item, user=request.user, ordered=False ) item_var = [] # item variation if request.method == 'POST': for items in request.POST: key = items val = request.POST[key] try: v = Variation.objects.get( item=item, category__iexact=key, title__iexact=val ) item_var.append(v) except: pass if len(item_var) > 0: for items in item_var: order_item_qs = order_item_qs.filter( variation__exact=items, ) if order_item_qs.exists(): order_item = order_item_qs.first() order_item.quantity += 1 … -
Error deploying django website on docker through heroku - "Your app does not include a heroku.yml build manifest"
I am in the final steps of deploying a django website. It uses docker to run it and I'm finally deploying it through heroku. I run into an error when running "git push heroku master". I receive "Your app does not include a heroku.yml build manifest. To deploy your app, either create a heroku.yml: https://devcenter.heroku.com/articles/build-docker-images-heroku-yml". This is odd as I do in fact have a heroku.yml app. heroku.yml setup: addons: - plan: heroku-postgresql build: docker: web: Dockerfile release: image: web command: - python manage.py collectstatic --noinput run: web: gunicorn books.wsgi The tutorial I am following is using "gunicorn bookstore_project.wsgi" but I used books.wsgi as that is the directory my website is in. Neither worked. -
Django REST: How to access to the POST request object
I'm trying to make a POST request to the server using axios in React.js .I have not errors sending the object from the front end to the back end (when the request is send, Django returns 200). Nevertheless, I can't access to the object's information: I have several fields, one of them is 'name'. When I try: views.py @api_view(['POST']) @permission_classes((permissions.AllowAny,)) def join_us(request): print(request.POST.get('name')) #This returns None return Response('test ') form.js formHandler=(event)=>{ event.preventDefault(); this.setState({loading:true}); const data = {...this.state}; console.log(data); //This print the object information, nothing is wrong here axios.post('https://127.0.1.1:8000/api/join_us/', data) } What is the right way to access to the sent object ? -
Django select more than 1 product and quantity
I have 3 models Cart, Product, and Order. I'm using the order model form to create an order, the order model is connected to the cart model with many to many relationship and The cart model is connected to product model with a foreign key, using the foreign key I can add products in the cart . Currently, I'm only able to create select more than 1 product and the quantity of each product in Django admin using the plus sign.I want to have to same functionality in my django form where I can select more than 1 product, quantity of each product and create the order. models.py class Cart(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) amount = models.IntegerField(default=1) def __str__(self): return str(self.product) class Product(models.Model): stockId = models.AutoField(primary_key=True) product_name = models.CharField(max_length=100) product_type = models.CharField(max_length=100) stock = models.IntegerField(default='0', blank=True, null=True) def __str__(self): return self.product_name class Order(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=30) date_created = models.DateTimeField('date_created', default=timezone.now(), blank=False) cart = models.ManyToManyField('Cart') status_choices = (('Processing', 'Processing'), ('Shipped', 'Shipped'), ('Delivered', 'Delivered'), status = models.CharField(max_length = 100, choices = status_choices) forms.py class OrderForm(forms.ModelForm): item = forms.ModelChoiceField(queryset=Item.objects.all()) class Meta: model = Order fields = '__all__' -
How can I just update one field at the time using mutation? graphene-django
Here's the code I wrote to update my task class UpdateTask(graphene.Mutation): class Input: id = graphene.ID() description = graphene.String(required=False) completed = graphene.Boolean() task = graphene.Field(Task) @classmethod def mutate(cls, root, info, **kwargs): task = Tasks.objects.get(id=kwargs.get('id')) task.description = kwargs.get('description') task.completed = kwargs.get('completed') task.save() return cls(task=task) But at the time I want to update the task, the description field is required, even when I specified that is not. Any idea how to solve it? -
How can I fetch a django rest api in vue native?
how can I fetch a django rest api into my vue native app? is this link (https://codesource.io/build-a-crud-application-vue-and-django/) a proper explanation of how to fetch a django rest api in vue native? -
How to return return multiple objects using get_context_data
The application is intended to serve a single user. I am attempting to stuff multiple model classes objects inside of the get_context_data method. My issue is when I go to call the context variable in my template all I get is the query set. If i call a specific item in the query set all I see is a location in memory. If I call the context varriable 'data' in a for loop inside of the template I get nothing at all. According to the django docs, this logic should work. What step am i missing? Or would I be better served using a function based view? my model class backend(models.Model): lang1 = models.CharField(max_length=50) lang2 = models.CharField(max_length=50) lang3 = models.CharField(max_length=50) def __str__(self): return 'Backend Language' class frontend(models.Model): lang1 = models.CharField( max_length=50) lang2 = models.CharField(max_length=50) lang3 = models.CharField(max_length=50) def __str__(self): return 'Frontend Language' class datalayer(models.Model): lang1 = models.CharField( max_length=50) lang2 = models.CharField(max_length=50) lang3 = models.CharField(max_length=50) def __str__(self): return 'Database Language' my view from django.shortcuts import render from django.views.generic import View, TemplateView, ListView from cbvapp.models import backend, frontend, datalayer class Index(ListView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['data'] = [backend.objects.all(), datalayer.objects.all(), frontend.objects.all()] return context -
error while creating superclass django postgresql
while creating new superclass. winpty python manage.py createsuperuser . getting usage: manage.py createsuperuser [-h] [--username USERNAME] [--noinput] [--database DATABASE] [--email EMAIL][--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [-- traceback] [--no-color] [--force-color] [--skip-checks] manage.py createsuperuser: error: unrecognized arguments: . insted of login details (email and password). ALSO after i remove the unrecognized arguments: . i get.. django.db.utils.OperationalError: FATAL: password authentication failed for user "postgresuser" and if i write python3 instead of python then NameError: name 'DatabaseClient' is not defined -
How to access @property variable in django template
I have a dropdown choice that an editor in Wagtail can use to choose an icon. Their choice will be mapped to a preset list of static assets. I'm trying to use a calculated attribute to get the path to the icon. I then want to use that within my template. Something is wrong. The template always returns blank src="static/". How can I accomplish this? panel template: {% for card in card_list %} <div> <img class="card__icon" src="{% static card.svg_url %}"> </div> {% endfor %} class CardBlock(blocks.StructBlock): icon = blocks.ChoiceBlock(choices=[ ('calendar', 'Calendar'), ('flag', 'Flag'), ]) @property def svg_url(self): svg_map = { 'calendar': 'img/calendar.svg', 'flag': 'img/flag.svg', } return svg_map[self.icon] class PanelBlock(blocks.StructBlock): heading = block.CharBlock() card_list = blocks.ListBlock( CardBlock(), ) class Meta: template = "website/blocks/panel.html"