Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I pull something other than the str value from a FK relation?
How do I pull something other than the str value from a FK relation? I have 2 Models, Client and Service Visit. I have the client as an FK in the ServiceVisit model, and when I loop through the ServiceVisits I can pull all data from the ServiceVisit table but I need to get the associated Clients address and print it but I can't seem to pull the ServiceVisit and work backward to also get the Associated clients address but it just wants to show me the Clients name because that's what I have in the __ str __ on it's model. Client Model class Client(models.Model): #Billing and Shipping Addresses address = models.CharField('Address Line 1', max_length=200, null=True, blank=True, unique=True) address2 = models.CharField('Address Line 2', max_length=200, null=True, blank=True) city = models.CharField('City', max_length=200, null=True, blank=True) zipcode = models.CharField('Zip Code', max_length=200, null=True, blank=True) state = models.CharField('State', max_length=2, null=True, blank=True, choices=STATE_CHOICES) country = models.CharField('Country', max_length=200, null=True, blank=True, default='USA') ServiceVisit Model class ServiceVisit(models.Model): address = models.OneToOneField(Client, on_delete=models.CASCADE, to_field='address', related_name='client_addresses') client_id = models.ForeignKey('Client', on_delete=None, null=True, blank=True) customer_service_rep = models.ForeignKey(settings.AUTH_USER_MODEL, to_field='extension', on_delete=None, blank=True, null=True, limit_choices_to= Q( groups__name = 'Customer Service')) remove_csr_credit = models.CharField(default="0", max_length=20, choices=ISTRUE) driver = models.ForeignKey('Driver', on_delete=models.CASCADE, null=True, blank=True) vehicle = models.ForeignKey('Vehicle', on_delete=models.CASCADE, null=True, blank=True) … -
Load page and content (graphs) separately
I have a Django website that contains a page with a lot of big data graphs. To build these graphs a few big queries are made, which causes the page to take a long time to load. As the data keeps growing, I've been trying to optimize the queries, but still it doesn't load very fast. Now my question is what I could do to make the page load separately from the graphs. So, the website would load, the user would see the navigation bar, and the outline of the graphs. Meanwhile the graphs would be build up using the data from the database. I've seen this happening on some websites, for example the Office Exchange admin panel, which shows the outline of the graph, while a loading icon is shown and the data will slowely fill said graph. I've looked into possible solutions but couldn't really find a satisfying answer. I found Celery which can be used to separate code tasks, but I'm not sure whether this is what I'm looking for here, as I basically only have two tasks. The basic website and the graphs after that. Could someone tell me whether Celery is the actual way to … -
python importing module from another module in same folder for both django project and self-executable
I am having trouble with importing another module (mod2.py) into a module (mod1.py). mod1 will be imported into a views.py of a django project, as well as into a self-executable python script (main.py). Now mod1 and mod2 are located in same folder as view.py and main.py. I have tried various of ways to import mod2 into mod1, but cannot achieve a success for both projects. Here are the ways I have tried: 1) In mod1.py, if I write as following: import mod2 then main.py is okay, but django (python manage.py runserver) will say: ModuleNotFoundError: No module name named 'mod2' 2) In mod1.py, if I write: from . import mod2 then django project starts without error, but main.py will say: ImportError: attempted relative import with no known parent package Python is v3.7.4. In both scenario, I am using in views.py: from .mod1 import class1, class2 and in main.py: import mod1 Any solution so I can make it work for both projects? Thanks in advance. -
Django api receiving a csv file
I am new to django and I want to build a django view that accepts a csv file and parse it. @permission_classes([AllowAny]) class FileUploadView(views.APIView): parser_classes = (MultiPartParser, ) def post(self, request, format=None): print(request.data) return JsonResponse({'message': 'good !'}, status=202) The problem is that when I query this api I get an error. here is how I query it: with open('dispatch.csv', 'rb') as f: res = requests.post("http://127.0.0.1:8000/api/mds/generate_from_csv/", data={'file': f}, headers={"Content-Type": "multipart/form-data"}) print(res.raise_for_status()) This is the error message that I get: requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: http://127.0.0.1:8000/**** -
Display an image from a model object in Django
So I have this model: class Inssurance(models.Model): name = models.CharField(max_length=45, blank=False) user = models.ForeignKey(User, on_delete=models.CASCADE) address = models.TextField(blank=True) logo = models.FileField(blank=True) city = models.ForeignKey(City, models.SET_NULL, blank=True, null=True) phone = models.CharField(max_length=15, blank=True) fax = models.CharField(max_length=15, blank=True) date_posted = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name And this one: class Folder(models.Model): #Dossiers sinistre numero = models.CharField(max_length=20, default=dossier_number, editable=False) created_by = models.ForeignKey(Prestataire, on_delete=models.SET_NULL, null=True) matricule = models.CharField(max_length=10, default="XXXXX-A-1") Inssurance= models.ForeignKey(Inssurance, on_delete=models.SET_NULL, null=True) And I am working on the Folder's template and I want to display the image of the related Inssurance. This is what I came up with but the image does not get displayed: <img src="{{folder.inssurance.logo.url}}" alt=""/> This is what I found when I run the server: The image is not found, and when I right-click on it and click on View Image, it gives me a 404 error, even though when I check in my server, I find the image uploaded. There are my media settings: STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' -
Nginx returning server error 500 after rest-auth login or registration
I am trying to set up authentication on my django app using rest-auth. It works perfectly on the development server, then I pushed to production and started getting server error 500 after every successful login or registration. This is my urls.py file: urlpatterns = [ path('admin/', admin.site.urls), path('rest-auth/', include('rest_auth.urls')), path('rest-auth/registration/', include('rest_auth.registration.urls')), path('api/', include('backend.urls')), ] This is my nginx conf: location /{ include proxy_params; proxy_pass http://unix:/myapp/path/gunicorn.sock; } Every route opens correctly even /rest-auth/login, but once I submit the login form or registration form I get the server error but it never happens on development server. I have tried to make changes in the nginx conf but it didn't work. Every other route works, can this problem be with nginx or rest-auth(it works on development)? -
How to set up nginx configuration site for django
I have a problem with nginx and django. Config: server { listen 80; server_name 193.88.95.120; charset utf-8; root /root/djangoprojects/megaproject; client_max_body_size 75M; location /media { alias /root/djangoprojects/media/; } location /static { alias /root/djangoprojects/megapproject/megaapp/static/; } location / { include /root/djangoprojects/megaproject/uwsgi_params; } } Error 403 - forbidden. When I create an index file in the project folder .html " - it opens. But I need Django to work. Please help me. -
Django ModelAdmin admin_order_field with nulls_last
I am trying to sort column of ModelAdmin list field with admin_order_field with nulls_last such as: class UserProfileAdmin(admin.ModelAdmin): def get_sum_amount(self, obj): return obj.sum_amount get_sum_amount.admin_order_field = F('sum_amount').desc(nulls_last=True) But I am getting following error: Traceback (most recent call last): File "/home/petr/.local/share/virtualenvs/aklub_project-HrPEZ5ak/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/petr/.local/share/virtualenvs/aklub_project-HrPEZ5ak/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/petr/.local/share/virtualenvs/aklub_project-HrPEZ5ak/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/petr/.local/share/virtualenvs/aklub_project-HrPEZ5ak/lib/python3.6/site-packages/django/contrib/admin/options.py", line 606, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/petr/.local/share/virtualenvs/aklub_project-HrPEZ5ak/lib/python3.6/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/petr/.local/share/virtualenvs/aklub_project-HrPEZ5ak/lib/python3.6/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/petr/.local/share/virtualenvs/aklub_project-HrPEZ5ak/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 223, in inner return view(request, *args, **kwargs) File "/home/petr/.local/share/virtualenvs/aklub_project-HrPEZ5ak/lib/python3.6/site-packages/django/utils/decorators.py", line 45, in _wrapper return bound_method(*args, **kwargs) File "/home/petr/.local/share/virtualenvs/aklub_project-HrPEZ5ak/lib/python3.6/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/petr/.local/share/virtualenvs/aklub_project-HrPEZ5ak/lib/python3.6/site-packages/django/contrib/admin/options.py", line 1672, in changelist_view cl = self.get_changelist_instance(request) File "/home/petr/.local/share/virtualenvs/aklub_project-HrPEZ5ak/lib/python3.6/site-packages/django/contrib/admin/options.py", line 744, in get_changelist_instance sortable_by, File "/home/petr/.local/share/virtualenvs/aklub_project-HrPEZ5ak/lib/python3.6/site-packages/django/contrib/admin/views/main.py", line 81, in __init__ self.queryset = self.get_queryset(request) File "/home/petr/.local/share/virtualenvs/aklub_project-HrPEZ5ak/lib/python3.6/site-packages/django/contrib/admin/views/main.py", line 436, in get_queryset qs = qs.order_by(*ordering) File "/home/petr/.local/share/virtualenvs/aklub_project-HrPEZ5ak/lib/python3.6/site-packages/django/db/models/query.py", line 1074, in order_by obj.query.add_ordering(*field_names) File "/home/petr/.local/share/virtualenvs/aklub_project-HrPEZ5ak/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1804, in add_ordering if not hasattr(item, 'resolve_expression') and not ORDER_PATTERN.match(item): TypeError: expected string or bytes-like object Is this issue in Django or am I doing something wrong? -
Django application deployment error on Heroku
I have developed my application on Heroku then I get application error could not save please give me solution this is my first django project https://wordbloger.herokuapp.com/ -
How to customize the restframework-jwt in django framework
Actually i am using json web tokens for authentication in django rest framework with reactjs. I done with login/signup and verify tokens, refresh tokens but can't able to reset password or change the password. anyone suggest me what is possible ways to move on. -
How to save images from HTML form in Django?
class Product(models.Model): product_name = models.CharField(max_length=250) product_rate = models.IntegerField() product_date = models.DateField(auto_now_add=True) product_image = models.ImageField(upload_to='products/') product_rules = models.TextField() product_catagory = models.ForeignKey(Catagory,on_delete=models.CASCADE,null=True,blank=True) def __str__(self): return " Name: {} | Date: {}".format(self.product_name,self.product_date) [this is my product model] using this model I can save data into my database. and I can also retrieve data and then I can show that into a browser. But when I am trying to save the data from HTML form everything goes to my database but I can't see the image on my media folder. when I save an image from the admin panel I can see the image in the media folder but not from HTML form. <input type="file" name="product_image" id="product_image"> This is my Views function for saving this data into database def addproducts(request): if request.method == "POST": product_name= request.POST.get('product_name') product_rate= request.POST.get('product_rate') product_rules= request.POST.get('product_rules') product_image = request.POST.get('image') Product.objects.create(product_name = product_name, product_rate =product_rate, product_rules =product_rules, product_image =product_image) return redirect('products') else: print("error") return render(request,'products/addproducts.html') It works properly except that image. But I can still see the image name from the ADMIN PANEL. What i did wrong? :/ -
Problem in Pandas When read column for filter from model record
Dears I tried t check solution for getting column name in pandas when read column name from model record, whet is a solution for my issue My Code : Gather Model Query_set = Alarm_rule.objects.filter(status=1) con = cx_Oracle.connect('my pass') cur = con.cursor() for indict in Query_set: try: cur.prepare(indict.Datasource_name.Query) result = cur.execute(indict.Datasource_name.Query) items = [dict(zip([key[0] for key in cur.description], row)) for row in result] df = pd.DataFrame.from_dict(items, orient='columns', dtype=None) df['ALARMNAME']=indict.Alarm_name df['moType']=indict.Motype_name df['domain']=indict.Motype_name.Domain KPI=indict.Indicator print(KPI) print (df[KPI]) the output shown I can get REQUEST but when I get column name in data frame from a variable , I get error REQEUST Traceback (most recent call last): File "C:\Users\m84052952\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\indexes\base.py", line 2897, in get_loc return self._engine.get_loc(key) File "pandas_libs\index.pyx", line 107, in pandas._libs.index.IndexEngine.get_loc File "pandas_libs\index.pyx", line 131, in pandas._libs.index.IndexEngine.get_loc File "pandas_libs\hashtable_class_helper.pxi", line 1607, in pandas._libs.hashtable.PyObjectHashTable.get_item File "pandas_libs\hashtable_class_helper.pxi", line 1614, in pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: 'REQEUST' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:/python/Dashgrapher3/Dashgrapher1/Dashmain/Alarmdetector.py", line 30, in print (df[KPI]) File "C:\Users\m84052952\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\frame.py", line 2995, in getitem indexer = self.columns.get_loc(key) File "C:\Users\m84052952\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas\core\indexes\base.py", line 2899, in get_loc return self._engine.get_loc(self._maybe_cast_indexer(key)) File "pandas_libs\index.pyx", line 107, in pandas._libs.index.IndexEngine.get_loc File "pandas_libs\index.pyx", line 131, in pandas._libs.index.IndexEngine.get_loc File "pandas_libs\hashtable_class_helper.pxi", line 1607, in pandas._libs.hashtable.PyObjectHashTable.get_item File "pandas_libs\hashtable_class_helper.pxi", line 1614, in pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: … -
Convert a list of dicts to DataFrame and back to exactly same dict?
In my Django view, I want to load a list of dictionaries into a Pandas dataframe, manipulate it, dump to dict again and return such manipulated data as a part of this view's JSON response: def test(request): pre_pandas = [{'type': 'indoor', 'speed': 1, 'heart_rate': None}, {'type': 'outdoor', 'speed': 2, 'heart_rate': 124.0}, {'type': 'commute', 'speed': 3, 'heart_rate': 666.0}, {'type': 'indoor', 'speed': 4, 'heart_rate': 46.0}] df = pd.DataFrame(pre_pandas) # some data manipulation here... post_pandas = df.to_dict(orient='records') response = { 'pre_pandas': pre_pandas, 'post_pandas': post_pandas, } return JsonResponse(response) The problem with my approach is that Pandas' to_dict() method replaces Python's None with nan, so that the response has NaN in it: {"pre_pandas": [{"type": "indoor", "speed": 1, "heart_rate": null}...], "post_pandas": [{"heart_rate": NaN, "speed": 1,...}] and JavaScript cannot tackle NaN. Is there a way to dump a dataframe to a dict so that the output is exactly the same as the dict it was build from? I could possibly adjust the data manually with a list replace() method, but it feels awkward and also I would need to cover for all of the other - if any - conversions Pandas' to_dict() method might do. I also cannot dump post_pandas to JSON, as I am already doing … -
Calculated field is not updated when fields that it is calculated from are updated using PATCH in django rest framework
I have a model like this: class MyModel(models.Model): available_from = models.DateTimeField() available_to = models.DateTimeField() objects = MyModelManager() MyModelManager adds a calculated field is_active based on available_from and available_to like so: class SprintTypeManager(models.Manager): def get_queryset(self) -> QuerySet: return ( super() .get_queryset() .annotate( is_active=expressions.Case( expressions.When( Q(available_from__lte=Now()) & Q(available_to__gte=Now()), then=expressions.Value(True), ), default=expressions.Value(False), output_field=fields.BooleanField(), ) ) ) This works well, I get the three fields on the API, I can order by them and I can filter by them. However, if I update available_from or available_to such that is_active should change using PATCH, that change isn't reflected in the returned body, only if I reload the object using GET. As a workaround, I could re-fetch the object in the serialiser class' to_representation() method, but I was wondering if there is a better way? -
Django template filters - how to insert variable in the middle of user input string
I had a code that looks like this: {% with line1="Some text"|add:"<b>"|add:variable|add:"</b> more text" %} {% include 'subtemplate.html' %} {% endwith %} and I would pass it to html template like this: <div><h4>{{ line1|safe }}</h4></div> and it worked just fine. However, now user wants to be able to modify line1. So as a solution I would like to update line1 from a csv file as var_1 = 'Some text <b>|add:variable|add:</b> more text' {% with line1=var_1 %} {% include 'subtemplate.html' %} {% endwith %} That results with following text on my webpage: 'Some text |add:variable|add: more text' How can I insert variable in the middle of user provided input string using django tags and filters? -
python manage.py runserver not respondning
python manage.py runserver is not working it just happened after I update my window. When I run the command python manage.py runserver it just simply return the command prompt next line without do anything -
Django - exclude from queryset if every related model meets a condition
Given two models: class Pizza(models.Model): ... class Topping(models.Model): on_pizza = models.ForeignKey(Pizza, on_delete=models.CASCADE, related_name='toppings') name = models.CharField(max_length=50) spicy = models.BooleanField(default=False) How can I exclude all Pizzas where "spicy" is set to "False" for every topping? So, I'd like to have a queryset of Pizzas where every Pizza has at least one spicy topping on it. Thanks! -
Dynamic table name database model in Django view function
I'm working with Sql Server, Django 2.1 and Python 3.6. I have several tables in SQL Server with the same columns. Each one differs from the other in the "YYMM" suffix name (two year digits, two month digits). The user can select the suffix manually, recovering the data register from the associated table. The view function sets the new database table on each request. The Django model: class AudiRequest(models.Model): id = IntegerField(primary_key=True) content = CharField() class Meta: db_table = '' def get_absolute_url(self): return reverse('audirequest-detail', args=[str(self.id)]) def __str__(self): return '%s' % (self.id) def AudiRequest_detail(request, pk): def get_audi_suffix(): # It simulates the user input, from August to November 2019 r = str(random.randint(1908, 1911)) return r AudiRequest._meta.db_table = 'AUDI' + get_audi_suffix() peticion = AudiRequest.objects.using('test').get(pk=pk) The first time it works perfectly, but if (the user) changes the suffix, Sql Server throws the exception: the multi-part identifier ... could not be bound. Supposing the first time the user chose 1910 and the second time 1911, the debugged query is SELECT AUDI1910.id, AUDI1910.content FROM AUDI1911 WHERE id = %s%. The table name is updated but not the fields we want to manage. How can I update this? -
Haystack Django Search multiple fields at once
Using elasticsearch (2.x), django-haystack(2.8.0), drf-haystack (1.8.6) Im building a search. Everything is working fine, except I can't search for multiple fields at the same time. Right now, I can only search for a specific field like (url) /search/?title=test and /search/?text=test. Each url responds with the right results but just for the specified field. The desired result is /search/?q=test returning both matches for the title and the text to contain the search query "test". Below I added the searchindex for the searched model. class ModelIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) title = indexes.CharField(model_attr='title', boost=2.5) slug = indexes.CharField(model_attr='slug') site_id = indexes.IntegerField() def get_model(self): return Model def prepare_text(self, obj): return obj.text def prepare_site_id(self, obj): return obj.site.id def index_queryset(self, using=None): # Used when the entire index for model is updated. return self.get_model().objects.all().filter(date__lte=datetime.datetime.now()) -
Average Date from Django DateField excluding year
I have a website where I am currently trying to display start and end dates of semesters but the issue I am running into is that I need to exclude the year part of the DateField. Since from one year to another, the dates can change, I'm only interested on the average of the Day and Month part. All the answers I have seen online compute a difference and take into account the Year. When I use {% variable.StartDate %} I see 21 August 2018 which is good in a way but since I want to exclude the year, I cannot compute the average. In my views.py, I get the dates with variable = ex.filter(Semester=1).order_by('EndDate').first(). Ideally, I would like something that would look like this in pseudo-code: semester1 = ex.filter(Semester=1) semester1_without_year = semester1.removeYear() semester1_avg = semester1_without_year.average() With a test set of data such as: 21st August, 22nd August, 3rd September, the end result would be 26th August -
render matplotlib/seaborn plots on django template
i am unable to render matplotlib plots on django template like sales_dashboard.html ? /* views.py file */ def display(request): # Generated plot using matplotlib or seaborn ax1 = sns.lineplot(x='DATE', y="Total Amount", hue="Category", data=df) # store image in string buffer buffer = BytesIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") #return HttpResponse(buffer.getvalue(), content_type="image/png") response = base64.b64encode(buffer.getvalue()) return render(request, 'sales_dashboard.html', {'plot': response}) # sales_dashboard.html - file {% extends 'base.html'%} {% block content %} <img src='{{ plot }}'/> {% endblock %} Although it is getting display on return HttpResponse but not on render(request,'sales_dashboard.html', {'plot': response}) -However in output only Empty string is displaying in console like " iVBORw0KGgoAAAANSUhEUgAAC7gAAAV4CAYAAAAwwpCQAAAABH......." Please go through above code and sample output image -
django deserialization error while generating fixtures
I have generated test data from a tool called Mockaroo. I have used csv2json.py script to convert the csv downloaded from Mockaroo to json format. The json generated is being used as a fixture data to run unit tests. I am facing deserializaion error for some of the fields since the fields are expecting some value to be present but I am leaving them blank. Any help would be appreciable -
Refactoring code for many to many field in django
I need some help with refactoring the code for category and subcategories where subcategories are many to many field. I need list of dictionaries with options for particular category, and label for only those subcategories which have options added for that category. I need output in this format [{'sub_cat1': [{'id': 1, 'name': 'option1'}, {'id': 2, 'name': 'option2'}, {'label_for_sub_cat1': 'label1'}], 'sub_cat2': [{'id': 1, 'name': 'option1'}, {'id': 2, 'name': 'option2'}, {'id': 3, 'name': 'option3'}, {'label_for_sub_cat2': 'label2'}], 'sub_cat4': [{'id': 1, 'name': 'option1'}, {'id': 2, 'name': 'option2'}, {'id': 3, 'name': 'option3'}, {'label': 'Label_for_sub_cat4'}]}] I achieved this by using this code : views.py def post(self, request): category = request.GET.get('category') if category: category_list = list() sub_cat_list_1 = list() sub_cat_list_2 = list() sub_cat_list_3 = list() sub_cat_list_4 = list() category_data_dict={} category_data = Categories.objects.get(id = category) for value in category_data.sub_cat1.all(): sub_cat_list_1.append({ 'id':value.id, 'name':value.field_name }) if sub_cat_list_1: sub_cat_list_1.append({'label':category_data.label_for_sub_cat1}) category_data_dict['sub_cat1'] = sub_cat_list_1 for value in category_data.sub_cat2.all(): sub_cat_list_2.append({ 'id':value.id, 'name':value.field_name }) if sub_cat_list_2: sub_cat_list_2.append({'label':category_data.label_for_sub_cat2}) category_data_dict['sub_cat2'] = sub_cat_list_2 for value in category_data.sub_cat3.all(): sub_cat_list_3.append({ 'id':value.id, 'name':value.field_name }) if sub_cat_list_3: sub_cat_list_3.append({'label':category_data.label_for_sub_cat3}) category_data_dict['sub_cat3'] = sub_cat_list_3 for value in category_data.sub_cat4.all(): sub_cat_list_4.append({ 'id':value.id, 'name':value.field_name }) if sub_cat_list_4: sub_cat_list_4.append({'label':category_data.label_for_skin_type}) category_data_dict['sub_cat4'] = sub_cat_list_4 category_list.append(category_data_dict.copy()) print(category_list) This is models.py class SubCat1(models.Model): field_name = models.CharField(_('field name'),max_length=100) created_on = models.DateTimeField(_('created on'),auto_now_add = True) … -
python can't load on VS Code
I develop in Djangon / Python recently and use until now Sublime Text. I would like to go to a more complete idea (console, debug, etc ...) so I installed VS Code but when I open a project Django / Python I have the error below when I wanted to install the python extension but I had the error below: The environment variable 'Path' seems to have some paths containing the '"' character. The existence of such a character is known to have caused the Python extension to not load. If the extension fails to load please modify your paths to remove this '"' character. when I look at the PATH environment variable I do not see quotes but 2 lines: %USERPROFILE%\AppData\Local\Microsoft\WindowsApps;C:\Program Files\PostgreSQL\11\bin;C:\Program Files\PostgreSQL\11\lib;C:\Program Files\Sublime Text 3;C:\Users\jl3.PRT-063\AppData\Local\Programs\Python\Python37-32\Scripts; C:\Users\jl3.PRT-063\AppData\Local\Programs\Microsoft VS Code\bin I decided to followed the tutorial VS Code Python and actually when I run the program "Hello world!" I have the error message below: [Running] python -u "c:\Users\jl3.PRT-063\hello\hello.py" 'python' n'est pas reconnu en tant que commande interne ou externe, un programme ex�cutable ou un fichier de commandes. When I run my django project with windows console, I use py instead of python... I don't know why and if it is … -
Is there a way I can edit my python ai chatbot to work with facebook messenger or discord or telegram to work on my django website
I am building a website and it needs a chatbot. I have created a text based AI in python but need to add it to django and haven't worked out how. Here is the link to the github repository: https://github.com/abilkus/chatbot