Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to hide and show a particular link on a sidebar menu based on checkbox value?
Is it possible to hide and show a link/icon on a sidebar menu based on checkbox value? I have a checkbox that once enabled (value = on), the icon of that particular link on sidebar menu should be shown and once disabled (value = off) will be hidden. Hope someone could help me. Thanks! -
How send post request and get file? Python Django
One site пenerating iPXE build imagea file that I need to download by sending a request. I want to make a request for a post on the 3th site (rom-o-matic.eu), and get a file from site. Is this possible? My example is this: def requestPOST(request): values = {'wizardtype': 'standard', 'outputformatstd': 'bin/ipxe.usb', 'embed': '#!ipxe dhcp route}', 'gitrevision': 'master'} r = requests.post("https://rom-o-matic.eu/", verify=False, data={values}) return() What should this return? Thanks. -
Select Multiple values from a previously selected dropdown value in Django form
I am trying to implement the steps given in this example (https://github.com/Sidon/djfkf/) to create a Django form that allows for multiple selection of values based on a previous selection. Essentially, I have two models, one for the organism and the other for targets. Each organism can have one or more targets. I would like to select an organism, and once I've selected the organism, a drop down menu appears having all its related targets. I used opt-groups but is not giving me what I desire. Could someone kindly assist. Am new to web programming. Kindly see the attached image displaying how I'd like it to appear -
django 1.10 - custom sql inserts when user registered
I am using django 1.10 + django-registration 2.2 (HMAC activation workflow). How can I make custom sql inserts when a new user is registered? For example every user has own settings and after registration I want to insert the default settings in the sql table for this user. Later the user can change these settings. What is the common approach? Do I have to edit the django-registration 2.2 files? -
how to set 2 rows to become header in a dataframe with originally has a header?
I facing problem on how to set another 2 rows be my header In a dataframe I have one header, and now I want take my first row and second row become header:(below is my dataframecode) pvm=pd.DataFrame(pvm) How can I add header=[0,1] into above code? Or need start from the table style? tableyy = final.style.set_table_attributes('border="" clas= "dataframe table table-hover table-bordered"').set_precision(10).render() -
Django-allauth how to connect social account to existing django account
I stuck with a problem. My scenario is easy: User login with existing django's user. Go to profile page and see for example button "Connect to Google" Click on button and connect his social account to existing django's one thats no matter the same emails or not, user name and etc, I just need connect it I made a url a href="{% provider_login_url "google" process="connect" %}" class="btn btn-success">Connect a Google account</a> But when I hit on it allauth everytime create new django account and new social account and link them but doesnt link my logged in user. I tried overload adapters like: from allauth.account.adapter import DefaultAccountAdapter from allauth.socialaccount.adapter import DefaultSocialAccountAdapter from allauth.utils import get_user_model from allauth.account.adapter import get_adapter as get_account_adapter class CustomAdapter(DefaultAccountAdapter): def new_user(self, request): if request.user.is_authenticated(): return request.user user = get_user_model()() return user def save_user(self, request, user, form, commit=True): from .utils import user_username, user_email, user_field if request.user.is_authenticated(): return user data = form.cleaned_data first_name = data.get('first_name') last_name = data.get('last_name') email = data.get('email') username = data.get('username') user_email(user, email) user_username(user, username) if first_name: user_field(user, 'first_name', first_name) if last_name: user_field(user, 'last_name', last_name) if 'password1' in data: user.set_password(data["password1"]) else: user.set_unusable_password() self.populate_username(request, user) if commit: # Ability not to commit makes it easier to derive … -
Every time I launch a new project this error pops up about installing django packages
enter image description here Is there any issue with library packages. -
server side pagination with restangular and rest api
I am trying to implement infinite scroll using restangular but not sure how to proceed as I am new to restangular.Please help me if anybody has done server side infinite scrolling using restangular. -
django filter by priority
I have a status model field which contain list of priorities which are given to the contacted person, from virgin to client, the virgin been the low priority and client the high priority, now the question is how can I filter them so I can show all contacts from highest to lowest, so this is the order that I need to show them client, qualified, contacted, virgin, this is the model field status = models.CharField(max_length=10, choices=LeadContactConstants.STATUSES, default=LeadContactConstants.STATUS_PRISTINE) and choices: STATUSES = ((STATUS_PRISTINE, "Virgin"), (STATUS_CONTACTED, "Contacted"), (STATUS_QUALIFIED, "Qualified"), (STATUS_CLIENT, "Client")) -
Django, how to rename images using a new auto-numbering per foreign key?
Ok, that title is probably as vague as vague things can get, but I couldn't come up with something good. Let me explain my problem. For the explanation, I'll use books as an example, just because that's easy. So, imagine I have 2 models like this: class Book(models.Model): title = models.CharField(max_length=100) class BookImage(models.Model): book = models.ForeignKey(Book) image = models.ImageField() is_cover = models.BooleanField() Now, as you can see a book can have multiple images. I want to rename the uploaded images to [book title]-[image-id].jpg (or whatever image extension there is of course). However, I want image-id to be unique per book. If that makes sense. So if I have BookA, I want the images to be called BookA-1, BookA-2 and BookA-3 etc. And BookB starts at 1 again, BookB-1, BookB-2, BookB3 etc. Any idea how I can do this? I've been thinking about it myself, but I can't come up with a really good solution. At first I thought I could do a count on the number of images and add 1 to that, but then you would run into problems if you delete images. I also thought about just keeping track of the ids in a separate Model, but that … -
Can/should haystack be used with django to write data to the searchable database
I am considering using django with haystack to make an application. The application shows content from the searchable database and a form. The form can be used to alter or enrich the content. Consequently, I do not only want to query the database but also write data back. The SearchBackend provides a method to update the database. But is haystack a good/accepted solution for this? Or should it only be used for reading/querying/searching the database? -
HTML POST form in Django giving TypeError when submitted
I'm trying get user input from a HTML form and use that value to populate a ChartJS graph in my Django app called DisplayData which has a template called Display.html. I have the following form in my project. Display.html <div class="row"> <form method="POST"> {% csrf_token %} <input type="text" name="textfield"> <button type="submit">Submit</button> </form> </div> In my views file, I have the following code to get the data from this form: views.py class ChartData(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): display_id = request.POST.get("textfield") #get data from form display_id = int(display_id) all_entries = models.Entries.objects.all().filter(parent=display_id) #change to input from drop down or change to 2 all_id = models.Entries.objects.all().values_list('id', flat=True) all_measurables = models.Measurables.objects.all().filter(user_id=request.user.id) #change to current user all_ids = [m.id for m in all_measurables] #use this to make drop down all_times = [m.timestamp for m in all_entries] all_data = [] for m in all_entries: data = m.data json_data = json.loads(data) value = json_data['value'] all_data.append(value) data = { "labels": all_times, "default": all_data, } return Response(data) My urls are set up as follows. urls.py from .views import get_data, ChartData urlpatterns=[ url(r'^$',views.DisplayView, name='DisplayView'), url(r'^api/data/$', views.get_data, name='api-data'), url(r'^display/api/chart/data/$', views.ChartData.as_view()), url(r'^logs/', views.LogDisplay, name='Display-Logs'), ] When I go into the form in the page and type in … -
Security using Django 1.10 + AJAX without any HTML form
I make a POST request via AJAX without HTML form. Are there any security issues? Why is there no csrf error? Because I do not send any csrf data and csrf is enabled in django? toggle-status.js jQuery(document).ready(function($) { $("#switch-status").click(function(){ $.ajax({ url: '/account/switches/', data: {'toggle': 'status'} }); }); }); view.py @login_required def switches(request): toggle = request.GET.get('toggle', None) current_user = request.user update = Switches.objects.get(owner=current_user) if toggle == 'status': if update.status is True: update.status = False else: update.status = True update.save() return HttpResponse('') -
Excluding certain routes in Django with React Router?
I am currently building a React with a Django REST backend. I have come into this one little problem I can't get past that has to do with Routing. Here is my urls.py file. urlpatterns = [ url(r'^api/', include(router.urls)), url(r'^admin/', admin.site.urls), url(r'^djangojs/', include('djangojs.urls')), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^$', TemplateView.as_view(template_name='exampleapp/itworks.html')), url(r'^(?:.*)/?$', TemplateView.as_view(template_name='exampleapp/itworks.html')), ] Using this, it lets the react router do it's thing on the front end. For example, if I wanted to go to 127.0.0.1:8000/mentors then it will take me to the page I have set for React Router. However, doing API calls in the frontend also returns the react page rather than the API endpoint because of this. So whenever I remove the last line in the code above: url(r'^(?:.*)/?$', TemplateView.as_view(template_name='exampleapp/itworks.html')),, then it gets the API returned in JSON format successfully. Problem is now when I try to go to the links it will return the Django 404 page rather than the React page I set in the React Router. Is there anyway I can get the best of both worlds? -
What is difference between request.method = "POST" , "PUT", "DELETE" in django
I want to know about what is use of "POST" "PUT" "DELETE" in django and also want to know the difference between these terms. -
Flask-Login raises TypeError: 'int' object is not callable
I just write a flask login demo. @app.route('/reg/', methods=['GET', 'POST']) def reg(): username = request.form.get('username').strip() password = request.form.get('password').strip() if (username == '' or password == ''): return redirect_with_msg('/regloginpage/', u'用户名或密码不能为空', category='reglogin') user = User.query.filter_by(username=username).first() if (user != None): return redirect_with_msg('/regloginpage/', u'用户名已存在', category='reglogin') salt = '.'.join(random.sample('0123456789abcdfeghijklmnABCDEFG', 10)) m = hashlib.md5() str1 = (password + salt).encode('utf-8') m.update(str1) password = m.hexdigest() user = User(username, password, salt) db.session.add(user) db.session.commit() login_user(user) return redirect('/') And Traceback like this: TypeError: 'int' object is not callable File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/Users/apple/PycharmProjects/pinstagram/pinstagram/views.py", line 94, in login login_user(user) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask_login/utils.py", line 140, in login_user user_id = getattr(user, current_app.login_manager.id_attribute)() TypeError: 'int' object is not callable It makes me upset, someone can save me ? -
django relationship how to map an indirect relation in model
I have three models class Venue(models.Model): property_values = models.ManyToManyField('feature.PropertyValue') class Feature(models.Model): name = models.CharField(max_length=255, null=False, blank=False) class PropertyValue(models.Model): name = models.CharField(max_length=255, null=False, blank=False) feature = models.ForeignKey('Feature', null=False, blank=False) In this I want to be able to add feature to venue model saying that belongs to it via property value. -
Creating connection to social account does not work when connection already exists
Assume 2 local accounts DjangoUser1 DjangoUser2 And they both have access to TwitterAcct1 Doing the following results in no social account being connected to DjangoUser2: DjangoUser1 registers with username, optional email, password DjangoUser1 logs into Twitter and successfully creates connection DjangoUser1 logs out DjangoUser2 registers with username optional email, password DjangoUser2 logs into Twitter and is taken back to connection page with no connection Is there a way that this can work with django-allauth? -
Can I use bigchainDB server with django instead of using sqlite?
I am creating degree verification process using blockchain approach which contain six main enntities. By entities I mean to say consensus mechanism will evolve around these six entities, so for this I need to build a distributed database . Two approaches came into my mind One approach of achieving this is to completely built everything from scratch ,seperate database for each node in sqlite and then connect each node with some type of query Another approach is to use bigchainDB server which is a distributed database server based on blockchain. Now my question which approach is feasible? . I don't know whether bigchainDB server is compatible with django or not since they haven't mention anything about it in their docs If anyone have use bigchainDB please help me out . I am really confused which approach should I follow -
Python Django Bound Form not returning
I am trying to validate a form by using is_valid() method. form = RegisterForm(request.POST) if form.is_valid(): form.save() else: return (RegisterForm) if there is error, I want tot return Bounded Registerform but I am getting 'get' error. If i remove the if block it is returning 'None' type error. my question is how do i return a bounded form. -
Django, update rate, signals
class Thing (model.Models): name = models.CharField(max_length = 222) ratee = models.IntegerField(default = 0) ... class Rate(models.Model): thing = models.ForeignKey(Thing) user = models.ForeignKey(User) rate = models.IntegerField() If user evaluate the thing(give rate in Rate), I want to automatically calculate average and save to ratee in Thing. How to make it? -
Subprocess with 'While True' ends after 3640 iterations
I have a Django app that spawns a subprocess everytime there is a database insert. models.py # spawn subprocess to trigger tweepy # output of subprocess DOES NOT log to the console. def tweepy_tester(sender, **kwargs): if kwargs['created']: logger.error('tweepy trigger-start!') p = subprocess.Popen([sys.executable, "/Users/viseshprasad/PycharmProjects/Blood_e_Merry/loginsignup/tests.py"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) logger.error('tweepy trigger-over!') # use post_save to trigger tweepy later post_save.connect(tweepy_tester, sender=User) tests.py logger = logging.getLogger(__name__) # Create your tests here. def for_thread(): i = 0 while True: f = open('test.txt', 'a') f.write('Tweepy triggered ' + str(i) + '\n') # python will convert \n to os.linesep f.close() # you can omit in most cases as the destructor will call it i += 1 for_thread() The trigger happens fine but the subprocess only writes 3640 lines to the test.txt file, even though I have used while True: I am basically look for a subprocess to run non-stop after the trigger, as a separate thread and not disturbing the main thread. The purpose : I run my app with the usual python manage.py runserver. User signs-up -> database insert -> triggers my implementation of tweepy which keeps on streaming tweets and analyzing them non-stop on a different background thread so as to not interfere with the signup process. … -
Circular import between models and helpers in Django
I'm trying to add a post_save Signal in my Django app and am running into a circular import issue. helpers.py from tracker.models import Record def get_account_id(name): return name + '123' models.py from helpers import get_account_id class Record(models.Model): id = models.AutoField(primary_key=True) created_at = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=120, blank=True) matched_account_id = models.CharField(max_length=120, unique=False, blank=True) def find_matched_account(sender, instance, *args, **kwargs): instance.matched_account_id = get_account_id(instance.name) instance.save() pre_save.connect(find_matched_account, sender=Record) This is obviously a simplification but sums up the issue I'm running into. I could move the code in helpers into models but would prefer to store things like this in helpers because I'll end up using it in other places. -
How to set a cell not column or row in a datafram with color?
I have a dataframe with table style that I created : tableyy = final.style.set_table_attributes('border="" class = "dataframe table table-hover table-bordered"').set_precision(10).render() I have go through this Coloring Cells in Pandas , Conditionally change background color of specific cells, Conditionally format Python pandas cell, and Colour cells in pandas dataframe, I still not able to set a cell with color not the whole dataframe without any condition. Anyone have any ideas, I try this color code for one months already so hope can receive advise from anyone of you guys, thanks. -
eliminate duplicates in django
I'm trying to pick up 3 random numbers out of a list of 20 numbers. In views.py i've defined this variable: nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] In my template index.html: {{ nums|random }} - {{ nums|random }} - {{ nums|random }} I want to get 3 different numbers but i don't know which filter/tag to apply. I've tried if/else statements, for loops, (if there's a duplicate i want a redraw) but i'm not satisfied with the results and i'm pretty sure there's a simple filter to do that. Thanks for your help!