Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use UserProfileCreationForm on edit profile page?
I have a User and UserProfile which has a OneToOne relation to User. I use AllAuth to take care of registration etc. but I use custom sign up form. This form contains User fields and UserProfile fields. I want to use this form on edit profile page. So basicly I want user to be able to edit anything except username, email and password. The problem is that these three fields are visible when I use this form. class UserProfileCreationForm(forms.ModelForm): username = forms.CharField(label="Benutzername", max_length=40, min_length=5, required=True) email = forms.EmailField(label="Mail", max_length=40, required=True,) first_name = forms.CharField(label='Vorname', max_length=40, required=True) last_name = forms.CharField(label='Nachnahme', max_length=40, required=True) password1 = forms.CharField(label="Kennwort", widget=forms.PasswordInput, min_length=5) password2 = forms.CharField(label="Passwort Bestätigung", widget=forms.PasswordInput) class Meta(): model = models.UserProfile fields = ( 'username','email','first_name','last_name','first_name', 'last_name', 'telephone', 'telephone2', 'city', 'street', 'number', 'psc' ) def __init__(self, *args, **kwargs): super(UserProfileCreationForm, self).__init__(*args, **kwargs) for field_name, field in self.fields.items(): if field_name in ['city', 'street', 'number', 'psc', 'telephone',]: field.required = True def signup(self,request,user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user_profile = models.UserProfile(user=user, telephone=self.cleaned_data.get('telephone'), telephone2=self.cleaned_data.get('telephone2'), street=self.cleaned_data.get('street'), city=self.cleaned_data.get('city'), number=self.cleaned_data.get('number'), psc=self.cleaned_data.get('psc'), ) user_profile.save() def edit_profile(self): self.instance.user.save() self.save() The view: def edit_profile(request): form = UserProfileCreationForm(request.POST or None, initial=model_to_dict(request.user),instance=request.user.userprofile) if request.method == 'POST': form.edit_profile() return HttpResponseRedirect(reverse('profile')) return render(request,'mainapp/edit-profile.html', context={'form':form}) How can I get rid off username, … -
How to extract hashtag form a user post/string?
i want to parse a string from a user input that has #hashtag and print out the result together with other words too for example: a user posts " hello #word, am learning #python and #django today! " i want the out put to be: hello #word, am learning #python and #django today! this is how far i've gone: @login_required @ajax_required def post(request): last_feed = request.POST.get('last_feed') user = request.user csrf_token = (csrf(request)['csrf_token']) feed = Feed() feed.user = user post = request.POST['post'] lookup_hash_tag = post.strip() hstg=re.compile(r"#(\w+)") #print pat.findall(s) for hashtag in hstg.findall(lookup_hash_tag): post = "<span><a href='/hastag/?q={}'>{}</a> </span> {}".format(hashtag, hashtag, post.replace('#', '#')) if len(post) > 0: feed.post = post[:255] feed.save() html = _html_feeds(last_feed, user, csrf_token) return HttpResponse(html) -
out of stack space (infinite loop?) error while working with matplolib and Django
I am trying to show a graph which I am trying to plot in Matplotlib and then showing it with some hard coding in HTML template.But out of 3 attempts, it is working only once else it is throwing TCL Out of stack space error. Below is my coding. def similar_images(request): n_groups = 5 means_men = (20, 35, 30, 35, 27) std_men = (2, 3, 4, 1, 2) means_women = (25, 32, 34, 20, 25) std_women = (3, 5, 2, 3, 3) fig, ax = plt.subplots() # somwhere here it is throwing this error index = np.arange(n_groups) bar_width = 0.35 opacity = 0.4 error_config = {'ecolor': '0.3'} rects1 = plt.bar(index, means_men, bar_width, alpha=opacity, color='b', yerr=std_men, error_kw=error_config, label='Men') rects2 = plt.bar(index + bar_width, means_women, bar_width, alpha=opacity, color='r', yerr=std_women, error_kw=error_config, label='Women') plt.xlabel('Shoe') plt.ylabel('Week') plt.title('Last Year sale details') #plt.xticks(index + bar_width / 2, ('A', 'B', 'C', 'D', 'E')) plt.legend() plt.savefig('/graph.png') plt.close() return render(request,'sales/Details.html') Please, can someone help me here? Below is the error. Exception Type: TclError at /sales/similar_images/ Exception Value: out of stack space (infinite loop?) -
Django-constance: relation "constance_config" does not exist
I am having trouble using django-constance. I've followed the steps from here: https://django-constance.readthedocs.io/en/latest/index.html: pip install "django-constance[database]" add 'constance' and 'constance.backends.database', to INSTALLED_APPS placed the following at the bottom of the settings file (it isn't callled setings.py but common.py): CONSTANCE_BACKEND = 'constance.backends.database.DatabaseBackend' CONSTANCE_DATABASE_PREFIX = 'constance:my_app_name:' CONSTANCE_CONFIG = { 'THE_ANSWER': (42, 'Answer to the Ultimate Question of Life, The Universe, and Everything'), } then ran python manage.py migrate database But a table for dynamic settings wasn't created. This what happpens when I try to list constance settings: $ python manage.py constance list ... django.db.utils.ProgrammingError: relation "constance_config" does not exist LINE 1: ...ce_config"."key", "constance_config"."value" FROM "constance... I am running Python 3.5.2 and Django 1.11.3. Any clue what is going on? -
In Django, where is the correct place to put a base.html that includes CDN links used by all apps?
When you start a Django project called "myproject", within that project you get a folder also called "myproject". Should I put my base.html (which includes links to CDNs like Bootstrap that are used by all my apps) in a folder called "myproject" within a templates folder within the "myproject" folder? In other words, should I put the base.html in myproject/templates/myproject and then place at the top of each HTML page in every app: {% extends 'myproject/templates/myproject/base.html %}? Alternatively, do I place a base.html in each app and extend like: {% extends 'myapp/templates/myapp/base.html %}? Thank you. -
django how to define limit_choices_to
I have a problem by creating a little Django app. I've got the following models: CarRegion(models.Model): name = models.CharField(max_length=64) [...] DamageType(models.Model): name = models.CharField(max_length=64) regions = models.ManyToManyField(CarRegion) [...] Damage(models.Model): kind = models.ForeignKey(DamageKind, on_delete=models.PROTECT, limit_choices_to=???) photo = models.ImageField(_('photo')) region = models.ForeignKey(CarRegion, on_delete=models.PROTECT) [...] Now my question: How I have to define the limit_choices_to keyword argument so that on the admin page if I want to add a damage after choosing a region only the for this region possible damagetypes are shown? Thanks in advance -
PyCharm breakpoints work partially
I have managed to set debug breakpoints on our Python Django server (running on apache). I set up the environment using the PyCharm's recommendations: I setup deployment (working) Also set up "Remote debugging" configuration with mapping (works partially). On server loading I call: sys.path.append('/home/cpmuser/debug/pycharm-debug.egg') import pydevd pydevd.settrace('localhost', port=21000, stdoutToServer=True, stderrToServer=True) This successfully helps catching breakpoints in a number of files - but only on server load time. After last "resume" (F5) there are no more breakpoints. Even after reloading the browser. It simply wont stop on any breakpoint anymore. Any clue how to resolve that? -
how to give engine values to django app for postgre instance that is on google cloud sql?
I was working on heroku for my back-end and data storage. now due to some reasons i want to shift on google cloud sql. i am little bit confused that how i can give engine values in settings.py to access postgre instance. currently i am doing like this. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'snr',#database name 'USER': 'amad', #database user 'PASSWORD': '1234',#database password 'HOST': '/cloudsql/shopnroar-175407:us-central1:snr-instance1', #connection name 'PORT': '5432', #port } } but it giving me error " File "/home/amad/python-docs-samples/appengine/flexible/django_cloudsql/env/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/amad/python-docs-samples/appengine/flexible/django_cloudsql/env/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/home/amad/python-docs-samples/appengine/flexible/django_cloudsql/env/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "/home/amad/python-docs-samples/appengine/flexible/django_cloudsql/env/local/lib/python2.7/site-packages/django/db/backends/postgresql/base.py", line 176, in get_new_connection connection = Database.connect(**conn_params) File "/home/amad/python-docs-samples/appengine/flexible/django_cloudsql/env/local/lib/python2.7/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: FATAL: password authentication failed for user "admin" FATAL: password authentication failed for user "admin" " can somebody tell me how i can access that instance on google cloud sql from my local django app. Any help will be highly appreciated. Thanks. -
How to get many numbers of random records from database?
I know this question has been asked many times, but most of the answers use this method : MyModel.objects.order_by('?')[:4] which will kill the database in the second day of production. I'm looking for a faster and lightweight solution, I'm using the one below for now, but I would like to get more than 1 random query (4 for example). views.py last = MyModel.objects.count() - 1 random_int = random.randint(0, last) records = MyModel.objects.all()[random_int] #one record only Any solution ? -
Write search query for Dajgno Haystack app
I am trying to use Haystack to search from the Elasticsearch Database in my Django app. This is the model 'Recordings' in my models.py: class Recordings(models.Model): channel = models.ForeignKey(Channel, related_name="recordings") date = models.DateTimeField(auto_now_add=True) duration = models.DurationField(default=0) file_size = models.FloatField(default=0.0) file_location = models.CharField(max_length=255) proceed = models.BooleanField(default=False) class Meta: get_latest_by = 'date' ordering = ['-date'] index_together = ["date", "channel"] def __str__(self): return str(self.date) The html page that is responsible to take the search items is search.html <h2>Search</h2> <form method="get" action="."> <table> {{ form.as_p }} <tr> <td> <input type="submit" value="Search"> </td> </tr> </table> {% if query %} <h3>Results</h3> {% for result in page.object_list %} <p> <a href="{{ result.object.get_absolute_url }}">{{ result.object.title }}</a> </p> {% empty %} <p>No results found.</p> {% endfor %} {% if page.has_previous or page.has_next %} <div> {% if page.has_previous %}<a href="?q={{ query }}&amp;page={{ page.previous_page_number }}">{% endif %}&laquo; Previous{% if page.has_previous %}</a>{% endif %} | {% if page.has_next %}<a href="?q={{ query }}&amp;page={{ page.next_page_number }}">{% endif %}Next &raquo;{% if page.has_next %}</a>{% endif %} </div> {% endif %} {% else %} {# Show some example queries to run, maybe query syntax, something else? #} {% endif %} </form> And the query that searches the data from the database is in views.py: def search(uri, term): … -
All javascript and jquery elements on my django project stopped responding on nginx gunicorn ubuntu 16.04
Up until two days ago, every javascript element on my django powered app was working just fine. But for some reasons beyond me, it all stopped yesterday and i spent the whole of yesterday trying to figure it out here is my base.html <div class="list"> <ul> <li><a href="{{ user.get_absolute_url }}">Profile</a></li> <li><p><a href="{% url "edit" %}">Edit your profile</a></li> <li><a href="{% url "password_change" %}">Change your password</a></li> <li><a href="/images/create">Upload</a></li> <li><a href="/images/likes/">likes</a></li> <span class="user"> {% if request.user.is_authenticated %} <li><a href="{% url "logout" %}">Logout</a></li> {% else %} <li><a href="{% url "login" %}">Log-in</a></li> {% endif %} </span> </ul> </div> {% if messages %} <ul class="messages"> {% for message in messages %} <li class="{{ message.tags }}"> {{ message|safe }} <a href="#" class="close">✖</a> </li> {% endfor %} </ul> {% endif %} <div id="content"> {% block content %} {% endblock %} {% block sidebar %} {% endblock %} </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4 /jquery.min.js"></script> <script src="http://cdn.jsdelivr.net/jquery.cookie/1.4.1 /jquery.cookie.min.js"></script> <link href="horbar.css" rel="stylesheet"> <script src="//http://code.jquery.com/jquery-3.2.1.min.js"></script> <script src="horbar.js"></script> <script> var csrftoken = $.cookie('csrftoken'); function csrfSafeMethod(method) { return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $(document).ready(function(){ {% block domready %} {% endblock %} }); $('.list').hide(); $('#one').hide(); $('#two').hide(); $('#request').on('click', function() { $('.list').toggle(); }); $('.image-likes').hide(); $('.count').on('click', function() { … -
Django creating a file and saving in a specific place on server in Linux
I know there are a lot of posts about this topic, but I still can't figure out what I am doing wrong. My goal is to create/update a file in the following directory: root/my_app_name/main/static/media/images/contact_photos My settings.py file looks like this: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' if DEBUG: MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static","static-only") #STATIC_ROOT = [os.path.join(BASE_DIR,"static-only")] MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),"static","media") #MEDIA_ROOT = [os.path.join(BASE_DIR,"media")] STATICFILES_DIRS = ( #os.path.join(os.path.dirname(BASE_DIR),"static","static"), os.path.join(BASE_DIR,"static"), ) Here's what I do now: full_filename = os.path.join(settings.BASE_DIR + '\main\static\media\images\contact_photos', filename) with open(full_filename, 'wb+') as f: f.write(img_data) I end up with the following error: [Errno 2] No such file or directory: '/root/static/media/images/file_name.jpg' -
How to share post on facebook using graph api in Django
I want to share post on facebook using graph api explorer in python-django -
Combining two different serializers into one view returning named JSON arrays
I need to combine two views into a single view. The final combined response should be like this : { "EQUITY": [{ "SYMBOL": "INFY", "BUY_QTY": 10, "BUY_RATE": 1010.01 }, { "SYMBOL": "TCS", "BUY_QTY": 10, "BUY_RATE": 1010.01 }, { "SYMBOL": "MARUTI", "BUY_QTY": 10, "BUY_RATE": 1010.01 }], "FNO": { "OPTIONS": [{ "SYMBOL": "INFY", "EXPIRY_DATE": "2017-07-18", "STRIKE": 1200, "OPT_TYPE": "CE", "BUY_QTY": 10, "BUY_RATE": 1010.01, "SELL_QTY": 0, "SELL_RATE": 0, "DIRECTION": "LONG" }, { "SYMBOL": "NIFTY", "EXPIRY_DATE": "2017-07-18", "STRIKE": 9200, "OPT_TYPE": "PE", "BUY_QTY": 10, "BUY_RATE": 1010.01, "SELL_QTY": 0, "SELL_RATE": 0, "DIRECTION": "SHORT" }], "FUTURES": [{ "SYMBOL": "INFY", "EXPIRY_DATE": "2017-07-18", "BUY_QTY": 10, "BUY_RATE": 1010.01, "SELL_QTY": 0, "SELL_RATE": 0, "DIRECTION": "LONG" }, { "SYMBOL": "NIFTY", "EXPIRY_DATE": "2017-07-18", "BUY_QTY": 10, "BUY_RATE": 1010.01, "SELL_QTY": 0, "SELL_RATE": 0, "DIRECTION": "SHORT" }] } } Initially I had made this into two separate end points but now the requirement is such that both the serializer responses should be in a single view. How can i club both of these serializers into one single view? This is my views.py from rest_framework.generics import ListAPIView from rest_framework.permissions import IsAuthenticated from .serializers import * from .models import EquityPositions class EquityPositionListView(ListAPIView): serializer_class = EquityPositionSerializer permission_classes = [IsAuthenticated] def get_queryset(self): print("logged in user ==== >", self.request.user.username) return EquityPositions.objects.using('tradingdb').filter(client_id=self.request.user.username, … -
How to add id to HTML tags in Django Templates
I am trying to add dynamic id's to the <body> tag in the HTML. Something like this - <body id="{{ django_view_name }}>" I want the id attribute to have the page name, like for the homepage id="home" and for the blog page id="blog" and contact page id="contact" I don't want to use Javascript or Jquery. How can i do this? Any help is really appreciated. -
QuerySet to contain two or more words in Django
I want to select in Django all objects containing two or more words. I'll show you two examples for better understanding: String 1: aab-2;bba-3;dwq-5 SQL query needs to be: LIKE '%aab-2%bba-3%dwq-5%' String 2: wqd-10;dwad-11 SQL query needs to be: LIKE '%wqd-10%dwad-11%' My code: fields = [] for name in names: fields.append(name) data = Data.objects.filter(reduce(lambda x, y: x | y, [Q(genes__contains=name) for name in fields])) But this, from what I see, checks for every word, not a group of words. Edit: fixed error in second example. Edit 2: I get names from another QuerySet. titles = Names.objects.filter(id=id)[0] names = titles.nu.split(';') and id is received with the request. My current code returns (for first example) entries like: aab-2;wqweq-17 -
django-haystack queryset not showing optimal results
I am using Haystack with Elasticsearch in Django to search for a list of items in two tables simultaneously. It runs OK locally, but shows different results in production. def myfunc(request): idlist = request.GET.getlist("idlist[]") queryset = [] queryset = SearchQuerySet().filter( Q(model1_field__in=idlist) | Q(model2_field__in=idlist)).models(model1, model2) return render(request, 'template.html',{"queryset":queryset,}) The list idlist contains items like 402, 403. But the queryset contains results like 40234, 40245, 40256, 40378, etc, i.e, terms which contain the list item as a part, and not just the exact list item. I want to have the exact list items and not the matching ones. What am I missing? -
(Sending email in python using SMTP ) How can i parse a list in body
i can send an Email with SMTP using simple text but i can't send it with alist in body instead of text i need this output; content : "content" text: "text" body: "body Here's the code import smtplib content = 'content' text = 'Text' body = 'body' msg = {'body' : body ,'text':text , 'content':content} print msg mail = smtplib.SMTP('smtp.gmail.com',587) mail.ehlo() mail.starttls() mail.login('mymail','password') mail.sendmail('From' , 'to' , msg) print ('Sent') mail.close() -
Docker+Django, server running but welcome page not showing
When I run my dockerfile I get the right output : ** Performing system checks... System check identified no issues (0 silenced). July 31, 2017 - 11:00:32 Django version 1.11.3, using settings 'tufleur.settings' Starting development server at http://127.0.0.1:8002/ Quit the server with CONTROL-C. ** This is my dockerfile ** FROM django:onbuild # Install Python dependencies RUN pip install django #CMD ["pwd"] RUN ./manage.py makemigrations RUN ./manage.py migrate #RUN ./manage.py collectstatic EXPOSE 8002 #Run Server CMD ./manage.py runserver 127.0.0.1:8002 ** But in the browser the django welcome page is not showing, can you help me to find the problem, because I can't find any -
RequestError: TransportError(400, u'parsing_exception')
I am using django-haystack and Elasticsearch for my app. I have loaded all the requirements and trying to search my indices using search.html But whenever I tried to retrieve the results using an API at http://localhost:8000/search, I am getting the below error and I have googled much about this but couldn't able to get any help: RequestError: TransportError(400, u'parsing_exception') The full error that I am getting is: Traceback (most recent call last): File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/haystack/backends/elasticsearch_backend.py", line 524, in search _source=True) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/elasticsearch/client/utils.py", line 69, in _wrapped return func(*args, params=params, **kwargs) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/elasticsearch/client/__init__.py", line 530, in search doc_type, '_search'), params=params, body=body) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/elasticsearch/transport.py", line 307, in perform_request status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/elasticsearch/connection/http_urllib3.py", line 93, in perform_request self._raise_error(response.status, raw_data) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/elasticsearch/connection/base.py", line 105, in _raise_error raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info) RequestError: TransportError(400, u'parsing_exception') Failed to query Elasticsearch using '(sdf)': TransportError(400, u'parsing_exception') Traceback (most recent call last): File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/haystack/backends/elasticsearch_backend.py", line 524, in search _source=True) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/elasticsearch/client/utils.py", line 69, in _wrapped return func(*args, params=params, **kwargs) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/elasticsearch/client/__init__.py", line 530, in search doc_type, '_search'), params=params, body=body) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/elasticsearch/transport.py", line 307, in perform_request status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout) File "/Manish/Projects/Spark/ad-tracking-django-env/lib/python2.7/site-packages/elasticsearch/connection/http_urllib3.py", line 93, in perform_request self._raise_error(response.status, … -
python social auth, log in without logging out
With python social auth, when a user is logged in when he clicks 'Login with Facebook' or similar. The request.user is not the newly logged in facebook user but the old logged in user. log in with email test1@gmail.com log in with facebook email test-facebook@gmail.com Logged in user (request.user) is still test1@gmail.com Is this intended behavior? Is there a way to fix this or should I not present log-in unless he's not logged out? -
Django ORM - Get Max group by
I have two models. Datacenter class Datacenter(models.Model): """ Datacenter """ uuid = models.UUIDField(verbose_name=_('UUID'), unique=True, default=uuid.uuid1, editable=False) name = models.CharField(_('name'), max_length=80, db_index=True) price_per_gigabyte = models.DecimalField(_('price per gigabyte'), max_digits=36, decimal_places=18, default=0, db_index=True) class Meta: verbose_name = _('datacenter') verbose_name_plural = _('datacenters') ordering = ['name'] def __str__(self): return f'{self.name} / ${self.price_per_gigabyte:.2f} per GB' Server class Server(models.Model): """ Server """ uuid = models.UUIDField(verbose_name=_('UUID'), unique=True, default=uuid.uuid1, editable=False) hostname = models.CharField(_('hostname'), max_length=253, db_index=True) datacenter = models.ForeignKey(Datacenter, models.PROTECT, related_name="servers", related_query_name="server", verbose_name=_('datacenter')) useful_storage_capacity = models.PositiveSmallIntegerField(_('useful storage capacity'), default=0, db_index=True) class Meta: verbose_name = _('server') verbose_name_plural = _('servers') ordering = ['hostname'] def __str__(self): return self.hostname Datacenter can have many servers. I need to get datacenter's most free space server (just one). Here is what have at the moment: servers = Server.objects.all() \ .annotate(free=F('useful_storage_capacity') - Coalesce(Sum('storage__space_used_latest_copy'), V(0)) - Coalesce(Sum('storage__space_used_repository'), V(0)) - Coalesce(Sum('storage__space_used_other'), V(0))) \ .filter(free__gte=space_prepaid) \ .order_by('-free') I annotate field 'free' which contains server free space. I need to group it by datacenter somehow and get max value of free. So at end i get one and the most free server from every datacenter. Could not find any examples how to do it the right way. Whats the solution? Thanks! -
Codes after the filename but before the file exetension in the EdX framework?
I'm trying to make some modifications to a default template by changing some images and CSS files but I'm having some issues with the file paths/names for the assets I'm using. So a path name generated would look like "/static/images/favicon.c074c912999f.ico" for an icon located at "/static/images/favicon.ico" but just that without the "c074c912999f" won't work. How would I go about inserting assets into this page and where does this ID come from? -
Django error : communication failure with the server
I am beginner in django and i want to create a web page that enable the user to edit in the mysql database model and add to it and i have created it's views and models but when i submit the new data the browser gives me error : communication failure with the server. view.py from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext from survey.models import * from user_management.models import Candidate from django.contrib.auth.decorators import login_required from django import forms import settings from emailtemplates import models from email_sender.models import * from report.pdf import DrawarmPDF,send_pdf_in_email from decorators import superuser_required from django.forms.models import ModelForm class EmailTemplateForm(forms.ModelForm): class Meta: model = EmailTemplate exclude = ('body_text','subject','from_email','reply_to_email','body_text','body_html') def __init__(self, *args, **kwargs): super(ModelForm, self).__init__(*args, **kwargs) @login_required @superuser_required() def home(request): template_name='pdf' try: template = EmailTemplate.objects.get(template_name=template_name) except EmailTemplate.DoesNotExist: template=EmailTemplate(template_name=template_name) if request.method == 'POST': form = EmailTemplateForm(request.POST, instance=template) if form.is_valid(): form.save() message = 'Your %s has been updated successfully.' % template_name else: form = EmailTemplateForm(instance=template) query_results = EmailTemplate.objects.all() return render_to_response('emailtemplates/emailtemplates.html', {"query_results":query_results}, context_instance=RequestContext(request)) html page {% for item in query_results %} <tr > <td><div class="usercheckbox"></div></td> <td class="firstname"><div class="editabletext">{{ item.template_name }}</div></td> <td> <a class="edit"></a> <a class="update" title="Update"></a> <a class="cancel" title="Cancel"></a> </td> </tr> {% endfor %} models.py from django.db … -
null value in column "logo_url" violates not-null constraint in django
I am trying to make an app that searches the logo of a website and gets the link of the image. Unfortunately, it gives me this error on some sites like "reddit.com" and the code is working fine on sites like "crossfitcut.com". Why is the problem appearing and how can I eliminate it? This is the code for the logo searcher: BAD_WEBSITE = 'bad_website' # if I eliminate this function the compiler doesn't give me an error def validate_url(value): url_validator = URLValidator() value_1_invalid = False value_2_invalid = False try: url_validator(value) except: value_1_invalid = True if not value_1_invalid: return value value_2_url = "http://" + value try: url_validator(value_2_url) except: value_2_invalid = True if value_1_invalid and value_2_invalid: raise ValidationError("Invalid URL") return value_2_url def get_logo(url): website = validate_url(url) try: result = requests.get(website, headers={ 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' }, timeout=30) except: return BAD_WEBSITE if result.status_code == 200: soup = BeautifulSoup(result.content, 'html.parser') logo = None try: for item in soup.select(re.compile('.*logo.*')): if item.name == 'img': return item['src'] else: return item.find('img')['src'] except: pass if not logo: stripped = website.strip('/') homes = ['/', 'index.php', 'index.html', 'home.html'] urls = [website] for home in homes: urls.append(stripped + '/' + home.strip('/')) urls.append(home) urls.append('/' …