Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - annotate on multiple fields and load relevant objects
Let's say I have the following models class Author(models.Model): name = models.CharField(max_length=25) ... class Publisher(models.Model): name = models.CharField(max_length=25) ... class Book(models.Model): author = models.ForeignKey(Author) publisher = models.ForeignKey(Publisher) ... For some reason, I want to query books and group results by the author and publisher, so: books = Book.objects.values('author', 'publisher').annotate('sth'=Avg('sth_else')) with the results looking like: <BookQuerySet [{'author': 2, 'publisher': 1, 'sth': 1.0}]> Is it possible to load the whole Author and Publisher objects and not just their related ids? -
local Docker container shows blank screen running with gunicorn
I am trying to run a Docker container locally, via the command: docker run --rm -d mellon:latest The gunicorn command which is executing is: gunicorn -b 0.0.0.0:8000 mellon.wsgi (more specifically in the Dockerfile): ... EXPOSE 8000 CMD python3 manage.py makemigrations && \ python3 manage.py migrate && \ gunicorn -b 0.0.0.0:8000 mellon.wsgi Everything in the terminal seems fine, this is the end of what I see: ... [2020-07-28 14:52:33 +0000] [10] [INFO] Starting gunicorn 20.0.4 [2020-07-28 14:52:33 +0000] [10] [INFO] Listening at: http://0.0.0.0:8000 (10) [2020-07-28 14:52:33 +0000] [10] [INFO] Using worker: sync [2020-07-28 14:52:33 +0000] [12] [INFO] Booting worker with pid: 12 So I then go to http://localhost:8000/ yet I just see a completely blank screen with the title and favicon of the project in the tab (see below). This isn't an issue with caching, as I have tried it in a few browsers and the favicon and title appear there too. And upon using 'inspect element' on the page, it shows the contents of the index.html file of my Vue.js project there (located in mellon/frontend/dist). It isn't a problem with my project as running the front-end server (npm run serve) and the back-end server (python3 manage.py runserver) as I usually … -
django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable
This project was working fine until I used environ to make SECRET_KEY and DEBUG as environment variable using environ. After I am getting this error:- The output is: (env) E:\ecommercedj>python manage.py runserver Traceback (most recent call last): File "E:\ecommercedj\env\lib\site-packages\environ\environ.py", line 273, in get_value value = self.ENVIRON[var] File "c:\users\matruchhaya\appdata\local\programs\python\python38-32\lib\os.py", line 675, in __getitem__ raise KeyError(key) from None KeyError: 'SECRET_KEY' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "E:\ecommercedj\env\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "E:\ecommercedj\env\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "E:\ecommercedj\env\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "E:\ecommercedj\env\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "E:\ecommercedj\env\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "E:\ecommercedj\env\lib\site-packages\django\core\management\commands\runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "E:\ecommercedj\env\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "E:\ecommercedj\env\lib\site-packages\django\conf\__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "E:\ecommercedj\env\lib\site-packages\django\conf\__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "c:\users\matruchhaya\appdata\local\programs\python\python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in … -
how to display count and sum on your website? postgresql, django
I am making a dashboard with django and postgresql, but I am having trouble with the sum and count select functions from sql. home.html <h5 class="card-title">{{total_monney}}</h5> views.py def home(request): d = Dashboard() total_monney = d.getTotalMonney() return render(request, 'home.html', {'total_monney': total_monney}) app.py class Dashboard: def getTotalMonney(self): sql = "SELECT SUM(product_price) FROM products" sqldata = () c = cursor('dashboard', sql, sqldata) result = c.connect() return result the result is that it displays this on the page, how do i only get the "33200"? [RealDictRow([('sum', 33200)])] Everthing works when i dont use the sum and count and just the select, so i dont know if i have todo something diffrent when i use these functions. I get the same result with count too -
Django pagination resets
I am building an application that lists certain records from a database. The database is quite large and I am building a pagination to show a specific number of rows. Currently I have set a default value for the paginate_by. Here is the class that I am using. class HomePageView(ListView): model = Syslog template_name = 'home.html' context_object_name = 'all_logs'; paginate_by = 10 def get_paginate_by(self, queryset): return self.request.GET.get("paginate_by", self.paginate_by) I have implemented and a feature that allows clients to change the pagination levels like so: <form action="" method="get"> <select name="paginate_by" onchange='this.form.submit()'> <option>1</option> <option>2</option> <option>3</option> <option>4</option> </select> </form> When the home page is loaded with the default value the number of pages show correctly. When a user submit another paginate_by value the number of pages change accordingly. The problem is that when the pagination parameter is changed and a user click on let's say 2nd page the paginate_by resets to the default. Regards, Jordan -
How can I convert the value of a DurationField to its number of microseconds in a QuerySet?
Suppose I have two models: Computer and DailyUsage. DailyUsage has a DurationField named usage_duration. On a QuerySet of Computers, I want to annotate the average daily usage in minutes. Each additional minute the computer has been used on average per day, the computer's "importance" increases. I have seen examples* of people using ExpressionWrapper to convert a DurationField to its BigIntegerField representation, but attempting this: average_in_duration_annotated = Computer.objects.annotate( avg=Avg("daily_usages__usage_duration", filter=Q(daily_usages__date__gte=one_month_ago)) ) average_in_minutes_annotated = average_annotated.annotate( avg_in_minutes=ExpressionWrapper(F("avg"), output_field=BigIntegerField()) / Value(10e6 * 60) ) ... results in: {TypeError}int() argument must be a string, a bytes-like object or a number, not 'datetime.timedelta' when the QuerySet is evaluated. Another example that fails the same way: Computer.objects.annotate( total_usage_minutes_microseconds=Sum("daily_usages__usage_duration", output_field=BigIntegerField()) ) How can I convert the value of a DurationField to its number of microseconds in a QuerySet? * Aggregate in django with duration field -
How to match time range if to_date can be Null in Django?
I have two date, let's say from_date and to_date, and I have column with prices for that range. It looks like this in my models: class PriceList(models.Model): from_date = models.DateField(verbose_name="Start date") to_date = models.DateField(verbose_name="End_date", null=True) product = models.ForeignKey(Models, on_delete=models.CASCADE) price = models.DecimalField(verbose_name="EUR/h", max_digits=10, decimal_places=5) I know how to get record for the correct product in a period if a to_date is available, but I am not sure how to fetch it if it is Null, that means from from_date to forever (until changed). And, obviously, would like to have query that will work in both scenarios - if ther is a to_date and if it Null. -
Display user image ({{ userprofile.image.url }}) on my base.html
I hope you're well? I'm beginner with Django. I'm using a profile for my users (witch belongs to "User" field. I'd like to display the image on my base.html (witch belongs to "Nutriscore" "templates" field). How I can do it? {{ userprofile.image.url }} only works on my update_profile.html page (witch belongs to the user templates field). MonProjetDjango Nutriscore -- templates -- urls.py User -- templates -- views.py -- models.py User > views.py @method_decorator(login_required(login_url='login/'),name="dispatch") class UserProfileUpdateView(UpdateView): model = UserProfile template_name = 'profile-update.html' form_class = UserProfileForm success_message = "Profile updated" def form_valid(self, form): form.instance.user = self.request.user form.save() return super(UserProfileUpdateView, self).form_valid(form) def get_success_url(self): return reverse('update_profile',kwargs={'slug':self.object.slug}) def get(self,request,*args,**kwargs): self.object = self.get_object() if self.object.user != request.user: return HttpResponseRedirect('/') return super(UserProfileUpdateView, self).get(request,*args,**kwargs) User > models.py class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) street = models.CharField(null=True,blank=True,max_length=300) number_street = models.CharField(null=True,blank=True,max_length=20) street_detail = models.CharField(null=True,blank=True,max_length=300) town = models.CharField(null=True,blank=True,max_length=60) zipcode = models.CharField(null=True,blank=True,max_length=20) country = models.CharField(null=True,blank=True,max_length=60) image = models.ImageField(null=True,blank=True,default='user/user-128.png', upload_to='user/') slug = models.SlugField(editable=False) def save(self, *args,**kwargs): self.slug = slugify(self.user.username) super(UserProfile, self).save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 200 or img.width > 200: new_size = (200, 200) img.thumbnail(new_size) img.save(self.image.path) def __str__(self): return self.user.username def create_user_profile(sender,instance,created,**kwargs): if created: UserProfile.objects.create(user=instance) post_save.connect(create_user_profile,sender=settings.AUTH_USER_MODEL) Nutriscore > urls.py path('profile/<slug:slug>/', UserProfileUpdateView.as_view(), name="update_profile"), -
How do I put extrenal link on blog title in Wagtail?
I made Blog-Index-Page on models.py, however I couldn't list it up in other pages, because Blog-Index-Page is a sheet of page so they cannot show on same page. and I want to put external links (URLs) on titles without my Blog-Detail-page. following is the BlogIndexPage on models.py☟ class BlogIndexPage(Page): template = "articles/blog_index.html" blog_title = models.CharField(max_length=100, blank=False, null=True) blog_url = models.URLField(max_length=200, default='DEFAULT VALUE') blog_thumbnail = models.ForeignKey("wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+") blog_caption = models.CharField(max_length=100, blank=True, null=True) content_panels = Page.content_panels +[ FieldPanel("blog_title"), FieldPanel("blog_url"), ImageChooserPanel("blog_thumbnail"), FieldPanel("blog_caption"), ] def get_context(self, request, *args, **kwargs): context = super().get_context(request, *args, **kwargs) context["posts"] = BlogIndexPage.objects.live().public() return context I want to apply this class as a listing page, not as detail page. Can I help me to make listing page and give me some idea. -
Fullcalendar cannot display event after event has been created (Django and Javascript)
currently I cannot display event after event has been created. In fact, I cannot display event at all from database. Previously, I made something like this and it worked. views.py def calendar(request): all_events = Events.objects.all() context = { "events":all_events, } return render(request,'fullcalendar/calendar.html',context) calendar.html events: [ {% for event in events %} { title: "{{ event.title}}", start: '{{ event.start|date:"Y-m-d" }}', end: '{{ event.end|date:"Y-m-d" }}', id: '{{ event.id }}', }, {% endfor %} ], But right now, I wanted to insert the part which is in the calendar.html to script.js and I tried to use EventSources but I failed to make events display on fullcalendar. Does anyone know how to convert the part which is in calendar.html to script.js? The reason why I decided to use script.js is because if I put everything in HTML, it will get really long. Currently, my EventSources of script.js looks like this. script.js eventSources:[{ url: '/fullcalendar/calendar', method: 'GET', success: function(){ alert("GOT IT!!"); }, failure: function(){ alert("PROBLEM!!!"); }, } ], it seems I have done nothing but trust me I have searched all over the place and tried so many things but I still fail to make the event display on the fullcalendar. I got the feeling … -
python script .sh is running or not check in portal
guys is it possible to check continuously if .sh (any script) file is running or not. with portal that monitor .sh services for example sample test backup.sh service running every 15 minute that take backup in cronjob. mkdir "/dev/my backup directory" mv /var/log/*2007* "/dev/my backup directory/" sed -i '/:[0-9][0-5]:/ {d}' "/dev/my backup directory/*" this is simple test script but is it possible that we can check throw portal that show if service is running or not that send alert if it is stop or started in web-application if it is possible in python or another language than where i can find useful information. -
Django: ValueError: Missing staticfiles manifest entry for 'jquery.twbsPaginationAlt.min.js'
Before marking as duplicate, note that I've checked all the similar questions that have been asked and it has not fixed my problem. I've deployed my Django App on Heroku in in one template where I reference a min.js file, it throws this error in question. My basic directory structure is this: myapp mysite dictionary static jquery.twbsPaginationAlt.min.js staticfiles settings.py: STATIC_URL = '/static/' # STATIC_ROOT = [os.path.join(BASE_DIR, 'staticfiles'), os.path.join(BASE_DIR, 'static/fonts')] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') if DEBUG: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'mysite/static'), os.path.join(BASE_DIR, 'static/')] import django_heroku # handles staticfiles, database url, and secret key, can be overwritten as needed django_heroku.settings(locals(), secret_key=False, logging=False) So originally if STATICFILES_DIRS had any value, I would get an error of FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_6f3eb879/mysite/static' when running collectstatic on heroku. However, if it is not set, than the fonts I have in my dev environment do not load in properly (I also have fonts inside the base level static folder). This is how I reference the js file in my problem template, it works fine on dev: <script src='{% static 'jquery.twbsPaginationAlt.min.js' %}'></script> For convenience, here is what django-heroku does in terms of staticfiles: logger.info('Applying Heroku Staticfiles configuration to Django settings.') config['STATIC_ROOT'] = os.path.join(config['BASE_DIR'], 'staticfiles') … -
django - template IF tag - how to do IF variable <= current date
In my models.py I have a end_date variable. In my template, I'd like to show certain stuff only if that end_date is passed. Is there a way to do that in the template? {% if end_date <= now %} ... {% else %} ... {% endif %} That doesn't work... Any pointers? Thanks! -
UniqueValidator with case sensitive char field
In serializer I have defined a name filed like this name = serializers.CharField(max_length=255,validators=[UniqueValidator(queryset=Names.objects.all())]) But on insertion I is letting add a same name with case sensitive name , Like Helo and helo both are inserting -
Error in following Django message warning code
I am getting error in the code below: {% if messages %} {% for message in messages %} x {{ message }} {% endif %} {% block content %} {% endblock %} The error message is as follow: Django Version: 3.0.8 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 53: 'endif', expected 'empty' or 'endfor'. Did you forget to register or load this tag? Exception Location: C:\hashimcapital\venv\lib\site-packages\django\template\base.py in invalid_block_tag, line 521 Line 53 is {% endif %} -
How to serve Multilingual URLs in Django DMS?
I'm trying to internationalize my site with Django CMS 3.7. Ref: http://docs.django-cms.org/en/latest/how_to/languages.html[![enter image description here]1]1 the language code and content are all setup ok. but I couldn't setup the URL with multilingual. when I tried to set URL with other language(ie. Chinese), error message: Slug must not be empty. only English is ok, screenshot attached. any ideas to fix it? thanks all -
How to set the maximum image size to upload image in django-ckeditor?
I am using django-ckeditor for my project to upload image along with text content. I used body = RichTextUploadingField(blank=True, null=True) in model. Now I want to restrict the user to upload large size images in content or larger than predefined maximum height/width. I want the uploaded images in content of particular height/weight and size like less then 1mb. How can I predefine maximum image height and width as well as maximum image size limit? Is there any way to define it from django-ckeditor configuration? Or How to resize the uploaded images from content at backend after user submitted the form? Here is my models.py: class Post(models.Model): STATUS_CHOICES = { ('draft', 'Draft'), ('published', 'Published'), } title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextUploadingField(blank=True, null=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') I tried a lot to solve it but failed.Any suggetion to solve the issue? Thanks in advance. -
Django and ngnix login problem Reload login
I'm a bit of a novice, not to mention a lot in django and ngnix, I have a django server called backend-for-frontend-ms, it runs on port 8083, the problem is that when I start ngninx, it redirects me to the login I want, but when I start session the page simply reloads I do not understand very well why this happens but I suppose it is something from the host but I do not know what to configure or add This is my code the ngninx SERVER_NAME = mydomain.co upstream django_server { server $DJANGO_HOST:$DJANGO_PORT; } server { listen 80; server_name $SERVER_NAME; try_files $uri @django_server; location @django_server{ proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://django_server; } } This is my settings.py from the service django SERVICE_NAME = os.environ.get( 'POSTGRES_BACKEND_FOR_FRONTEND_MS_DATABASE_NAME', '') ALLOWED_HOSTS = ['manto.c-pyme.co'] if DEBUG: ALLOWED_HOSTS.append( '{}.localhost.com'.format(SERVICE_NAME).replace('_','-')) #else: # ALLOWED_HOSTS.append( # '{}.c-pyme.co'.format(SERVICE_NAME).replace('_','-')) # Application definition ------------------------------------------------------ INSTALLED_APPS.extend([ 'backend_for_frontend_MS', 'user_MS', 'manto_MS' ]) MIDDLEWARE.insert( 4, '{}.middleware.MultipleProxyMiddleware'.format(SERVICE_NAME)) MIDDLEWARE.insert( 5, '{}.middleware.TimezoneMiddleware'.format(SERVICE_NAME)) MIDDLEWARE.insert( 11, '{}.middleware.SetOautClientCredentials'.format(SERVICE_NAME)) MIDDLEWARE.insert( 12, '{}.middleware.CompanyHostMiddleware'.format(SERVICE_NAME)) ROOT_URLCONF = '{}.urls'.format(SERVICE_NAME) # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://example.com/media/", "http://media.example.com/" MEDIA_URL = '/{}/media/'.format(SERVICE_NAME) WSGI_APPLICATION = '{}.wsgi.application'.format(SERVICE_NAME) TEMPLATES = [ { 'BACKEND': … -
Issues upgrading python social auth django (psycopg2.IntegrityError)
I am working on a codebase using Django 1.9, I am busy getting everything ready to upgrade to 1.10. I have run into an issue after migrating from python social auth to python social auth app django. I have used the steps found here After updating my settings and url files, I ran into the below error. Does anyone know how I can get around this? Running migrations: Rendering model states... DONE Applying social_django.0006_partial... OK Applying social_django.0007_code_timestamp... OK Applying social_django.0008_partial_timestamp... OK Applying social_django.0009_auto_20191118_0520...Traceback (most recent call last): File "/home/brendan/venvs/social/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: column "modified" contains null values The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/brendan/venvs/social/lib/python3.6/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/home/brendan/venvs/social/lib/python3.6/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/brendan/venvs/social/lib/python3.6/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/home/brendan/venvs/social/lib/python3.6/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/home/brendan/venvs/social/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/home/brendan/venvs/social/lib/python3.6/site-packages/django/db/migrations/executor.py", line 92, in migrate self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/brendan/venvs/social/lib/python3.6/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/brendan/venvs/social/lib/python3.6/site-packages/django/db/migrations/executor.py", line 198, in apply_migration state = migration.apply(state, schema_editor) File … -
Django not loading database after Heroku plan upgrade
I recently updated my Postgresql plan on Heroku and migrated the data from the old database to the new one, i destroyed the old database with which worked fine. After the migration my app stoped working and i got this error: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Is there something else that i need to change in my app so that i connect to a new database i created, the new database has a different attached as name is that a factor? Thank you -
Optimize Serializer Performance in Django Rest Framework
I'm developing a web app using Django and Django Rest Framework and struggling with slow API responses which appear to be based on fetching data from related tables. Test case 1 runs very quickly because the fields are directly tied to the Host model. As soon as I introduce a many-to-many field, it slows down dramatically. Test case 1 - takes 250ms serializers.py class HostSerializer(serializers.Serializer): created = serializers.DateTimeField() last_updated = serializers.DateTimeField() name = serializers.CharField(); Test case 2 - takes 30s serializers.py class HostSerializer(serializers.Serializer): created = serializers.DateTimeField() last_updated = serializers.DateTimeField() name = serializers.CharField(); applications = serializers.SerializerMethodField(read_only=True) def get_applications(self, instance): return [item.name for item in instance.applications.all()] models.py class Host(models.Model): created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) name = models.CharField(unique=True, max_length=settings.MAX_CHAR_COUNT) ip_addresses = models.ManyToManyField(IPAddress, blank=True) open_ports = models.ManyToManyField(Port, blank=True) domain = models.ForeignKey('Domain', on_delete=models.CASCADE) applications = models.ManyToManyField(Application, blank=True) tls = models.ForeignKey(TLS, on_delete=models.CASCADE, blank=True, null=True) class Meta: ordering = ['name'] def __str__(self): return self.name def __repr__(self): return self.name def __eq__(self, other): if isinstance(other, Host): return self.name == other.name return False def __hash__(self) -> int: return hash(self.name) def __lt__(self, other): return self.name < other.name views.py class HostList(generics.ListAPIView): """ List all hosts for a given domain """ host_service = HostService() def get(self, request, domain_name, format=None): hosts = self.host_service.find_hosts_by_domain_name(domain_name) … -
Im getting error object of type 'NoneType' has no len()
im getting this Nonetype error.im stuck at it all day. first i was getting MultiDictError after changing it to filetitle = request.POST.get('bob') contentitle = request.POST.get('pop') it seems to work and now this error. views.py def add(request): filetitle = request.POST.get('bob') contentitle = request.POST.get('pop') return render(request, "add/add.html"),{ "entries":util.save_entry(filetitle,contentitle) } utills.py def save_entry(title, content): """ Saves an encyclopedia entry, given its title and Markdown content. If an existing entry with the same title already exists, it is replaced. """ filename = f"entries/{title}.md" if default_storage.exists(filename): default_storage.delete(filename) default_storage.save(filename, ContentFile(content)) add.html {% block body %} <h1>Create New Page</h1> <form action="encyclopedia:add" method="post"> {%csrf_token%} <input name="bob" type="text" placeholder="Enter the Markdown content " id="abz"> <textarea name="pop" rows="20" cols="25" value="content"></textarea> <input type="submit" value="submit" /> </form> {% endblock %} i tried several things but none of them seems to work. thanx in advance -
I am trying to save a record in table two of one to many relationship and retrieve it for specific user in Django
I have two tables one user and one MyGoal with one to many relationship between them in this order only. I am unable to save the record in table though i am able yo create form from model, secondly i want to display goals of a particular user in the my goal temple it will be of the user who has logged in ,i have written code for these two tasks but am unable to complete them please help. Models.py file class MyGoal(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) Goal_subject=models.CharField(max_length=50) Goal_Url=models.URLField() Forms.py class UserForm(forms.ModelForm): password=forms.CharField(max_length=10) class Meta(): model=User fields=('username','email','password') class MyGoalForm(forms.ModelForm): class Meta: model=MyGoal fields="__all__" Url.py applications url(r'^MyGoal/$',views.MyGoalView,name='MyGoal'), Url.py project url(r'^FirstApp/',include('FirstApp.url')), Views.py @login_required def MyGoalView(request): My_goal= MyGoal.objects.filter(user=request.user) form=MyGoalForm() if request.method=="POST": form=MyGoalForm(request.POST) if form.is_valid(): form.save(commit=True) return index(request) else: print("Invalid form") return render(request,'FirstApp/MyGoal.html',{'forms':form,'goal':My_goal}) Template {%for p in My_goal%} {{p.Goal_Url}} {%endfor%} <form> {{forms.as_p}} {%csrf_token%} <input type="submit" value="Submit"> </form> -
Django automatic Logout and and after login it stays on same page
I am new to Django and using Django 3.0.2. Sometimes Django automatically logout and when I try to log in on my website then it stays on the login page but creates a session(I mean, I can see all the buttons which a user will see after login in header and footer). I am not experiencing this issue when I am manually logging out and logging in. Please help if someone else is also experiencing the same issue. Thanks in advance. -
What is the best way to implement a REST API based payment gateway for a Django web app
Should i make the payment requests from views.py or from them templates using javascript. Currently i am sending http requests from views.py to the REST API and the problem is how do i send the product price to the template and when the user confirms payment, how do i fetch the amount to be paid. The rest of the payment details like credit card number i collect from a checkout form.