Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django or Flask?
I am trying to build a webpage app that allows easy access to a tool that I built in python. The tool currently takes in csv files and then processes them and outputs a data frame with all necessary information. I guess I ultimately want a web app that allows a user to select csv files from their desktop and then outputs the data frame on the same page. What is the best software to do this? -
json loop from model in Django
How would I be able to create a loop on items, to further build up more items values. this is how my json looks, just not sure on the on the loop part to add extra items to the json_data so 1 or 20 items could be sent json_data = { 'data': { 'type': 'Delivery', 'customer_feedback': None, 'warehouse_address': None, 'items': [ { 'id': '5b22055510c92b1a046ece21', 'sku': '12387654', 'quantity': 8, }, { 'id': '5b22055510c92b1a046ece06', 'sku': '12387654', 'quantity': 5, }, ], }, response = requests.post('https://api.url', headers=headers, json=json_data) -
Sending a list value via ajax to view in Django
I'm trying to send a list from template to view Django via ajax. After I send that, I get same list as a string format! index.html <script> ... var provinces_list = [] var obj = document.getElementById('objectSelected'); for (var i=0; i<obj.length; i++) { provinces_list.push(obj.options[i].value) } var jsonText = JSON.stringify(provinces_list); $.ajax({ method: "GET", data: { 'P_list': jsonText }, url: '{% url '...' %}', dataType: 'json', success: function (context) { ... } }) </script> view.py provincesList = request.GET.get('P_list') when I debug, I get the list as str format: provincesList={str}'["X","Y","Z"]' I want to get value as a list. how can do that? thanks in advance -
Ensuring one task of a kind is being executed at a time. (Multiple tasks of different kinds can be executed concurrentlly) celery python
Let's say I have created two shared tasks: from celery import shared_task @shared_task def taskA(): #do something pass @shared_task def taskB(): #do something else pass I am using celery to perform certain tasks that will be invoked by the users of my Django project. I have no issue with taskA and taskB being executed at the same time. But, if taskA is already being executed, and another user tries to invoke taskA again, I want to show them an error message. Is there a way to do that? -
A weird behaviour of get_media_prefix of Django
I am monitoring a weird behaviour in the working of my django application. Sometimes the get_media_prefix returns a mix between static and get_media_prefix. I ask here because I have not found any solution in the searchers and If anyone could have any idea because server and web application do not shown any error, It just returns the incorrect path since is a mix between two paths. The django template is: {% load static %} <!DOCTYPE html> ... <script src="{% static "js/bootstrap.bundle.min.js" %}"></script> </head> <body> ... <img src="{% get_media_prefix %}{{ website.avatar }}" width="60" height="60" class="img-fluid rounded-circle" alt="Blog avatar"></img> ... View: def index(request): results = cache.get(1) if not results: # REDACTED code cache.set(1, foobar, 86400) return render(request,'index.html',{"Foobar" : foobar}) else: return render(request,'index.html',{"Foobar" : foobar}) Apache2 server: Alias /static/ /home/xxx/xxx.xxx/yyy/static/ Alias /media/ /home/xxx/xxx.xxx/yyy/media/ ... <Directory /home/xxx/xxx.xxx/yyy/static> <LimitExcept POST GET> Require all granted </LimitExcept> </Directory> <Directory /home/xxx/xxx.xxx/yyy/media> <LimitExcept POST GET> Require all granted </LimitExcept> </Directory> The weird situation always begins randomly and always looks like fix with a restart of apache2. for i in {1..20};do curl -s https://xxx.yyyy/ |grep avatar ; done <img src="/media/avatar/avatar2.webp" width="60" height="60" class="img-fluid rounded-circle" alt="Blog avatar"></img> <img src="/media/avatar/avatar2.webp" width="60" height="60" class="img-fluid rounded-circle" alt="Blog avatar"></img> <img src="/media/avatar/avatar2.webp" width="60" height="60" class="img-fluid rounded-circle" … -
Why does website not look like a module path?
I am going through a Django tutorial, and after creating my app directory, linking the urls.py files, and adjusting the views.py file, I am getting the error ImportError: website doesn't look like a module path. here is the full error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Conda\envs\DjangoTutorial\lib\site-packages\django\utils\module_loading.py", line 25, in import_string module_path, class_name = dotted_path.rsplit(".", 1) ValueError: not enough values to unpack (expected 2, got 1) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Conda\envs\DjangoTutorial\lib\site-packages\django\core\servers\basehttp.py", line 47, in get_internal_wsgi_application return import_string(app_path) File "C:\Conda\envs\DjangoTutorial\lib\site-packages\django\utils\module_loading.py", line 30, in import_string return cached_import(module_path, class_name) File "C:\Conda\envs\DjangoTutorial\lib\site-packages\django\utils\module_loading.py", line 15, in cached_import module = import_module(module_path) File "C:\Conda\envs\DjangoTutorial\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\Dustin Oliver\Desktop\Coding Notes\Django\DjangoTutorial\dentist\dentist\wsgi.py", line 16, in <module> application = get_wsgi_application() File "C:\Conda\envs\DjangoTutorial\lib\site-packages\django\core\wsgi.py", line 13, in get_wsgi_application return WSGIHandler() File "C:\Conda\envs\DjangoTutorial\lib\site-packages\django\core\handlers\wsgi.py", line 125, in __init__ self.load_middleware() File "C:\Conda\envs\DjangoTutorial\lib\site-packages\django\core\handlers\base.py", line 40, … -
Django CSRF Protection Issue
I've just started building an API with Django for the first time and I've run into an issue while trying to test an endpoint with Postman. When I send a POST request to the endpoint http://localhost:8000/arithmetic/ containing the following JSON: { "expression": "1 + 2 × 3" } <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"> <title>403 Forbidden</title> <style type="text/css"> html * { padding: 0; margin: 0; } body * { padding: 10px 20px; } body * * { padding: 0; } body { font: small sans-serif; background: #eee; color: #000; } body>div { border-bottom: 1px solid #ddd; } h1 { font-weight: normal; margin-bottom: .4em; } h1 span { font-size: 60%; color: #666; font-weight: normal; } #info { background: #f6f6f6; } #info ul { margin: 0.5em 4em; } #info p, #summary p { padding-top: 10px; } #summary { background: #ffc; } #explanation { background: #eee; border-bottom: 0px none; } </style> </head> <body> <div id="summary"> <h1>Forbidden <span>(403)</span></h1> <p>CSRF verification failed. Request aborted.</p> </div> <div id="info"> <h2>Help</h2> <p>Reason given for failure:</p> <pre> CSRF token from the &#x27;X-Csrftoken&#x27; HTTP header has incorrect length. </pre> <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or … -
"Looks like your app is listening on 127.0.0.1. You may need to listen on 0.0.0.0 instead." Django project deployment to Railway app error
I want to deploy my Django project to the Railway app(deployment application). I have followed the instructions from this article but still I am getting this error "Looks like your app is listening on '127.0.0.1'.you may need to listen on '0.0.0.0' instead. " I don't know how to get rid of this error. Any help is accepted. -
Could not parse the remainder: '[i]' from 'l[i]' - Django
I am trying to use 'for i in r' as a way to simulate 'for i in range()' as shown in https://stackoverflow.com/a/1107777/14671034 . The r in my case is just a list of numbers from 0 to 10. 'l' is list of objects, here is .html file : {% for i in r %} {% for j in l[i] %} <tr> <td>{{j.a}}</td> <td>{{j.b}}</td> </tr> {% endfor %} {% endfor %} here is the part of views.py: am = [i for i in range(len(list_of_objs))] context = {'l': list_of_objs, 'r': am} everything worked just fine when i was passing list of object instead of list of numbers -
Install PGAdmin4 on Ubuntu
I'm from Iran and i need to install PGAdmin4 for my Ubuntu. To be honest i spent 12 hours time to install this application but after this i realized that the packets coming from server are disable due to internet restrictions from government. is there a way for me to install it ? the issue is raised when i trying to run this command : sudo sh -c 'echo "deb [signed-by=/usr/share/keyrings/packages-pgadmin-org.gpg] https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/$(lsb_release -cs) pgadmin4 main" > /etc/apt/sources.list.d/pgadmin4.list && apt update' the command line is waiting for receive a response but didn't get it. I installed Postgres but i can't install PGAdmin4. can anyone help me out ??? thanks a lot for your comments. I try to install PGAdmin4 but i couldn't do that. please help me... thanks -
save .xlsx file writen by pandas and export as a django model
I am going to have a web app that does some processing on user data and is going to give him/her back an excel file of processed data in Django. here is my app/views.py function: @login_required(login_url='/signin/') def processing(request): ... # read imported file (uploaded by user) and do the process. # finally have 3 uf, vf, wf array. ... # save the file in "excel_file = models.FileField" from pandas import DataFrame, ExcelWriter data = { 'uf': uf, 'vf': vf, 'wf': wf, } excel_data = DataFrame(excel_data) despiked = Despiking( #other models excel_file=excel_data.to_excel(???), ) despiked.save() return render(request, 'filteration/despiking.html', context=context) how can I save the excel_data into its model (excel_file) and create its media into Media directory? I already have read django pandas dataframe download as excel file question, but wasn't able to fix the problem with HttpResponse. any help would be greatly appreciated -
django mysql connection don't respect databases settings in settings.py
This is my database connection string in settings.py. DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "HOST": "127.0.0.1", "PORT": os.getenv("DB_PORT", '3306'), "NAME": os.getenv("DB_DATABASE", 'sm'), "USER": os.getenv("DB_USER", 'root'), "PASSWORD": os.getenv("DB_PASSWORD", ''), } } As above the host specified 127.0.0.1 but when I run python manage.py runserver database connection error with the wrong hostname. django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'172.18.0.1' (using password: NO)") As you can see I wrote hostname 127.0.0.1 but in the project, it is connecting 172.18.0.1 I really appreciate, it if someone gives me an answer to this issue. Thank you. -
How to add icons or emoji in django admin buttons
So I have some buttons in django admin and I need to add something like that: ⬅️➡️↩️↪️ to my admin buttons, but I have 0 idea how to do this and I feel like I am the first ever person to ask that question on the internet, google didnt help :)) Can you guys suggest something? Button for rotating photo in admin Tried to paste this ⬅️➡️↩️↪️ in the name of buttons, but it doesnt work like that xD -
How to set html attributes to Django form created using model
I have model class Listings(models.Model): user_id = models.ForeignKey( User, on_delete=models.CASCADE ) title = models.CharField(max_length=180) desc = models.CharField(max_length=900) price = models.IntegerField(validators=[MinValueValidator(1)]) img = models.ImageField(upload_to='uploads') timestamp = models.DateTimeField(auto_now_add=True) And form class class ListingForm(ModelForm): class Meta: model = Listings fields = ('title', 'category', 'price', 'desc', 'img') labels = { 'desc': 'Description', 'img': 'Upload photo', 'price': 'Starting price' } I want to add HTML attributes like min="0" or remove required from my img = models.ImageField(upload_to='uploads') for example. How can I implement this? I found in stack overflow method with widgets = {'price': IntegerField(attrs='min': 0}) and I also tried ...forms.IntegerField... but I had TypeError: __init__() got an unexpected keyword argument 'attrs' And I also found solution with def __init__(self, *args, **kwargs): super(Listings, self).__init__(*args, **kwargs) self.fields['price'].widget.attrs.update({ 'min': 1 }) (I added it to my form class) But also did not work super(Listings, self).__init__(*args, **kwargs) TypeError: super(type, obj): obj must be an instance or subtype of type [05/Jan/2023 19:22:01] "GET /create_listing HTTP/1.1" 500 60691 -
Django compare two users of a model and if one is the current user return the other user
I have this really simple friendship model that just consists of two users. After all if user1 is friends with user2 then user2 is friends with user1 automatically. I would like to filter all the results by the current user and if a row contains the current user I would like to return the other user. So basically I want to return all records if the current user is either userone or usertwo and if the current user is usertwo swap the values so the current user is userone. Currently it works but only one way using the following model, serializer and view Model: class Friendship(models.Model): userone = models.ForeignKey( User, on_delete=models.CASCADE, related_name="friendone" ) usertwo = models.ForeignKey( User, on_delete=models.CASCADE, related_name="friendtwo" ) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: unique_together = ["userone", "usertwo"] def __str__(self): return "{} is friends with {}".format(self.userone, self.usertwo) def save(self, *args, **kwargs): if self.userone == self.usertwo: return "Same person friendship should happen mentally" else: super().save(*args, **kwargs) serializer: class FriendSerializer(serializers.ModelSerializer): profile2 = serializers.SerializerMethodField() class Meta: model = Friendship fields = [ "usertwo", "profile2" ] def get_profile2(self, obj): profile2_obj = Profile.objects.get(id=obj.usertwo.profile.id) profile2 = ProfileSerializer(profile2_obj) return profile2.data and view: class FriendList(generics.ListAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = … -
Why is django.conf.urls.static.static returning an empty list?
I'm trying to allow serving files from my media directory, but the media url isn't getting included... here's my code: from django.conf.urls.static import static urlpatterns = [ ... ] if settings.LOCALHOST_DEVELOPMENT: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) From a Django shell session: >>> from django.conf import settings >>> settings.LOCALHOST_DEVELOPMENT True >>> settings.MEDIA_URL '/media/' >>> settings.MEDIA_ROOT '/Users/[my username]/code/survey_server/media' >>> from survey_server import urls That last call return a list of urls without media url... >>> from django.conf.urls.static import static >>> static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) [] ... and it looks like the media url wasn't included because that static call is returning an empty list. Why is this empty? -
Combining serializers and sorting with filtering
I have a problem with the API JSON (serializers). I need to display only the last added price for a store and sort by lowest price for an article. There is no possibility to change the relationship in the database. DB schema looks like. DB Schema models.py from django.db import models class Shop(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.data() def data(self): return "{}".format(self.name) class Article(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.data() def data(self): return "{}".format(self.name) class Price(models.Model): article = models.ForeignKey(Article, on_delete=models.PROTECT, related_name='prices') shop = models.ForeignKey(Shop, on_delete=models.PROTECT, related_name='shops') name = models.CharField(max_length=100) date = models.DateField(null=True, blank=True) def __str__(self): return self.data() def data(self): return "{} {}".format(self.name, self.date) serializers.py from .models import Article, Price, Shop from rest_framework import serializers class PriceSerializer(serializers.ModelSerializer): class Meta: model = Price fields = ['name', 'date'] class ShopSerializer(serializers.ModelSerializer): prices = PriceSerializer(many=True) class Meta: model = Shop fields = ['name', 'prices'] def to_representation(self, instance): bdata = super().to_representation(instance) bdata ["prices"] = sorted(bdata["prices"], key=lambda x: x["date"], reverse=False) return bdata class ArticleSerializer(serializers.ModelSerializer): prices = PriceSerializer(many=True) class Meta: model = Article fields = ['name', 'prices'] views.py from .models import Shop, Article, Price from rest_framework import viewsets, permissions, filters from apitest.serializers import ArticleSerializer, PriceSerializer, ShopSerializer #from rest_framework.response import Response #from django.db.models import Prefetch class … -
Saving to database an object after celery task is finished successful
I'm a newbie and need some help with saving some datas after a successful celery task, i have these models and serializers: texts/models.py class MyTexts(models.Model): TxTitle=models.CharField(max_length=300) TxText=models.TextField() TxAnnotatedText=models.TextField(blank=True) TxAudioURI=models.CharField(max_length=200, blank=True) TxSourceURI=models.CharField(max_length=1000,blank=True) TxTLang=models.ForeignKey(Language, related_name="TextLang",on_delete=models.CASCADE) TxtUser=models.ForeignKey(Learner, related_name="TextUser",on_delete=models.CASCADE) TxtTag=models.ForeignKey(to="tags.MyTags",on_delete=models.CASCADE,related_name="TextTags",blank=True,null=True) TxtArchived=models.BooleanField(default=False) TxtDifficulty=models.IntegerField() def __str__(self) -> str: return self.TxTitle Learner/models.py class Learner(AbstractUser): SelLanguage=models.OneToOneField(Language,on_delete=models.CASCADE,null=True,related_name="SelLanguage") is_teacher=models.BooleanField(default=False) can_post=models.BooleanField(default=False) level=models.IntegerField(default=0) def __str__(self) -> str: return self.username Learner/serializer.py from django.contrib.auth import authenticate, get_user_model from djoser.conf import settings from djoser.serializers import TokenCreateSerializer User = get_user_model() class CustomTokenCreateSerializer(TokenCreateSerializer): def validate(self, attrs): password = attrs.get("password") params = {settings.LOGIN_FIELD: attrs.get(settings.LOGIN_FIELD)} self.user = authenticate( request=self.context.get("request"), **params, password=password ) if not self.user: self.user = User.objects.filter(**params).first() if self.user and not self.user.check_password(password): self.fail("invalid_credentials") # We changed only below line if self.user: # and self.user.is_active: return attrs self.fail("invalid_credentials") language/models.py class Language(models.Model): LgName=models.CharField(max_length=40) LgDict1URI=models.CharField(max_length=200) LgDict2URI=models.CharField(max_length=200) LgGoogleTranslateURI=models.CharField(max_length=200) LgExportTemplate=models.CharField(max_length=1000) LgTextSize=models.IntegerField() LgRemoveSpaces=models.BooleanField() LgRightToLeft=models.BooleanField() LgSkills=models.TextField() def __str__(self) -> str: return self.LgName language/serializers.py class LanguageSerializer(serializers.ModelSerializer): class Meta: model=Language fields='__all__' tags/models.py class MyTags(models.Model): T2Text=models.CharField(max_length=30,blank=True) T2Comment=models.CharField(max_length=200,blank=True) TagsUser=models.ForeignKey(Learner, on_delete=models.CASCADE,related_name="MyTagsUser",blank=True) TagsText=models.ForeignKey(to="texts.MyTexts",on_delete=models.CASCADE,related_name="MyTagsText",blank=True) TagsLang=models.ForeignKey(Language,on_delete=models.CASCADE,related_name="MyagsLang",blank=True) TagsArchived=models.BooleanField(blank=True) tags/serializers.py class MyTags(models.Model): T2Text=models.CharField(max_length=30,blank=True) T2Comment=models.CharField(max_length=200,blank=True) TagsUser=models.ForeignKey(Learner, on_delete=models.CASCADE,related_name="MyTagsUser",blank=True) TagsText=models.ForeignKey(to="texts.MyTexts",on_delete=models.CASCADE,related_name="MyTagsText",blank=True) TagsLang=models.ForeignKey(Language,on_delete=models.CASCADE,related_name="MyagsLang",blank=True) TagsArchived=models.BooleanField(blank=True) and these two endpoints in texts/view.py: @api_view(['POST']) def match_patterns_request_view(request): username = request.data.get("username" ) document = request.data.get("document") language = request.data.get("language") user=Learner.objects.get(username=username) priority=user.level task = match_patterns.apply_async(args=(username,document,language),priority=priority) return Response(status=status.HTTP_200_OK, data={"id":task.id}) @api_view(['GET']) def match_patterns_result_view(request, task_id): task_result = AsyncResult(task_id) # Check … -
how to pass `request` info to Django form Widget
I am trying to pass a filter queryset for a Django form widget. Normally, I would do something like # views.py class MyView(SuccessMessageMixin, CreateView): model = MyModel form_class = MyCreateForm template_name = 'create.html' success_message = "You new object has been created." success_url = reverse_lazy('mymodel-index') # forms.py class MyCreateForm(forms.ModelForm): class Meta: model = MyModel fields = [ 'title', 'car', # etc ] widgets = { 'car': forms.widgets.Select( required=True, queryset=Car.objects.all(), # I need to filter this to the current user ), } However, I need to filter the queryset (in the car select Widget) to by the currently logged in user. I could try passing the user to __init__ from the View, but I don't know how to access that from the Meta subclass. Any pointers in the right direction would be appreciated. -
Postgres db index not being used on Heroku
I'm trying to debug a slow query for a model that looks like: class Employee(TimeStampMixin): title = models.TextField(blank=True,db_index=True) seniority = models.CharField(blank=True,max_length=128,db_index=True) The query is: Employee.objects.exclude(seniority='').filter(title__icontains=title).order_by('seniority').values_list('seniority') When I run an explain locally I get "Gather Merge (cost=1000.58..196218.23 rows=7 width=1)\n Workers Planned: 2\n -> Parallel Index Only Scan using companies_e_seniori_12ac68_idx on companies_employee (cost=0.56..195217.40 rows=3 width=1)\n Filter: (((seniority)::text <> ''::text) AND (upper(title) ~~ '%INFORMATION SPECIALIST%'::text))" however when I run the same code on Heroku I get costs of 1000x, seemingly because the former is using an index while the second is not: "Gather Merge (cost=216982.26..216982.90 rows=6 width=1)\n Workers Planned: 2\n -> Sort (cost=215982.26..215982.26 rows=3 width=1)\n Sort Key: seniority\n -> Parallel Seq Scan on companies_employee (cost=0.00..215982.25 rows=3 width=1)\n Filter: (((seniority)::text <> ''::text) AND (upper(title) ~~ '%INFORMATION SPECIALIST%'::text))\nJIT:\n Functions: 4\n Options: Inlining false, Optimization false, Expressions true, Deforming true" I confirmed the model indexes are identical for my local database and on Heroku, this is what they are: indexname | indexdef ----------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------- companies_employee_pkey | CREATE UNIQUE INDEX companies_employee_pkey ON public.companies_employee USING btree (id) companies_employee_company_id_c24081a8 | CREATE INDEX companies_employee_company_id_c24081a8 ON public.companies_employee USING btree (company_id) companies_employee_person_id_936e5c6a | CREATE INDEX companies_employee_person_id_936e5c6a ON public.companies_employee USING btree (person_id) companies_employee_role_8772f722 | CREATE INDEX companies_employee_role_8772f722 ON public.companies_employee USING btree (role) companies_employee_role_8772f722_like | … -
Cannot assign "1": "Account.country" must be a "Country" instance
class MyAccountManager(BaseUserManager): ... class Country(models.Model): country_name = models.CharField(max_length=50) class Account(AbstractBaseUser): image = models.ImageField(upload_to='photos/profils/', default='media/photos/profils/constantly_img.jpg') first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(max_length=50, unique=True) GENDER_CHOICES = [ ('MALE', 'Мужской'), ('FEMALE', 'Женской') ] gender = models.CharField(max_length=7, choices=GENDER_CHOICES) birthday = models.DateField() phone_num = models.CharField(max_length=50) password = models.CharField(max_length=50) country = models.ForeignKey(Country, on_delete=models.PROTECT) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'phone_num', 'country'] When i am creating the superuser in terminal and if i want to populate the Account.country field by binding it to the Country model. I got an error. What am I doing wrong? -
Django Windows ./manage.py
I have saw a lot of posts regarding about how to do ./manage.py for windows and linux but i find the instructions unclear as a beginner. I have tried using "chmod +x manage.py" in my django project directory ("C:\Users\user\Django\Project") in windows command prompt and it does not work as it is not recognised by an internal or external command. So how would you do this in Windows? -
ValueError: Cannot assign "'1'": "Post.user" must be a "User" instance
I am doing a group project for a bootcamp and we just started Django for the back-end. We also are using React for front-end. Our project is basically a knockoff reddit. We have a User model: `from django.db import models class User(models.Model): firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) email = models.CharField(max_length=100, unique=True) username = models.CharField(max_length=32, unique=True) password = models.CharField(max_length=255) def __str__(self): return '%s' % (self.username)` and a Post model: `from django.db import models from auth_api.models import User class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=255) formBody = models.TextField(null=True, blank=True) imageURL = models.CharField(max_length=200, null=True, blank=True) created = models.DateTimeField(auto_now_add=True)` Our Post Serializers(pretty unfamiliar with this): `from rest_framework import serializers from .models import Post class PostSerializer(serializers.ModelSerializer): user = serializers.CharField(required=True) class Meta: model = Post fields = ('id', 'user', 'title', 'formBody', 'imageURL', 'created',)` And our Post Views: `from django.shortcuts import render from rest_framework import generics from .serializers import PostSerializer from .models import Post from auth_api.models import User class PostList(generics.ListCreateAPIView): queryset = Post.objects.all().order_by('id') serializer_class = PostSerializer class PostDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Post.objects.all().order_by('id') serializer_class = PostSerializer` The idea was when a user created a post their info would be saved with the post so that way when we display the post we could say who … -
Django website runs but none of the frontend shows
I am running my Django website using Amazon Linux EC2 instance. Everything runs correctly but for some reason, the actual front end of the website is not displayed. It even shows the title of the website in the search bar but can't display the actual content for me to interact with the website. It is just a white screen. Any help would be greatly appreciated. When I load the website, the GET requests display in my CLI: "GET / HTTP/1.1" 200 847, "GET /static/js/main.b1d3e335.js/ HTTP/1.1" 302 0, etc. I'm not sure what to try next. I used the collectstatic command for Django so I am thinking there may be a problem with the static files. But it is weird that my actual title of the website displays in the search bar but everything else is simply a white screen. -
Is it possible to include a view directly from the html?
I would like to know if it's possible, with Django, to include a view in another view like: Declare a view: def ads(request): param = ["first_ads_title"] return render(request, "blog/ads.html", context={"param": param}) With the following html : <div>ads {{ param[0] }}</div> And be able to call it from another html view like: <body> <h1>hello article {{ article }}</h1> {% include "blog/ads" %} </body> To display first_ads_title in my body ?