Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a page where a field value can be set/modified for many instances of an object with one submit?
I have a model, Experiment and a model, Ad which has a foreign key to Experiment. Ads also have a foreign key to another model, Category. I'm hoping to create a page where a user can set the category of many/all ads for a given experiment without having to press submit for each ad. A DetailView of an Experiment lets me display all of the ads for the experiment but I'm not sure how to add a dropdown or radio buttons (preferred) for each ad with a single 'save' button which would update all of the ads w/ the new category values. I think this is what formsets are meant to achieve but it seems like this might be a bit different. I'm not trying to allow a user to add/modify new category values but rather just choose one from what's available for each ad on one page. So the relationship between Ad and Category seems to be different than what I've read re: inlineformsets I'm using Django 2.2 and have tried to figure this out with formsets and inlineformsets but am struggling to see the path ahead. Basic structure of the models: class Category(models.Model): name = models.CharField(max_length=120) display_name = … -
Using path() in Django for URL mapping what is the name= keyword argument for?
What is the name= keyword argument used for? is it used to pass reference later? Sorry I am new to Python and Django. example ''' from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), path('contact/', views.contact, name='contact') ] ''' -
Django: How to append html to template?
I need to pass a html (mini template) with a list of prices to my template: shop/medidas-cantidades.html. The prices are dynamic values that get queried every time user changes the size of the product selecting a different radio button. This is the query, I'll be doing to get the prices: def prices(request): size_selected = request.GET.get("size_selected") prices = list(costo_de_los_productos.objects.filter(category=Category.objects.get(slug='c_slug'), product=Product.objects.get(slug='product_slug'), size=size_selected).values_list("price",flat=True)) return render(request, "shop/prices.html", {"prices": prices}) Now, I'm sending this data to a template called shop/prices.html, where I've: {% for price in prices %} <span>{{price}}</span> {% endfor %} In shop/medidas-cantidades.html I have this to get which radio button is selected and send this value to backend functionprices(request): function get_prices() { return new Promise(function (resolve, reject) { var size_selected = $('input[name=size]:checked').val(); $.ajax({ url: "/prices/", data: { // Pass parameters in separate object size_selected: size_selected }, }).done(function (result) { $('input[name=size]:checked').html(result); resolve(result) }); }); } $("document").ready(function () { $('input[name=size]').change(async /* <--- */ function () { await /* <--- */ get_prices(); }); }); I'm using a FormView to render my main html shop/medidas-cantidades.html: class StepOneView(FormView): form_class = StepOneForm template_name = 'shop/medidas-cantidades.html' success_url = 'subir-arte' def get_initial(self): # pre-populate form if someone goes back and forth between forms initial = super(StepOneView, self).get_initial() initial['size'] = self.request.session.get('size', None) … -
django messages avoid to display property object with message
I create some simple Django success form save message but anty time with my message show and property object and i don't like this because is useless for users i want to keep only the message with code. views.py def add_category(request): user = request.user if request.method == "POST": form = catForm(request.POST) if form.is_valid(): note = form.save(commit=False) id=note.id messages.success(request, 'NEW ENTRY CODE %s.'%(id)) return render(request, "template1.html") else: form = catForm() return render(request, 'template2.html',{'form':form}) html page template 1 : {% if messages %} <ul> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> {% endif %} result message : <property object at 0x000001A606930EA8> NEW ENTRY CODE 56. how can I show my message without show me that <property object at 0x000001A606930EA8> message? I use all but without success property message stay in all messages messages.debug(request, 'Total records updated {0}'.format(count)) messages.info(request, 'Improve your profile today!') messages.success(request, 'Your password was updated successfully!') messages.warning(request, 'Please correct the error below.') messages.error(request, 'An unexpected error occured.') -
Loading data from Json file into PostgresSql causes: ERROR "duplicate key value violates unique constraint - already exists."
I am deploying my Django site on to Google Cloud. One of the step is to change the database to postgresSQL. As I am using SqlLite locally I wanted to migrate all of the database into postgresSql. I followed an online guide where you Dump your data first and then change Database in settings.py to your new database. I have done everything upto this command; python manage.py loaddata datadump.json where datadump.json is the dumped database from SQLITE. Now I am stuck with this error django.db.utils.IntegrityError: Problem installing fixtur, Could not load users.Profile(pk=3): duplicate key value violates unique constraint "users_profile_user_id_key" DETAIL: Key (user_id)=(1) already exists. and I don't have any idea as to what to do. Some answers I looked up such as this: postgresql duplicate key violates unique constraint AND Django admin "duplicate key value violates unique constraint" Key (user_id)=(1) already exists haven't helped, as I cannot understand what's going on. I did use MySQL 6 years ago, but I cannot understand this. I managed to run some SQL commands from online resources and managed to produce this for my database: !https://imgur.com/a/qQNLEs7 I followed these guides: https://medium.com/@aaditya.chhabra/how-to-use-postgresql-with-your-django-272d59d28fa5 https://www.shubhamdipt.com/blog/django-transfer-data-from-sqlite-to-another-database/ -
How show many questions after submit form - Django
I have this view: from django.shortcuts import render, get_object_or_404, HttpResponseRedirect, HttpResponse, reverse from . models import Certificacao, Certificado from questoes . models import Situacao, Questao from multescolha . models import Alternativa, MCQuestao from . forms import QuestaoForm from django.views.generic import ListView, FormView class HomeView(ListView): model = Certificacao template_name = 'certificacoes/index.html' def certificados(request, slug): certificacao = get_object_or_404(Certificacao, slug=slug) certificados = Certificado.objects.filter(certificacao__slug=slug) context = { 'certificacao': certificacao, 'certificados': certificados, } return render(request, 'certificacoes/certificados.html', context) class Perguntas(FormView): form_class = QuestaoForm template_name = 'certificacoes/pergunta.html' template_name_result = 'certificacoes/resultado.html' def get_form(self, *args, **kwargs): id_certificado = self.kwargs['id'] # url capturada via kwargs slug_certificacao = self.kwargs['slug'] # url capturada via kwargs self.cache_questoes = Questao.objects.filter(situacao__certificado__id=id_certificado, situacao__certificado__certificacao__slug=slug_certificacao).values_list('id', flat=True) self.questao = Questao.objects.get_subclass(id=self.cache_questoes[0]) self.alternativas = Alternativa.objects.filter(questao=self.questao) if self.form_class is None: form_class = self.get_form_class() else: form_class = self.form_class return form_class(**self.get_form_kwargs()) def get_form_kwargs(self): kwargs = super(Perguntas, self).get_form_kwargs() return dict(kwargs, questao=self.questao) def form_valid(self, form): hipotese = form.cleaned_data['respostas'] correto = self.questao.checar_correta(hipotese) if correto is True: return render(self.request, self.template_name_result, {'correto': correto, 'escolhida': self.questao.alternativa_escolhida(hipotese), 'fundamento': self.questao.alternativa_fundamento(hipotese), 'pergunta': self.questao}) else: return render(self.request, self.template_name_result, {'correto': correto, 'escolhida': self.questao.alternativa_escolhida(hipotese), 'fundamento': self.questao.alternativa_fundamento(hipotese), 'pergunta': self.questao}) def get_context_data(self, **kwargs): context = super(Perguntas, self).get_context_data(**kwargs) context['questao'] = self.questao context['alternativas'] = self.alternativas return context This line returns me the number of objects that were found (can be … -
Saving HTML multiple row data to Database
How can I save multiple row data from HTML table to Django database. Suppose, I have a list of Items and its price, then I want to select any of item and added to HTML table, then select another item and so on. So, how will I save those multiple items to the database all at once? -
How do I make a real-time machine learning project in Django models with an update-able database?
Okay, so what I want to do is learn about how models and databases work (of which I have very limited knowledge of) in Django through a Machine Learning mini-project in which the website will take user-drawn-digits and predict/recognize what digit it is. After every query it would ask if it has predicted correctly or not and then update the training dataset with the new datapoint. So the question is, how or where do I start if I want the database to not just be a csv file and want to use sql to interact with the 'databases'? Any help/pointers will be highly appreciated. Thanks in advance! -
Custom SRID in Django-Leaflet
I'm having trouble specifying a custom SRID with django-leaflet. The documentation on projections isn't very detailed, and mentions only briefly: By default, django-leaflet will try to load the spatial reference from your static files at “proj4js/{{ srid }}.js”. If it fails, it will eventually rely on spatialreference.org. I followed the django-leaflet installation guidelines, and added the SRID used in my data in PostGIS as follows: LEAFLET_CONFIG = { 'SRID': 2056, # See http://spatialreference.org 'DEFAULT_CENTER': (46.800663464, 8.222665776), 'DEFAULT_ZOOM': 7, 'MIN_ZOOM': 1, 'MAX_ZOOM': 20, } But this raises the following errors in Chrome: uncaught exception: Leaflet and proj4 must be loaded first The script from “http://127.0.0.1:8000/static/proj4js/2056.js” was loaded even though its MIME type (“text/html”) is not a valid JavaScript MIME type. Loading failed for the <script> with source “http://127.0.0.1:8000/static/proj4js/2056.js”. uncaught exception: No projection definition for code EPSG:2056 I have leaflet in INSTALLED_APPS, and also load proj4.js and proj4leaflet.js in my page's head. <!DOCTYPE html> {% load static %} {% load leaflet_tags %} <html lang="en"> <head> {% leaflet_js %} {% leaflet_css %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/leaflet-ajax/2.1.0/leaflet.ajax.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.5.0/proj4.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/proj4leaflet/1.0.2/proj4leaflet.min.js"></script> <meta charset="utf-8"> <style> .leaflet-container { width: 600px; height: 400px; } #specialbigmap { height: 800px; } .django-leaflet-raw-textarea { width: 100%; } … -
Django 2.2 + DetailView Multiple models with filtering
I'm trying to get my three models working correctly on one DetailView. I have all of them loaded, but the model that contains the images keeps showing the first image. I know I need to filter it somehow, but I don't really know how to do it. Since I need the product info to filter the images. Here is my code: views: class VendorDetailView(DetailView): context_object_name = 'vendor_detail' model = Vendor queryset = Vendor.objects.all() template_name = 'vendor_details.html' def get_context_data(self, **kwargs): context = super(VendorDetailView, self).get_context_data(**kwargs) context['products'] = Product.objects.filter(vendor=self.get_object()) context['image'] = ProductImage.objects.all() return context models: class Product(models.Model): product_model = models.CharField(max_length=100) vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) slug = models.SlugField(max_length=200, unique=True, null=True) length = models.CharField(max_length=50) length_range = models.ForeignKey(LengthRange, on_delete=models.SET_NULL, null=True, blank=True) hull_type = models.ForeignKey(Hull, on_delete=models.SET_NULL, null=True, blank=True) max_beam = models.CharField(max_length=50, blank=True, default='0') cockpit_length = models.CharField(max_length=50, blank=True, default='0') cockpit_beam = models.CharField(max_length=50, blank=True, default='0') price = models.DecimalField(decimal_places=2, max_digits=50) power = models.ForeignKey(PowerConfiguration, on_delete=models.SET_NULL, null=True, blank=True) average_bare_hull_weight = models.CharField(max_length=50, blank=True, default='0') fuel_capacity = models.CharField(max_length=50, blank=True, default='0') seating_capacity = models.ForeignKey(Seat, on_delete=models.SET_NULL, null=True, blank=True) speed = models.ForeignKey(SpeedRange, on_delete=models.SET_NULL, null=True, blank=True) warranty = models.CharField(max_length=256, default='None') hull_only_available = models.BooleanField(blank=False, default=False) description = models.TextField() featured = models.BooleanField(blank=False, default=False) class Meta: ordering = ['product_model'] def __str__(self): return '{} {}'.format(self.vendor, self.product_model) def save(self, *args, **kwargs): # just … -
What is advantage of using serializer to save object in django?
Suppose I have a Model as follow: class SampleUser(models.Model): name = models.CharField(max_length=100) email = models.CharField(max_length=100) class Group(models.Model): members = models.ManyToManyField(SampleUser) name = models.CharField(max_length=100) I want to know what are the advantage of using Serializers to create an object, lets say serializers.py class SampleUserSerializer(serializers.ModelSerializer): class Meta: model = SampleUser fields = ('name','id','email') views.py serializer = SampleUserSerializer(data = request.data) if(serializer.is_valid()): serializer.save() than directly creating an sample user object SampleUser.objects.create(....) Thanks in advance!!! -
Invalid trial_end when trying to update an existing Subscription
When calling stripe's api to update a customer's subscription, I am getting an error. When users perform actions on my site, they can earn free months for their subscription. To give users free months, I'm trying to update the trial_end parameter to extend the free trial period. The error I'm getting is: Invalid trial_end must be one of now new_end_dt = datetime.now() + timedelta(days=30) new_end_ts = new_end_dt.replace(tzinfo=timezone.utc).timestamp() stripe.Subscription.modify( self.stripe_subscription_id, trial_end=new_end_ts, trial_from_plan=False, ) -
AttributeError: module 'django.contrib.auth.views' has no attribute 'LoginView'
I am using an older version of django.After i run my code i get this error -"AttributeError: module 'django.contrib.auth.views' has no attribute 'LoginView'".I should get error if I use login instead of LoginView. Even after using login I get the same attribute error. this is my urls.py- from django.conf.urls import url from django.contrib.auth import views as auth_views from . import views app_name = 'accounts' urlpatterns = [ url(r"login/$",auth_views.LoginView.as_view(template_name="accounts/login.html"),name='login'), url(r"logout/$", auth_views.LogoutView.as_view(), name="logout"), url(r"signup/$", views.SignUp.as_view(), name="signup"), ] this is my app's urls.py- from django.conf.urls import url,include from django.contrib import admin from .import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$',views.HomePage.as_view(),name='home'), url(r'^accounts/',include('accounts.urls',namespace='accounts')), url(r'^accounts',include('django.contrib.auth.urls')), url(r'^test/$',views.TestPage.as_view(),name='test'), url(r'^thanks/$',views.ThanksPage.as_view(),name='thanks') ] and views.py- from django.shortcuts import render from django.contrib.auth import login, logout from django.core.urlresolvers import reverse_lazy from django.views.generic import CreateView from . import forms class SignUp(CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy("login") template_name = "accounts/signup.html" I got this result after making migrations.My app's name is accounts:- (myDjangoEnv) C:\Users\saini computers\Desktop\simple_social_clone\simplesocial>python manage.py makemigrations accounts Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\saini computers\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Users\saini computers\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\saini computers\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\saini computers\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\management\base.py", line 342, in execute self.check() File "C:\Users\saini … -
How to display siblings of page in navigation when there are no children?
I'm trying to render dynamic menu in Django/Wagtail. It works well so far but as I traverse the page tree and get to the last child, the menu disappears. I'm wondering if there is a way to make it so when a user has clicked through all the pages and reaches a page with no further children, is it possible for me to get the siblings of that page and display those links? Or is there a way for me to tell wagtail that if the page has no children, render the siblings of the page? This way someone can easily navigate the pages even if they are on a last child. I'm using wagtailmenus to render a flat_menu to do this so far. I was able to get this to sort of work by doing the following: {% for content in page.get_siblings %} This worked to get the siblings as an experiment but of course the logic is no longer there to get the children. Below is my current code. {% load static wagtailcore_tags menu_tags %} <aside class="sidebar sidebar-boxed sidebar-dark"> <ul class="nav sidenav dropable sticky"> {% for content in page.get_children %} <li class="{{ content.active_class }}"> <a href="{% pageurl content … -
Django send_mail security password
I am trying to send an email from an app, however in my settings it asks to put the EMAIL_HOST_PASSWORD and although it worked, how can you protect it from being viewed it GitHub or when it's deployed? settings.py: EMAIL_HOST='smtp.gmail.com' EMAIL_HOST_USER='lala@gmail.com' EMAIL_HOST_PASSWORD='' EMAIL_PORT=587 EMAIL_USE_TLS=True EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend' Views.py: def contact(request): if request.method=='POST': message=request.POST['message'] send_mail('Contact Form', message, settings.EMAIL_HOST_USER, ['lala@gmail.com'], fail_silently=False) return render(request, 'first_app/contact.html') -
Linking button to new page in Django
I have created an update view and am trying to link it to my form but the button linking doesn't seem to be working at all urls.py path('uploadupdate/<int:upload_id>', UploadUpdate.as_view(), name='uploadupdate'), forms.py <button href="{% url 'uploadupdate' uploads.upload_id %}" type="submit" class="edit" formmethod="POST">Edit</button> views.py class UploadUpdate(UpdateView): form_class = UploadEditForm template_name = 'studyadmin/upload_update_form.html' queryset = Uploads.objects.all() def get_object(self, queryset=None): obj = Uploads.objects.get(upload_id=self.kwargs['upload_id']) print(obj) return obj def form_valid(self, form): upload = form.save(commit=False) upload.save() return redirect('/manageupload/') enter code here -
Static files don't get updated in django
Some static scripts and css in my django application fail to load and produce a "404" on both the terminal and the browser's console, -I deleted the cache and refreshed million times -I am very sure about the path to the files -I have a static files directory defined inside every app; with a directory inside it carrying the app name "my_app/static/my_app" -The settings.py: STATIC_ROOT = '' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join('static'), ) it consumed most of my day, what's the problem ? -
Django: Checkbox choice displaying as True/False value
I'm a beginner at django and I'm trying to get my calendar to display a checkbox itself rather than a True/False value. I'm able to get the data to save from the form however models.py class Event(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField(max_length=350) start_time = models.DateTimeField() #end_time = models.DateTimeField() event_checked = models.BooleanField() @property def get_html_url(self): url = reverse('cal:event_edit', args=(self.id, )) return f'<a href="{url}"> <label> {self.title} {self.event_checked}<label></a>' def __str__(self): return '{} - {} by {}'.format(self.title, self.description, self.user) forms.py class EventForm(forms.ModelForm): event_checked = forms.BooleanField() class Meta: model = Event # datetime-local is a HTML5 input type, format to make date time show on fields widgets = { 'start_time': DateInput(attrs={'type': 'datetime-local'}, format='%Y-%m-%dT%H:%M'), } fields = ('title', 'description', 'start_time') def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) # input_formats parses HTML5 datetime-local input to datetime field self.fields['start_time'].input_formats = ('%Y-%m-%dT%H:%M',) views.py def event(request, event_id=None): instance = Event() if event_id: instance = get_object_or_404(Event, pk=event_id) else: instance = Event() form = EventForm(request.POST or None, instance=instance) if request.POST and form.is_valid(): event = Event.objects.create(**form.cleaned_data, user=request.user) print(event.title) return HttpResponseRedirect(reverse('cal:calendar')) return render(request, 'cal/event.html', {'form': form}) How my calendar looks with some events -
How do i created multiple connected objects at once in Django Rest Framework?
I have following model in my Django Model class Match(models.Model): initiator = models.ForeignKey('CustomUser', related_name='match_initiator', on_delete=models.CASCADE) matched_person = models.ForeignKey('CustomUser', related_name='matched_person', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) algo_version = models.IntegerField() room_no = models.ForeignKey('Room', related_name='room_match', on_delete=models.CASCADE, null=True, blank=True) class Room(models.Model): name = models.CharField(max_length=20, unique=True) members = models.ManyToManyField(CustomUser, related_name="joined_rooms") created_at = models.DateTimeField(auto_now=True,editable=False) is_active = models.BooleanField(default=True) So basically I have two models, Room and Match with Match having a foreign key to a room. Now I want to create both of these objects at once, but I can not do it as first I have to create Room object get the id of it and assign it to Match object instance and then save it again. Problem with this is that if any of the model save is failed, it breaks the code. Is there any way I can create both Match and Room object at once? Thanks in advance!!! -
Create automatic login mechanism for Kolibri education website
I'm trying to create a mechanism which will automatically log a user into a Kolibri education website. Kolibri is typically hosted offline in communities without internet access and provides services like Kahn Academy and other educational programming. There is a demo site set up at: https://kolibridemo.learningequality.org/user/#/signin username: 'learnerdemo', password: 'pass' Kolibri is built on Django. Our users will be coming from one of our own websites and accessing a version of Kolibri that we host ourselves. I've tried using some basic scripts like the ones from these questions: Automatic login script for a website on windows machine? But I get various errors like CSRF verification problems and others. I can get responses back from here by inputting {"username":"learnerdemo","password":"pass"} https://kolibridemo.learningequality.org/api/auth/session/ And can generate csrf tokens etc. by doing curl commands like this one: curl -v -X POST https://kolibridemo.learningequality.org/api/auth/session/ -d 'username=learnerdemo&password=pass' I'm not sure how to pull all of this together to do the following -- ultimately my goal is to be able to attach the u/p (encrypted or otherwise) to the URL and pass it to the kolibri site or to an intermediate/script site and login automatically. Can anyone help create or point me in the right direction to a mechanism … -
How to set up Django Models? Users can post in rooms they are subsribed to
I wanted to create an app where Users can be put into Rooms where they can send Posts to which are then displayed (if they have permission to do so). I want the users to be able to select a room they are subsribed to on the Website and see all the Posts which the other users posted within the Room. What is the best way to set up the Django models for this ? I also don't know How i can add a relation between User and Room in the user model ? My thougts where the following: Users can have multiple Groups Rooms can have multiple users and Posts Posts have one User as their author and can be posted in multiple Rooms at once So i created the following models: class Room(models.Model): roomname = models.CharField(max_length=6) class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) rooms = models.ManyToManyField(Room) I don't know How i can add a relation between User and Room in the user model ? How would you Change the models ? Is this even the Right way to do this or are there better Options for Setting up the models … -
After posting content of my blog ni, they are shown in html format rather than pure text
I am using tinymce for my web blog that allows me to post my blogs, but as I post they are shown in rawHTML format like below: this is my template {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block styler %} {% endblock styler%} {% block content %} <div class="content-section"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset> <legend class="border-bottom pb-3 mb-3">Post blog</legend> {{ form|crispy }} </fieldset> <button class="btn btn-outline-info" type="submit">Post</button> </form> </div> {% endblock content %} and my forms.py class PostCreateForm(forms.ModelForm): title = forms.CharField() content = forms.CharField( widget=TinyMCEWidget( attrs={'required': False, 'cols': 30, 'rows': 10} ) ) thumbnail = forms.ImageField() class Meta: model = Post fields = ['title', 'content', 'thumbnail'] and associated views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post form_class = PostCreateForm help me how to solve this problem, I searched a bit and find out this could be due to @Html.Raw(@Model.LongDescription) but I don't know either where do I have to add that? and please check if you can do any improvement for my code. thank you for your help. -
Multiple Django Project + Nginx
Am trying to run multiple dashboards written in Django to run on my server, but am not getting it up and running.Followed this digital ocean tutorial and modified it according to this SO answer. Now everything is up and running and but when am pointing to my url, it shows Nginx welcome page http://ipaddr/first_dashboard Below is the gunicorn_fdab.socket file : [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn_fdab.sock [Install] WantedBy=sockets.target Below is gunicorn_fdab.service file : [Unit] Description=gunicorn daemon for fdab Requires= gunicorn_fdab.socket After=network.target [Service] User=root Group=root WorkingDirectory=/opt/fdab ExecStart=/opt/anaconda/envs/fdab/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn_fdab.sock \ fdab.wsgi:application [Install] WantedBy=multi-user.target Now this is my Nginx conf file : server { listen 80; server_name 111.11.11.111; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /opt/fdab/fdab; } location /fdab { include proxy_params; rewrite /fdab(.*) $1; proxy_pass http://unix:/run/gunicorn_fdab.sock; } } Am not able to understand where am doing it wrong. If am doing curl --unix-socket /run/gunicorn_fdab.sock localhost , it just returning nothing. (base) root@virtualserver01:~# curl --unix-socket /run/gunicorn_fdab.sock localhost (base) root@virtualserver01:~# Project is stored at /opt/fdab. -
Django-allauth facebook claaback (/accounts/facebook/login/callback/) error without trace
I have successfully login to facebook: "GET /accounts/facebook/login/ HTTP/1.0" 302 0 "GET /accounts/facebook/login/callback/?code=AQCMYR8By_NW2ArWZ63Kq00twt4mSUiQ9BBApbvwt7eLWYyiMxYJkOXuRlbXzb9tq4lS-QunyFUlKxgVc0P6D3K-rl6AVkuMUZ2o7XjJi1LNmiaiUdzT6WHzWhyAbRm2SLIkm6mwgOPMI_g47h_yRE4tra1qLMZikfWq9npXC2QWybHQ9XeaFv3zS13EqaG8H9rJ-RMKmZXb9Ti4uSzK3-Vlzk1ORLWEIbIZw3YiEpqg18fSf4hb3PEB-ro7C5FmflEdoxwaig3Vdmddvl9wOyqmx1czE4bIwqtYR3yFilZ2h0o8uEj0g03rbBY5e5GGAcNyjFmgQj1zGsgMJIQDjFXO&state=fBRf1vERs3PD HTTP/1.0" 200 4362 In front I recieves message Social Network Login Failure An error occurred while attempting to login via your social network account. VK auth is working. What can be wrong and now to debug it? Any SOCIALACCOUNT_PROVIDERS and any other VIRABLES values. -
"author_link" does not work in Django syndication feed framework
In the Django Feed class reference for RSS/ATOM feed we have the next field: # AUTHOR LINK --One of the following three is optional. The framework # looks for them in this order. In each case, the URL should include # the "http://" and domain name. def author_link(self, obj): """ Takes the object returned by get_object() and returns the feed's author's URL as a normal Python string. """ def author_link(self): """ Returns the feed's author's URL as a normal Python string. """ author_link = 'https://www.example.com/' # Hard-coded author URL. Any of this 3 options does not work. I have working RSS/ATOM feed in my Django project. All other fields are working well: item, descriptions, author etc. But I do not see any "author links" in my RSS.