Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django channels on aws : daphne and workers running but websocket taret unhealthy
I have been following this article - https://blog.mangoforbreakfast.com/2017/02/13/django-channels-on-aws-elastic-beanstalk-using-an-alb/ to get my django-channels app working on aws..but only non-websockets request are getting handled. my channel layer setting is : CHANNEL_LAYERS = { "default": { "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')], }, "ROUTING": "malang.routing.channel_routing", }, } I have two target group as mentioned in the article. One forwarding path / to port 80 and /ws/* to 5000. My supervisord.conf is - [program:Daphne] environment=PATH="/opt/python/run/venv/bin" command=/opt/python/run/venv/bin/daphne -b 0.0.0.0 -p 5000 malang.asgi:channel_layer directory=/opt/python/current/app autostart=true autorestart=true redirect_stderr=true user=root stdout_logfile=/tmp/daphne.out.log [program:Worker] environment=PATH="/opt/python/run/venv/bin" command= /opt/python/run/venv/bin/python manage.py runworker directory=/opt/python/current/app process_name=%(program_name)s_%(process_num)02d numprocs=4 autostart=true autorestart=true redirect_stderr=true stdout_logfile=/tmp/workers.out.log When I check the result of supervisorctl status on aws logs it shows them running fine. But still I get 404 response for ws. Please help and let me know if you want some more info.. -
how to fix, NameError at?
When i finished enter my username and password, this error is blow up, he write that variables password is not defined, how to fix? Thank you all for your help, I will look forward to your advice! full traceback Traceback (most recent call last): File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\newstudio\accounts\views.py", line 40, in login_view if form.is_valid(): File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\forms\forms.py", line 183, in is_valid return self.is_bound and not self.errors File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\forms\forms.py", line 175, in errors self.full_clean() File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\forms\forms.py", line 385, in full_clean self._clean_form() File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\lib\site-packages\django\forms\forms.py", line 412, in _clean_form cleaned_data = self.clean() File "C:\Users\P.A.N.D.E.M.I.C\Desktop\td11\newstudio\accounts\forms.py", line 25, in clean if user.check_password(password): NameError: name 'password' is not defined forms.py class UserLogInForm(forms.Form): username = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Username"), error_messages={ 'invalid': _("This value must contain only letters, numbers and underscores.") }) password = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password")) def clean_username(self): user = User.objects.get(username__iexact=self.cleaned_data['username']) if user: return self.cleaned_data['username'] else: raise forms.ValidationError('This user does not exist!') def clean(self): username = self.cleaned_data['username'] user = User.objects.filter(username=username) if user.count() == 1: user = user.first() if user.check_password(password): raise forms.ValidationError("Incorrect password!") return self.cleaned_data else: raise forms.ValidationError('This user does … -
TypeError: using html <select>, model.object.create error: "coercing to Unicode: need string or buffer, tuple found"
I don't understand how to handle the "< select >" options from my html page, when inserting to SQL Lite, I get this error... "coercing to Unicode: need string or buffer, tuple found" I have tried converting the postdata['rating'] to str(postdata['rating']). I don't really understand what the select is passing in. I printed the return and you can see it at the top of my error log "********** Rating value is: 5 **********". So.... any ideas how to handle this select object TypeError? HTML <!DOCTYPE html> <html lang='en'> <head> <title>Add Bikes</title> <meta description='Add a Bike Page for Bike Reviewer Project'> <meta charset='utf-8'/> </head> <body> <div id='wrapper'> <h3> welcome .. </h3> <h3>Add your Bike and Review it here.</h3> <form action="/bikes/insertreview" method="POST"> {% csrf_token %} <p><label for="newmodelyear">Bike Model Year:</label> <input type="text" name="newmodelyear" placeholder="Enter Year 1950 to 2018"></p> <p><label for="make">Bike Make:</label> <select id="makeselector" name="make"> {% for each in makes %} <option value={{each.bikemake}}>{{each.bikemake}}</option> {% endfor %} </select></p> <p><label for="newmake">or create a new one:</label> <input type="text" name="newmake" placeholder="min 3 characters..."></p> <p><label for="model">Bike Model:</label> <input type="text" name="model" placeholder="min 3 characters..."></p> <p><label for="review">Review:</label> <textarea name="review" rows="5" cols="50"></textarea></p> <p>Rating: <select id="rating" name="rating"> <option value="1">1 star</option> <option value="2">2 star</option> <option value="3">3 star</option> <option value="4">4 star</option> <option value="5">5 star</option> </select></p> … -
Slight issue parsing text into html
Hmmmm, this may well be an easy one but may well be a complex one. I'm having an issue setting up an SEO friendly Twitter feed within the Django framework. Most of the heavy lifting is done as a template tag blog_tags.py file as follows: @register.inclusion_tag('blog/frame/twitter.html') def show_latest_tweets(): tweets = [] try: """The import error is here to catch any server migrations were the tweepy package not to be found in site_packages""" import tweepy except: tweets.append({'status': 'There was a problem referencing our tweets. Please inform our webmaster.', 'relative_date': 'Just now'}) raise ImportError # OAuth process, using the keys and tokens auth = tweepy.OAuthHandler(settings.EOS_TWITTER_FEED['EOS_FEED_TWITTER_KEY'], settings.EOS_TWITTER_FEED['EOS_FEED_TWITTER_SECRET']) auth.set_access_token(settings.EOS_TWITTER_FEED['EOS_FEED_TWITTER_ACCESS_TOKEN'], settings.EOS_TWITTER_FEED['EOS_FEED_TWITTER_ACCESS_TOKEN_SECRET']) # Creation of the actual interface, using authentication api = tweepy.API(auth) user = 'FFXVEN' avatar_url = api.get_user(screen_name='@'+user).profile_image_url i = 0 for tweet in tweepy.Cursor(api.user_timeline, screen_name='@'+user).items(): if 'RT' not in tweet.text: if i <= 4: status = tweet.text hashtags = [word for word in status.split() if word[0] == "#"] #Find hashtags in tweet and create a string to contain <a href="https://twitter.com/search?q=" + hashtag>#hashtag</a> for hashtag in hashtags: if hashtag.endswith((',',';','.')): hashtag = hashtag[:-1] status = status.replace(hashtag, '<a href="https://twitter.com/search?q={}">{}</a>'.format(hashtag[1:], hashtag)) relative_date = tweet.created_at tweets.append({'user': user, 'avatar_url': avatar_url, 'status': html.unescape(status), 'relative_date': relative_date}) i += 1 else: break else: … -
django admin many-to-many with intermediate model add new
I have the following models (simplified): class Concert(models.Model): title = models.CharField(max_length=50) date = models.DateField() songs = models.ManyToManyField(Song, through='RunOrder', related_name='run_order', blank=True) class Song(models.Model): title = models.CharField(max_length=50) class RunOrder(models.Model): concert = models.ForeignKey(Concert, on_delete=models.CASCADE) song = models.ForeignKey(Song, on_delete=models.CASCADE) act_no = models.SmallIntegerField() scene_no = models.SmallIntegerField() Basically, songs can be in multiple concerts, concerts have multiple songs. While creating a new concert in the admin view, I would like to be able to add new songs. Here's what I have: class ConcertAdmin(admin.ModelAdmin): ... inlines = [SongInline] class SongInline(admin.TabularInline): model = RunOrder show_change_link = True extra = 1 But this only lets me select from existing songs. In order to add a new song, I have to use the Song admin interface. When I tried to use Song as the model for SongInline, I got a has no ForeignKey error. Is there a way I can streamline/inline the process of adding new Songs to a Concert? -
How to send email with Django Newsletter using Zoho mail?
I'm trying to send email with django-newsletter using Zoho Mail, but there is not way to make it works. You can say that is duplicated because of Send email through Zoho SMTP but is not. I'm not asking how to send with Django. I want to send using Django Newsletter. I already have tried the options on the link above, but I want a way to make it work with Django Newsletter, with just with Django. Thanks in advance. -
NoReverseMatch at /myname even url is named?
I am getting Reverse for 'myname' not found. 'myname' is not a valid view function or pattern name. But 'myname' is defined in, url(r'^myname$', views.myname, name='myname'), What is wrong? -
Django ValidationError showing only one error
I am trying to make a Django login screen that shows the errors when the user for exemple doesn't type the right password. But the only error i am recieving is the "This user doesn't exist!" how can i make the other error massages to show up? What is the problem with my code? forms.py class UserLogInForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput) def clean(self, *args, **kwargs): username = self.cleaned_data.get("username") password = self.cleaned_data.get("password") #if username and password: # user = get_user_model() user = authenticate(username=username, password= password) # user = authenticate(username=username) if not user: raise forms.ValidationError("This user does not exist!") if not user.check_password(password): raise forms.ValidationError("Incorrect password!") if not user.is_active: raise forms.ValidationError("This user is no longer active.") return super(UserLogInForm, self).clean(*args, **kwargs) views.py def login_view(request): title = "Login" form = UserLogInForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get("password") user = authenticate(username=username, password=password) login(request, user) return redirect('/') return render(request, "form.html", {"form": form, "title": title, 'errors': form.non_field_errors()}) form.html <form method='POST' action='' enctype="multipart/form-data">{% csrf_token %} {{ form.non_field_errors }} <table align="center"> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> <div id="wrapper"> <button id="button" type="submit">Login</button> </div> </form> -
selenium without display missing content
I am using django 1.10, selenium 3.4 and python 3.6. My PC is used to test if my code is accurate. Using Chrome webdriver The production service is on Amazon EC2 Ubuntu instance. Using Chrome webdriver as well but without display like below. display = Display(visible=0, size=(1024, 768)) display.start() I was using selenium to find a certain information that resides in the html like below code. <div id="myid"> <table> <tbody> <tr>...</tr> <tr> <td>...</td> <td ...> <div ...> <div ...> <table ...> <tbody> <tr>...</tr> <tr ...> <td ...></td> <td ...></td> <td ...></td> <td ...></td> <td ...></td> <td ...></td> <td ...>This is what I searching</td> <td ...></td> <td ...></td> .......... Sadly, there's not much id or unique class that I can use on searching. So, I'm using xpath as this line. driver.find_element_by_xpath("//div[@id='treegrid_QUICKSEARCH_TABLE']/table/tbody/tr[2]/td[2]/div/div[1]/table/tbody/tr[2]/td[7]").text I can find the element I want on my PC with browser. But not on my EC2 instance without display. When I check the upper tag of it. driver.find_element_by_xpath("//div[@id='treegrid_QUICKSEARCH_TABLE']/table/tbody/tr[2]/td[2]/div/div[1]/table/tbody/tr[2]").text I found that selenium is indeed not getting that text I'm searching. I even tried increasing the size of Display to (1920,1920) Once again, the code works just fine on my PC with browser. Can someone tell me what's the problem? -
Using Heroku buildpacks locally
I scoured Heroku's documentation, but wasn't able to find an answer. Is it possible to use a Heroku buildpack locally? I'd like parity between local and prod environments. I'm using Django, and I'd like to use this buildpack. -
deploy django app: uwsgi and Nginx in separate docker containers
Please, i am having an issue with connecting nginx to uwsgi which are on different docker containers. Below are the configuration. I have a docker network configured with IP addresses assigned to the containers and port 8030 exposed for connection between containers/uwsgi while 8040 for connecting to the nginx e.g 127.0.0.1:8040. However, I can only see the default page of nginx. # nginx.conf upstream tangent_django { server 172.18.0.3:8030; server 172.18.0.4:8030; } server { listen 80; # the domain name it will serve for server_name 127.0.0.1; charset utf-8; #Max upload size client_max_body_size 75M; location /media { alias /datavolume/tangent_leave_app_solution/media; } location /static { alias /datavolume/tangent_leave_app_solution/staticfiles; } location / { include /etc/nginx/uwsgi_params; } } This is my uwsgi configuration on a different server (docker container) with ip address 172.18.0.3 also having port 8030 exposed. [uwsgi] plugins = python master = true processes = 4 socket = 0.0.0.0:8030 chmod-socket = 777 # the base directory chdir = /code/tangent_leave_app_solution module =Hr.wsgi:application home = /root/.virtualenvs/python_env_11/ max-requests = 5000 vacuum = true daemonize = /var/log/uwsgi/tangent.log -
Django display values of a choice
If I take for example the manual of Django : from django import forms FAVORITE_COLORS_CHOICES = ( ('blue', 'Blue'), ('green', 'Green'), ('black', 'Black'), ) class SimpleForm(forms.Form): favorite_colors = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=FAVORITE_COLORS_CHOICES, ) In my template, I just want to display the value of the checkbox. Something like this : {% for item in favorite_colors %} {{value_of_checkbox}} {{item}} {% endfor %} I want {{value_of_checkbox}} return "blue", "green" and "black" And so the {{item}} return "Blue", "Green" and "Black" Any way to do this ? Thanks -
How do you create links using slugfield in Django generic listview class?
How to you create links (i.e. href) using SlugField for the output of Django's ListView generic class? Right now I can list all persons in the database using the code below but I want links using slug when clicked will show the person's description. models.py class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) slug = models.SlugField(max_length=50) description = models.TextField() views.py class PersonList(ListView): model = Person person_list.html <ul> {% for person in object_list %} <li>{{ person.first_name }}&nbsp{{ person.last_name }}</li> {% endfor %} </ul> -
Should I use JSONField or FileField to store JSON datas?
I am wondering how I should store my JSON datas to have the best performances and scalability. I have two options : The first one would be to use JSONField, which will probably provides me an advantage in simplicity when it comes on performances and handling the datas since I don't have to get them out of a file each time. My second option would be to store my JSON datas in FileFields as json files. This seems the best option since the huge quantity of JSON wouldn't be stored in a DataBase (only the location of the file). In my opinion it's the best option for scalability but maybe not for user performances since the file has to be read each time before displaying them in the template. I would like to know if I am thinking reasonably, what's the best way between to store JSON datas for them to be reusable as fast as possible without making it complicated to the database & scalability ? -
Can I conbine a webpage created by solr and a django website?
I have i website created with Django, and a product catalog made with solr. Can I combine them in a way that I will have one website? -
Django Tic Tac Toe Game
I have a separate Tic Tac Toe game for Player vs AI. It runs as expected as an independent script. I am trying to integrate that with my new Django project. I have started to design a view. def aitictactoe(request): context = RequestContext(request) move = None if request.method == 'GET': board = request.GET['board'] move = request.GET['move'] playing = request.GET['playing'] difficulty = request.GET['difficulty'] gameID = request.GET['game-id'] if playing = True: AITicTacToe.get_object_or_create(pk=gameID) I am thinking to implement it using AJAX and send/receive responses in JSON. I am unable to move forward. I need suggestions on how do I integrate and work on it. My Tic-Tac-Toe game is located here - https://github.com/khizirsiddiqui/tic-tac-toe. Definitely I will have to change the functions (keeping the algorithms) Please also suggest me on using AJAX/JSON or using something like express/socket.io. -
Docker Cloud autotest cant find service
I am currently trying to dockerize one of my Django API projects. It uses postgres as the database. I am using Docker Cloud as a CI so that I can build, lint and run tests. I started with the following DockerFile # Start with a python 3.6 image FROM python:3.6 ENV PYTHONUNBUFFERED 1 ENV POSTGRES_USER postgres ENV POSTGRES_PASSWORD xxx ENV DB_HOST db RUN mkdir /code ADD . /code/ WORKDIR /code RUN pip install -r requirements.txt RUN pylint **/*.py # First tried running tests from here. RUN python3 src/manage.py test But this DockerFile always fails as Django cant connect to any database when running the unit tests and justs fails with the following error as no postgres instance is running in this Dockerfile django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known Then I discovered something called "Autotest" in Docker Cloud that allows you to use a docker-compose.text.yml file to describe a stack and then run some commands with each build. This seemed like what I needed to run the tests, as it would allow me to build my Django image, reference an already existing postgres image and run the tests. I removed the RUN python3 … -
Reverse for 'password_reset_confirm'
Django==1.11.2 django-registration-redux==1.6 When I'm trying to reset password (http://localhost:8000/accounts/password/reset/), I occur at a page with headline Django administration, and breadcrumbs below: Home › Password reset. So, this is a part of Django functionality. This may be important, though, I don't know how. But anyway, this is not the functionality of django-registration-redux. I input an email. And get this: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. In django-registration-redux another name is used. Namely auth_password_reset_confirm. Well, could you give me a kick here? My settings are below: settings.py INCLUDE_REGISTER_URL = True INCLUDE_AUTH_URLS = True urls.py urlpatterns = [ url(r'^accounts/', include('registration.backends.default.urls')), } -
How to make a class diagram for a django project?
I have this Django project that contains several applications , each one contains (apps, models, forms, views, urls, tests) files. the question is what is the structure I should follow to design the class diagram, and should I include tests file to the design or not? and what are the relations among the apps. -
how can i create advanced custom search form in django admin and use django admins change list display
how can i create advanced custom search form in django admin and use django admins change list display.my advanced search form hast regiopn city provience and etc fields . admin.py: class PropertyAdmin(ModelAdmin): change_list_template = "gigaja_property/admin/property_change_list.html" list_per_page = 20 list_display_links = ('property_country_province_city',) search_fields = ('id',) list_filter = ('is_sale','is_rent','is_presales','estate_type','water') list_display_links = ('property_type',) Models.py class Property(models.Model): objects = PublicPropertyManager() title = models.CharField(_("title"), max_length = 80, help_text=_("please enter the title"),blank=True) # Country of sale property country = models.ForeignKey(Country, help_text=_("The country where the property is located in"),verbose_name=_("Country")) # Province of the property province = models.ForeignKey(Province, help_text=_("The province where the property is located in"),verbose_name=_("Province")) # City of sale property city = models.ForeignKey(City, help_text=_("The city where the property is located in"),verbose_name=_("City")) # Region of sale property region = models.ForeignKey(Region, help_text=_("The region where the property is located in"),verbose_name=_("Region")) # Address of the property address = models.CharField( _("address"), max_length = 250, help_text=_("The address where the property is located in."),blank=True,null=True) -
How to avoid "The number of GET/POST parameters exceeded" error?
I have created a custom admin page on my Django website, Where only administrators will be allowed and will be able to change objects and their attributes. The amount of objects is a lot (9000+) and on admin page there are equal amounts of input fields as objects in that model. This is the code: <form action="{% url 'Home:AdminPrices' %}" id="mainForm" method="post"> {% csrf_token %} {% for item in prices %} <ul class="row" style="width: 100%;padding: 0;background-color: white;height: 100px;display: flex;justify-content: left;white-space: nowrap;margin-bottom: 0;margin-top: 0;"> <div style="width: 33.333333333333336%;background-color: white;display: block;color: black;font-size: 0.8em;white-space: nowrap;text-align: center;font-family: 'Lato';padding-top: 25px;">{{ item.hashname }}</div> <div style="width: 33.333333333333336%;background-color: white;display: block;color: black;font-size: 1.2em;text-align: center;font-family: 'Lato';padding-top: 25px;">{{ item.sug }}</div> <div style="width: 33.333333333333336%;background-color: white;display: block;color: black;font-size: 1.2em;text-align: center;font-family: 'Lato';"><input type="number" value="{{ item.actual }}" name="prices_{{ item.actual }}" style="width: 100%;height: 100%;padding-bottom: 25px;background-color: white;border: 0;color: black;font-size: 1.2em;text-align: center;font-family: 'Lato';"></input></div> </ul> {% endfor %} <input type="submit" id="mainSubmit" style="display: none;" name="submitPrices"></input> </form> <div onclick="document.getElementById('mainForm').submit();" style="background-color: black;border-radius: 5px;position: fixed;display: block;height: 50px;width: 200px;bottom: 0;left:0;right:0;margin: 0 auto;color: white;font-size: 1.5em;text-align: center;padding-top: 12.5px;cursor: pointer;">Submit</div> Once submit button is pressed, Website crashes and prompts out this error: The number of GET/POST parameters exceeded I'm not quite sure how can i avoid it, Could i change the settings and set different limit specifically for … -
Django - Select from a list
I have a list : logo_nofav = [('codwaw.png', 'codwaw'), ('lol.png', 'lol')] In my template I can : call the first in the list with {{logo_nofav.0}} call the second with {{logo_nofav.1}} just call the second element of the second in the list with {{logo_nofav.1.1}} Now my question is, how could I just call the second element of each object. We could image {{logo_nofav.x.1}} where "x" is a variable which means anywhere on the list. I hop I was clear. Thanks -
Js Framework for good integration with backend Python/Django
I'm a backend developer in python / Django. I work in a small company, so I gave out a full-stack project. Jquery is not enough (too much code will come out).Found that i need a bunch of DRF (django-rest-framework) + Js framework. What framework would you recommend me for good integration with the backend? It is desirable a fairly popular(angular 1/2, react) -
How to parse time retrieved from Facebook Graph into 12 hour format? Django
When I pull events start times from Facebook Graph in comes in this form: 2017-09-26T18:00:00+0300 I'd like to convert it into readable format so I use this: readable_event_date = dateutil.parser.parse(event_date).strftime('%a, %b %d %Y %H:%M:%S') and it comes out like this: Tue, 26 Sep 2017 18:00:00 Which is good but it loses the offset from UTC and I'd like it in AM PM format. Thus, I would like it like this: Tue, 26 Sep 2017 9:00 PM -
Django preload Yelp API results
I am making a website for a restaurant and they want to show their Yelp reviews. I configured and can retrieve data with the Yelp API. I have to query two things in order to get what I need. All in all this means the page takes 10-15 seconds to load, and I don't want to have to query the Yelp API everytime someone wants to see the page anyway. yelp_api = YelpAPI('secretkey1', 'secretkey2') business_results = yelp_api.business_query(id='secretbuisness', location='secretplace') reviews_results = yelp_api.reviews_query(id='secretbuisness', location='secretplace') return render(request, 'reviews.html', {'reviews_results': reviews_results, 'business_results': business_results}) Is there any way to make it so I can get the Yelp API data separate from the page request and store it somewhere ready to use, maybe updating every 5-10 minutes?