Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Integration of multiple database using mongoDB with django
I have a scanerio that I want to implement the mongoDB multiple database with django so is it possible to implement the multiple database integration with django? -
Django/Python Unit Testing: Let exceptions rise
I'm debugging a unit test failure whereby an exception is raised from the guts of some libraries; many exceptions. I'm using ipdb from the commandline to debug it. when running ./manage.py test path.to.test and the exception happens, the test runner catches the exception, prints a stack trace and marks the test failed or whatever. I get why this is useful, rather than letting the exception rise. In my case, I want it to rise so ipdb catches it and lands me in a nice position to move up/down frames and debug the issues. I don't want to keep wrapping tests in try or putting ipdb.set_trace() calls where the exceptions are thrown. It is a pain and it is slowing down debugging. Ordinarily this isn't an issue, but today it is. Q: Can I stop the test runner catching the exception so ipdb catches it instead without code modifications? I feel like there should be a way to do this, as it would be very helpful when debugging, but I have missed it somewhere along the line. -
How to get multiple range queries to work in elasticsearch?
I'm trying to use multiple range queries in elasticsearch 2.4.5, but it doesn't seem to work when combined with each other. I'm building an online store which must have the ability to search and filter products, and I'm using elasticsearch to add those functionalities. The store must be able to filter products by the following fields: price, num_in_stock, and popularity. Here's how each field is store internally by elasticsearch: popularity = float (i.e. 0.0098736465783, which will be converted to percent to indicate how popular the product is) price = float (i.e. 5.890000000, which will be rounded and converted to proper price format) num_in_stock = long (i.e. 10) Here's what I know for sure: When I perform a single range query with any field individually (price, popularity, or num_in_stock), it works fine. For instance, when I filter by popularity -- let's say 0.05 (5%) - 0.75 (75%) -- it works fine. However, when I combine multiple range queries the popularity range query does not work. However the price and num_in_stock ranges do work. In the sample query below, the range price and num_in_stock works fine, but the range popularity does not work! Here's a sample query: { "query": { "query": { β¦ -
Django Template: How to display the value of Foreign Key in a values_list
models.py: class Transaction(models.Model): ''' This class will host RBC raw data. ''' account_type = models.CharField(max_length = 20) account_number = models.CharField(max_length = 20) transaction_date = models.DateField() cheque_number = models.CharField(max_length = 20, null = True, blank = True) description_1 = models.CharField(max_length = 100, null = True, blank = True) description_2 = models.CharField(max_length = 100, null = True, blank = True) cad = models.DecimalField(max_digits = 10, decimal_places = 2, blank = True, null = True) usd = models.DecimalField(max_digits = 10, decimal_places = 2, blank = True, null = True) user = models.ForeignKey(settings.AUTH_USER_MODEL, blank = True, null = True, on_delete = models.PROTECT) category = models.ForeignKey('BudgetCategory', blank = True, null = True, on_delete = models.PROTECT) # same as above comment subcategory = models.ForeignKey('BudgetSubCategory', blank = True, null = True, on_delete = models.PROTECT) # Does not delete related sub-categories if a transaction is delted. views.py: transaction_fields = ['account_type', 'account_number', 'transaction_date', 'description_1', 'description_2','cad', 'category', 'subcategory'] field_order_by = ['category', 'subcategory', 'description_1', 'transaction_date'] class AllRecordsView(ListView): template_name = 'index.html' context_object_name = 'transactions' fields = transaction_fields field_order_by = field_order_by def get_queryset(self, *args, **kwargs): transactions = Transaction.objects.all().values_list(*self.fields).order_by(*field_order_by) return transactions def get_context_data(self, **kwargs): context = super(AllRecordsView, self).get_context_data(**kwargs) column_fields = fields_to_columns(self.fields) # returns the name of columns in capitalized form and changing underscore to β¦ -
Django occupying more memory with every request
Many views of my Django app use a big model (900Mb) to compute their outputs. I want to load this model once and share it with all the views. The way I have done it was to load the model in views.py and then use the model as a global variable. with open('big_model.pkl','rb') as f: model = pickle.load(f) def view1(request): out = model.compute(request) ... def view1(request): out = model.compute(request) ... I have my Django app deployed on AWS beanstalk. If I run top on the instance running my app I see the following after 1 request: Mem: 4048016k total, 2807496k used, 1240520k free, 3660k buffers PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 11530 wsgi 20 0 2817m 1.6g 30m S 0.0 41.9 0:04.63 httpd After the second request, another process appears and 1Gb of memory got occupied. Mem: 4048016k total, 3941208k used, 106808k free, 2192k buffers PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 11530 wsgi 20 0 2817m 1.6g 29m S 0.0 41.9 0:04.63 httpd 11532 wsgi 20 0 2817m 1.6g 29m S 0.0 41.9 0:04.32 httpd This doesn't happen in my local machine. Any ideas? -
How do i customise Django UserCreationForm so that I create the username from lastname and firstname, not the user entering it?
I want to modify my UserCreationForm so that when users request to sign up to my site they get given a username of last_name+'.'+first_name. my django forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): first_name = forms.CharField(max_length=30, required=False) last_name = forms.CharField(max_length=30, required=False) email = forms.EmailField(max_length=254) class Meta: model = User fields = ('first_name', 'last_name', 'email', 'password1', 'password2', ) exclude = ['username', ] So I have excluded the username from the actual form: <h2>Sign up</h2> <form method="post"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field }} {% if field.help_text %} <small style="color: grey">{{ field.help_text }}</small> {% endif %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <button type="submit">Sign up</button> </form> and in my views.py: def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) I have tried putting in form.save() here and then trying to get cleaned_data first_name.last_name = username, but it does not work if form.is_valid(): form.save() first_name = form.cleaned_data.get('first_name') last_name = form.cleaned_data.get('last_name') raw_password = form.cleaned_data.get('password1') #username = form.cleaned_data.get('username') username = firstname+'.'+lastname user = authenticate(username=username, password=raw_password) user.is_active = False user.save() return render(request, 'registration/signedup.html', {'user': user}) else: return β¦ -
Django form custom field
If we have a modelForm with some fields not directly corresponding to the model, how do we have the form process them in a custom way, while saving the rest of fields as by default? For example, we have a model for an item that supports multilingual descriptions. The models are: class Item(models.Model): name = models.ForeignKey(Localization) on_sale = models.BooleanField(default=False) class Localization(models.Model): de = models.TextField(blank=True, null=True, verbose_name='de') eng = models.TextField(blank=True, null=True, verbose_name='eng') The form to add/edit an Item looks like that: class ItemForm(forms.ModelForm): id = forms.CharField(widget=forms.HiddenInput(), max_length=128, label='') name_eng = forms.CharField(widget=forms.TextInput(attrs={'style': 'width:200px;'}), label='eng') name_de = forms.CharField(widget=forms.TextInput(attrs={'style': 'width:200px;'}), label='de') on_sale = forms.CharField(widget=forms.CheckboxInput(), label='on_sale', ) class Meta: model = Item fields = ('id', 'on_sale',) Now what saving this form should do, is for a new Item - create Localization object with the two name fields, then create an Item object with on_sale field, linked to Localization object. For an existing Item - edit the corresponding Localization object and then on_sale field of the Item itself. I did the task with a separate function, that processes the custom fields from the request separately, but having it all done by the form's save() method looks better. Or am I wrong? PS I'm sorry to be β¦ -
AttributeError 'WSGIRequest' object has no attribute 'recaptcha_is_valid'?
I wanted to install CAPTCHA to avoid spam, and used it through decorators and added all the code there, and that's the problem! If someone can help, I will be happy, thank you all! > 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 104, in login_view > if form.is_valid() and request.recaptcha_is_valid: AttributeError: 'WSGIRequest' object has no attribute 'recaptcha_is_valid' > [12/Jul/2017 19:48:06] "POST /accounts/login/ HTTP/1.1" 500 68761 > Internal Server Error: /accounts/login/ 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 104, in login_view > if form.is_valid() and request.recaptcha_is_valid: AttributeError: 'WSGIRequest' object has no attribute 'recaptcha_is_valid' there is decorators.py from functools import wraps from django.conf import settings from django.contrib import messages import requests def check_recaptcha(view_func): @wraps(view_func) def _wrapped_view(request, *args, **kwargs): request.recaptcha_is_valid = None if request.method β¦ -
when I use requestcontext it takes errors
enter image description here enter image description here Here are my view.py and the errors,Iam new of django,I hope,you can solve my problem very 3Q -
Django Aggregate Max doesn't give correct max for CharField
I have this query to give me the next available key from the DB. It works just fine until it get to 10, where it will say that 10 is available when it's not max_var = ShortUrl.objects.filter(is_custom=False).aggregate(max=Cast(Coalesce(Max('key'), 0),BigIntegerField()))['max'] + 1 The collumn is a CharField. Any tips on how to fix this? -
bring forloop counter as input value Django
I have (add button) when i click on it adds input field and remove button for this input field on each click on it . on the 1st time i want to check the max_fields max 10 times ,on update i want to check the length of the list and add as ex the data in input field 4 in and 4 input field so i want on each click add input field 6 times only . <label><h4>Delivery Number *</h4></label> <div class="input_fields_wrap"> <div class ="delivery-num-container"> <button class="add_field_button btn btn-info btn-sm">Add More Numbers</button> </div> {% if not admissions.delivery_numbers|length %} <input type="text" id="delivery_num" class="form-control delivery-num-input" required pattern="[0-9]+" placeholder="ex(1524587....)"/> {% else %} {% for delivery_number in admissions.delivery_numbers %} <div> <input type="text" id="delivery_num" value="{{delivery_number}}" class="form-control delivery_number_plus delivery-num-input" required pattern="[0-9]+"/> {% if forloop.counter != 1 %} <a href='#' class='remove_field btn btn-sm btn-danger'>Remove</a> {% endif %} </div> {% endfor %} {% endif %} </div> <label><h4>Notes</h4></label> <input class="form-control" value="{{admissions.total_notes}}" name="notes"> <input type="hidden" name="delivery_numbers" id="delivery_numbers" value="" class="form-control delivery-num-input"/> </div> js code var max_fields = 10; //maximum input boxes allowed var wrapper = $(".input_fields_wrap"); //Fields wrapper var add_button = $(".add_field_button"); //Add button ID var x = 1; //initlal text box count $(add_button).click(function(e){ //on add input button click e.preventDefault(); if(x β¦ -
Recieve, change and return data from a Django model on a website
What i have: In my Django configuration, I create a painting model in models.py class Painting(models.Model): Number = models.CharField(max_length=128) When the right URL is called, views.py returns a HTML paged rendered with a SQL query. def index(request): painting_list = Painting.objects.order_by('id')[:5] context_dict = {'paintings':painting_list} return render(request, 'binaryQuestionApp/index.html', context=context_dict) Now, I can access the Number fields in my HTML like so: <div> {% if paintings %} <ul> {% for painting in paintings %} <li> {{ painting.Number }} </li> {% endfor %} </ul> {% endif %} </div> What i want: Next, I wish to be able to change the values on the website. Something like this {{ painting.Number = 1}} // set the value to 1 {{ painting.Number += 1}} // or maybe take the current value and increment Next, I would want to send the newly set values back to Django to update the Painings, probably with a POST request. Question: What is the best way to get the desired behavior? -
Django - many to many relationships not saving
I'm creating an app for an educational school. The school has a RegularSchoolClass class (inherits from a base SchoolClass class) and also has a LessonSchedule class that tracks the schedule of a class. In particular, the SchoolClass (base class) has a many-to-many relationship with LessonSchedule. In particular, a SchoolClass object should have 48 lesson schedules (e.g. week 0, week 1, week 2; 48 lessons in a year). At the same time, a particular lesson schedule could be shared by multiple SchoolClass objects, hence I chose a many-to-many relationship. I wrote some logic that whenever a user changes the day of a class in the admin console, it should automatically change all the LessonScheules linked to the class. For instance, if a class was originally on a tuesday, and it switched to a wednesday, then all the lesson schedules should be switched accordingly. What's weird is that this doesn't show up in the admin console - it defaults to 0 lesson schedule, even after I save. But in the console, self.lesson_schedule.all().count() shows 48. Wondering if someone could guide me to the right answer? I checked (Saving Many To Many data via a modelform in Django) and my case seems to be β¦ -
Django production static files 404
I have following in settings.py STATICFILES_DIRS = [ ( os.path.join('static'), ) ] STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = '/home/user/webapps/fooder/static' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media_cdn') in html when viewing source I have <link rel="stylesheet" type="text/css" href="/static/admin/css/base.css"> but if I try to open this url I get 404 -
Calculating the difference between the output of two class objects
I have created two class objects that retrieve information from a database and store them in pandas in order for me to use the data science libraries. They both return values that I display in a Django template. I want to create a third value that is just the calculated difference of the first two and also display that in the Django template. First class object: class IntDailyGoals (object): def __init__(self, begin_date, end_date, store=None): self.begin_date = begin_date self.end_date = end_date self.store = store self.int_daily_numbers = pd.DataFrame(list(gapayment.objects.values('Trans_Store', 'Fee_Pd', 'Trans_date'))) self.int_daily_numbers['Fee_Pd'] = pd.to_numeric(self.int_daily_numbers['Fee_Pd']) self.int_daily_numbers['Trans_date'] = pd.to_datetime(self.int_daily_numbers['Trans_date']) self.sum_int_daily_numbers = np.sum(self.int_daily_numbers[(self.int_daily_numbers['Trans_date'] >=self.begin_date) & (self.int_daily_numbers['Trans_date'] <= self.end_date) & (self.int_daily_numbers['Trans_Store'] == self.store.store_number)]) def get_sum_int_daily_numbers(self): sum_intdailynumbers = self.sum_int_daily_numbers['Fee_Pd'] sum_intdailynumbers = round(sum_intdailynumbers.astype(float), 3) return sum_intdailynumbers def __str__(self): return self.get_sum_int_daily_numbers() Second Class Object: class IntDailyGoals (object): def __init__(self, begin_date, end_date, store=None): self.begin_date = begin_date self.end_date = end_date self.store = store #print(self.begin_date, self.end_date, self.store.store_number) self.int_mnth_goal = pd.DataFrame(list(StoreGoalsInput.objects.values('store_number', 'interest', 'date'))) self.int_mnth_goal['interest'] = pd.to_numeric(self.int_mnth_goal['interest']) self.int_mnth_goal['date'] = pd.to_datetime(self.int_mnth_goal['date']) self.mnth_goal_int =self.int_mnth_goal[(self.int_mnth_goal['date'] >= self.begin_date) & (self.int_mnth_goal['date'] <= self.end_date) & (self.int_mnth_goal['store_number'] == self.store.store_number)] self.mnth_goal_int= self.mnth_goal_int['interest'] self.tot_workingdays = np.busday_count(np.datetime64(self.begin_date), np.datetime64(self.end_date), weekmask='Mon Tue Wed Thu Fri Sat') self.div_intmnthgoal_workingdays = round(np.divide(self.mnth_goal_int, self.tot_workingdays),2) def get_div_goalsint_wdays(self): div_goalsint_wdays = self.div_intmnthgoal_workingdays.tolist()[0] return div_goalsint_wdays def __str__(self): return self.get_div_goalsint_wdays() I believe I need to make β¦ -
How do i create a table in django database
While modifying models.py we write different classes and these classes have their own database. What should i do in order to create a table showing relationship between these different models. Click the image to see the django table. Something on the lines like this. A table having all the relations ,here 'title' is of class Model1 and 'url' and 'category' are of class Model2 -
Django contact form on homepage
I need to embed a contact form at the bottom of my homepage, which is a single page application. I followed several tutorials on how to create my own contact form on another page (e.g., myportfolio.com/contact) which were successful. Unfortunately I haven't been able to adapt those results or find other tutorials on how to make that contact form visible and functional on the same page all of my other model data is displayed (e.g., myportfolio.com). I followed this tutorial: https://atsoftware.de/2015/02/django-contact-form-full-tutorial-custom-example-in-django-1-7. I've only created one application. I feel like this should be a very common thing to want to do, which makes me think I'm overlooking something glaringly obvious. -
Django with Postgresql on Heroku - Could not translate host name "db" to address: Name or service not known
I deployed on Heroku my project in Docker with Angular 4 frontend, Django backend and Postgresql database. At this moment my files look as shown below. When I open app I get error: 2017-07-11T19:51:14.485577+00:00 app[web.1]: self.connect() 2017-07-11T19:51:14.485577+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 94, in __exit__ 2017-07-11T19:51:14.485578+00:00 app[web.1]: six.reraise(dj_exc_type, dj_exc_value, traceback) 2017-07-11T19:51:14.485578+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise 2017-07-11T19:51:14.485578+00:00 app[web.1]: raise value.with_traceback(tb) 2017-07-11T19:51:14.485579+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection 2017-07-11T19:51:14.485579+00:00 app[web.1]: self.connect() 2017-07-11T19:51:14.485579+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 189, in connect 2017-07-11T19:51:14.485580+00:00 app[web.1]: self.connection = self.get_new_connection(conn_params) 2017-07-11T19:51:14.485580+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 176, in get_new_connection 2017-07-11T19:51:14.485580+00:00 app[web.1]: connection = Database.connect(**conn_params) 2017-07-11T19:51:14.485581+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py", line 130, in connect 2017-07-11T19:51:14.485581+00:00 app[web.1]: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) 2017-07-11T19:51:14.485582+00:00 app[web.1]: django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known Locally everything seems to be working properly. I use docker exec -ti name /bin/bash then python {path}\manage.py migrate and database is added. Maybe there is a problem with my database migration on Heroku? Any suggestions? Procfile: web: sh -c 'cd PROJECT/backend/project && gunicorn project.wsgi --log-file -' Project tree: DockerProject βββ Dockerfile βββ Procfile βββ init.sql βββ requirements.txt βββ docker-compose.yml βββ PROJECT βββ frontend βββ all files βββ backend βββ project βββ β¦ -
Run subproccess without blocking and get the final output
I have a Django app that should allow to run different process from different users without blocking. So If I try to do this: output = subprocess.Popen(command, close_fds=True).communicate()[0] The system gets block because of communicate(). My question is: is there anyway to run a subprocess in a different thread so it don't block the main thread? The idea is: Main thread creates a new thread Launch a process in that thread That thread blocks until that process finish to get the output and write it to a file. I don't need to read line by line as I have seen in other questions, just get all at the end. Thanks in advance. -
How to integrate the multiple database with django
I have a query about multiple database using mongoDB with django is it possible to use multiple database in mongoDB with django and how to integrate the multiple database with django? -
How can I create an instance of one model as soon as an instance of a different model is created?
I have two linked models: class MyUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=24, unique=True) class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) Users of my site register and create an account first (MyUser), should be able to view their not-yet-created/blank profile (Profile), and then have the option of editing/saving their blank profile from within the profile_detail page. My ProfileDetailView: class ProfileDetailView(DetailView): template_name = 'profile/profile_detail.html' def get_object(self, *args, **kwargs): user_profile = self.kwargs.get('username') obj = get_object_or_404(Profile, user__username=user_profile) return obj They cannot access their own profile page after registration due to their profile instance not having been created. To allow them to go to their profile and view the blank profile, then update their ProfileUpdateForm from there, I've attempted signaling: def user_post_save_receiver(sender, instance, created, *args, **kwargs): if not instance.profile.exists(): Profile.objects.create(user=instance) as well as def user_post_save_receiver(sender, instance, created, *args, **kwargs): Profile.objects.get_or_create(user=instance) The first of the two returns RelatedObjectDoesNotExist: MyUser has no profile. The second works, but Django docs do not recommend using get_or_create there. What is a better way to achieve the desired result? Also, is a class ProfileCreateView(CreateView): even necessary in this case when I have class ProfileUpdateView(UpdateView): form_class = ProfileUpdateForm template_name = 'profile/profile_edit.html' def get_object(self, *args, **kwargs): user_profile = self.kwargs.get('username') obj = get_object_or_404(Profile, user__username=user_profile) β¦ -
NoneType' object has no attribute 'name'
I was building wine recommendation system using k means approach in django. I made cluster module in admin and added 3 clusters manually. However, when I am trying to recommend wine to logged in user I get this error.Can you please help: AttributeError at /reviews/recommendation/ 'NoneType' object has no attribute 'name' I am getting error in line: User.objects.get(username=request.user.username).cluster_set.first().name here is the code for view.py @login_required def user_recommendation_list(request): # get request user reviewed wines user_reviews = Review.objects.filter(user_name=request.user.username).prefetch_related('wine') user_reviews_wine_ids = set(map(lambda x: x.wine.id, user_reviews)) # get request user cluster name (just the first one righ now) try: user_cluster_name = \ User.objects.get(username=request.user.username).cluster_set.first().name except: # if no cluster assigned for a user, update clusters update_clusters() user_cluster_name = \ User.objects.get(username=request.user.username).cluster_set.first().name # get usernames for other memebers of the cluster user_cluster_other_members = \ Cluster.objects.get(name=user_cluster_name).users \ .exclude(username=request.user.username).all() other_members_usernames = set(map(lambda x: x.username, user_cluster_other_members)) # get reviews by those users, excluding wines reviewed by the request user other_users_reviews = \ Review.objects.filter(user_name__in=other_members_usernames) \ .exclude(wine__id__in=user_reviews_wine_ids) other_users_reviews_wine_ids = set(map(lambda x: x.wine.id, other_users_reviews)) # then get a wine list including the previous IDs, order by rating wine_list = sorted( list(Wine.objects.filter(id__in=other_users_reviews_wine_ids)), key=lambda x: x.average_rating, reverse=True ) return render( request, 'reviews/user_recommendation_list.html', {'username': request.user.username,'wine_list': wine_list} ) and here is the code for suggestions.py from .models β¦ -
Can not access to /admin django API rest with wsgi and Apache
I am using django version 1.11 on a centos 7 OS. I deployed my rest api with apache and wsgi. Most of my non-auth apis run well in deployment phase, but when i tried to access to my admin page with the superuser, but i have an error 500 with apache and wsgi but not with the local runserver. Could someone help me with this ? Thanks I have printed my error code below [Wed Jul 12 11:12:33.433901 2017] [:error] [pid 427699] ]> [Wed Jul 12 13:27:13.714040 2017] [mpm_prefork:notice] [pid 427698] AH00170: caught SIGWINCH, shutting down gracefully [Wed Jul 12 13:27:14.970278 2017] [suexec:notice] [pid 431116] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [Wed Jul 12 13:27:14.993828 2017] [auth_digest:notice] [pid 431116] AH01757: generating secret for digest authentication ... [Wed Jul 12 13:27:14.994874 2017] [lbmethod_heartbeat:notice] [pid 431116] AH02282: No slotmem from mod_heartmonitor [Wed Jul 12 13:27:14.999724 2017] [mpm_prefork:notice] [pid 431116] AH00163: Apache/2.4.6 (CentOS) mod_wsgi/3.4 Python/2.7.5 configured -- resuming normal operations [Wed Jul 12 13:27:14.999782 2017] [core:notice] [pid 431116] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND' -
view of django 1.8 using mongodb
I am using mongoengine with Django 1.8 and my project needs to connect to one instances of MongoDB while another with sql.so first i decided to do all work related to mongodb database. i want to display 'battery_status' and 'name' column or document in my table 'location' which is in mongodb database 'pom'. but it is not displaying any data .i don't know why My display screen is empty.plz help out view.py import hashlib import json import sys import datetime from django.core.cache import cache from django.views.generic import View from django.shortcuts import render from django_datatables_view.base_datatable_view import BaseDatatableView from django.http import HttpResponse, HttpResponseNotFound from django.shortcuts import get_object_or_404, render from django.template import Context, RequestContext,loader from django.utils import timezone from django.utils.crypto import get_random_string from django.template.loader import get_template from admin_app.models import location class Travel_Details(View): try: def index(request): users= location.objects.all() template = loader.get_template('Travel/Travel_list.html') context = RequestContext(request,{'users': users} ) return HttpResponse(template,render(context)) except Exception as general_exception: print general_exceptionf print sys.exc_traceback.tb_lineno -
Django app on heroku: content wont appear in mobile browser
After deploying my django application on heroku i had a weird experience why the application content is fine and working on desktop browsers however in any mobile devices such as android and ios browsers the content wont display. Is there any setup for mobile browser?